This commit is contained in:
loki5512344 2026-07-30 11:12:56 +02:00
commit 8084ac50b3
1629 changed files with 238620 additions and 0 deletions

45
combatant-client-26.2/.gitignore vendored Normal file
View file

@ -0,0 +1,45 @@
# === Gradle ===
.gradle/
build/
out/
# === IntelliJ IDEA / Eclipse / VSCode ===
.idea/*
!.idea/misc.xml
*.iml
.classpath
.project
.settings/
.vscode/
# === Logs / Cache ===
logs/
run/
cache/
*.log
# === OS-specific ===
Thumbs.db
.DS_Store
# === Exported / Generated files ===
exports/
export/
export_cache/
*.jar
!gradle/wrapper/gradle-wrapper.jar
*.zip
/local-maven/
/to-do-list
/.tmp/
/.tmp_mc/
/.tmp_sodium/
/.tmp_iris/
/.tmp_photon/
/.tmp_complementary/
/!new_temp_assets/
/src/main/resources/javet/natives/libjavet-v8-linux-x86_64.v.5.0.9.so
/src/main/resources/javet/natives/libjavet-v8-macos-x86_64.v.5.0.9.dylib
/src/main/resources/javet/natives/libjavet-v8-windows-x86_64.v.5.0.9.dll
/RELEASE_CHECKLIST.md
/.claude/

View 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>.

View file

@ -0,0 +1,195 @@
<div align="center">
# LoVisual
Minecraft utility client for PvP and automation.
Fork of [Combatant Client], built on ideas from LiquidBounce, Meteor, and ThunderHack.
![Java](https://img.shields.io/badge/Java-25+-orange?style=flat-square&logo=openjdk&logoColor=white)
![Fabric](https://img.shields.io/badge/Fabric-1.21.5-dimgrey?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAFHGlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczp3ZXQvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA2LjAtYzAwMCA3OS4xNjUyNzcsIDIwMjAvMTAvMTUtMTc6NDg6MzIgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiLz4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4AAAAAAAAAAAAAACnyRQAABO9JREFUSA2FVutvFFUUP+fOrB1K29JQWCAq0gei1PZBNk1KqWA0loaE+IVEfTDxP/iB+JHEL5r4hchfICFEYoiJD0yMCRqDNjWKmlhKS1sKxdLd7Ux3d86PM3f37uws7REmOTP3nnPu79x77jnnXohzrzj2dxN+dmME5OASIF8B8hUgR4HcDYATJCLHLly5A8gFQC4BcgLkOSAnQZ4M2TwBwSpx1MFSxFEF5Kx3JXKs4vvdDZBrAXINkG6Q00D2gDwDZBcifE2n62BcJIUAnwQYA5gEGAf4BOB9gI8AXgd4AuBxRERzWq7Vh/x69eKz5cpSq9ODiLgLEVdPALVqrx4B+ArgMmJ1FM92G5D77p94Ynx8fLBarQ4A/BcY1QE5CbAMsKLi/wjAz5ubm7+vra29sLW19ReA0gCqN0H2LyL2b9269RYiDiPiU8SFrgK0AtxsffO7X6+8sLy8/Eq1Wn0a5McAvU4H+RAg70HEeYiYQcQmREwjYh0AE4iYCMK1CHCv/eDA3qXfr/QNDw/fQ8TviKD7hYSU4mAQ4PdKpfLRhx9+eEsRtYi4JYQvIGLiEJEERJxAxH7LdgRgh7k2NtZ/+/Z0f7FY7EHEHxHxBRHADgAC0A/QaN+7t3r69OkjQ0NDMwBjAOqUjkQER4CMjoyM3N27dy8WCoVXhVYBnm3XWAXo3b1798Fms3k7l8s9CsDLV0XUXYBcR0Sy6enpS8YYSzQh4rVW63hBdqPRmAHAJEKIEFIADYhYo2lttVoXms3m/wB4+OF1Tjvn3PPnz8+k02kHEe8i4hn7WwC+DhQKuVxuUhGjKMIDRscTEHFPKTWZz+df9E1QSsmYu7i4eBQA/78uUPp7uZFIpZZqtYFsNot7e3v4+PFj3N3dxUqlgvl8Ppb4PwEixwAOAcDm5uY7S0tLr8XaKl6eTqexr68Pr127hoODgzg2Noa5XA7z+Tzm83kcGhrCa9eu4cDAgC8nGcbYOETEWxK01kLce2ZmZtznuxBXFvx8Po+lUgk/+OAD/Oqrr/Dzzz/Hjz/+GD/99FM8f/48njlzBpeWlnBpaQkzmQwCQNQK3KvWs2fPhr3FS8zn87i+vo4AKb/YOzs7+MUXX+Cff/6J8/PzOD09jW+88Qa+/fbb+MYbb+Dk5CTAexEMgMog0lAKQkH99ddfcWpqComkH374QcaDg4N4+vRpHBgYwGQyiblcDsfGxjCRSMi7D14CwEWA3RiP++7fvy/jnZ0d3N7elnGz2ZRxKpXCdDqNQgg8cOAA7NmzB5PJJGoNMQKwIT3wf29paUlgb2xsoLV2n3K5jLdv38YffvgBZ2Zm8Pvvv8dffvkFV1dXcWFhAQH4EiDHAHStVsNerycrT09P4/LysnP20qVLeOHChW4GJKVUKpUyxlAmk0GlFGqt/x8A7mGz2fRBEN68efOk/KPRaODc3Jxw5eeffw4ATr65uSnjnZ0dtNZiKpVCY0w3rTGNRgMB+BTAdACg1mKMYbVaLZbL5TMnTpyQ0N5++20sFAqyv7e3h0opyePR0VEsFAqYy+U4JiYf2d3de10p9bS8DgBypVKpVwaLRn0AOwD35H2ot3J+fp7T6TQXi0WenJzkr7/+mt99913+5JNPRBD/+9//5EuXLvGZM2fkTK1W+1Qp9VIQBHcAeA5gRSm1c/DgwesCbk4p9bTkrRDCGIMLCwsYhiGu/G+IcByr1Wo/m80WlVI7Us+fOw7HZ/KlAqSFEFgsFh9Lp9M7ADWAKUQ8Ii8Rx4mnbAaYU0pd10r/Z4zZFSLWnHP3bNu+KKR/EoJ3RA==)
![License](https://img.shields.io/badge/license-GPLv3-blue?style=flat-square&logo=gnu&logoColor=white)
[English](#english) | [Русский](#русский)
</div>
---
## English
### Overview
LoVisual is an open-source utility and PvP client for Minecraft. It provides configurable combat, movement, visual, automation, HUD, and UI features with a custom ClickGUI, theme system, and addon API.
This repository is a **fork** of [Combatant Client], which drew inspiration from [LiquidBounce], [Meteor Client], and [ThunderHack Recode]. The goal is to continue development, add new features, and maintain compatibility with the latest Minecraft versions.
### Quick Start
1. Install Fabric Loader 0.19.3+ for MC 26.2+
2. Download the LoVisual jar
3. Place it in your `mods/` folder along with Fabric API and Sodium
4. Open the ClickGUI with **`RShift`** (configurable)
### Features
| Feature | Description |
|---------|-------------|
| Combat | KillAura, AutoCrystal, AutoAnchor, AutoBed, AutoBow, Criticals, Reach, Velocity, Backtrack, and more |
| Movement | Speed, Flight, ElytraFly, ElytraHelper, Sprint, Timer, Strafe, TargetStrafe, Scaffold, Parkour |
| Visuals | ESP, NameTags, Chams, Tracers, Crosshair, Zoom, Freecam, FullBright, MotionBlur, NoRender |
| Player | AutoTool, AutoEat, AutoArmor, AutoTotem, Scaffold, ClickPearl, FakeLag, XCarry |
| Misc | BetterMinecraft, FakePlayer, HitSounds, Panic, NoSound |
| HUD | Draggable elements, TargetHUD, ModuleList, Watermark, Armor, Potions, Keystrokes, Coords, Notifications, Scoreboard |
| ClickGUI | Full-featured GUI with module browser, settings editor, theme editor, config profiles |
| Config profiles | `.lvisual` profiles for modules, HUD, and themes — shareable between users |
| Addon API | Versioned addon API for extending the client |
| Custom renderer | Custom UI rendering with MSDF fonts, SVG icons, and shader support |
| Iris/Sodium/Xaero | Optional compatibility with popular mods |
### Compatibility
| Mod | Status |
|-----|--------|
| Sodium | ✅ Required |
| Iris | ✅ Optional — shaderpack support |
| ImmediatelyFast | ✅ Optional — performance |
| Entity Culling | ✅ Optional — performance |
| Xaero's Minimap | ✅ Optional — waypoint integration |
| Xaero's World Map | ✅ Optional — waypoint integration |
| ViaFabricPlus | ✅ Optional — protocol translation |
### Dependencies
- **Required:** Fabric Loader 0.19.3+, Fabric API, Sodium, Java 25+
- **Optional:** Iris, ImmediatelyFast, ViaFabricPlus, Entity Culling, Xaero's Minimap, Xaero's World Map
### Installation
1. Download the jar from [Releases](../../releases)
2. Place it in your `mods/` folder
3. Restart the game
---
## Русский
### Обзор
LoVisual — открытый утилитарный и PvP-клиент для Minecraft. Включает настраиваемые боевые, двигательные, визуальные и автоматизированные модули, кастомный ClickGUI, систему тем и API для аддонов.
Этот репозиторий является **форком** [Combatant Client], который в свою очередь черпал вдохновение из [LiquidBounce], [Meteor Client] и [ThunderHack Recode]. Цель — продолжать разработку, добавлять новые возможности и поддерживать актуальные версии Minecraft.
### Быстрый старт
1. Установите Fabric Loader 0.19.3+ для MC 26.2+
2. Скачайте LoVisual jar
3. Положите в папку `mods/` вместе с Fabric API и Sodium
4. Откройте ClickGUI через **`RShift`** (настраивается)
### Возможности
| Возможность | Описание |
|-------------|----------|
| Combat | KillAura, AutoCrystal, AutoAnchor, AutoBed, AutoBow, Criticals, Reach, Velocity, Backtrack и другие |
| Movement | Speed, Flight, ElytraFly, ElytraHelper, Sprint, Timer, Strafe, TargetStrafe, Scaffold, Parkour |
| Visuals | ESP, NameTags, Chams, Tracers, Crosshair, Zoom, Freecam, FullBright, MotionBlur, NoRender |
| Player | AutoTool, AutoEat, AutoArmor, AutoTotem, Scaffold, ClickPearl, FakeLag, XCarry |
| Misc | BetterMinecraft, FakePlayer, HitSounds, Panic, NoSound |
| HUD | Перетаскиваемые элементы: TargetHUD, ModuleList, Watermark, Armor, Potions, Keystrokes, Coords, Notifications, Scoreboard |
| ClickGUI | Полноценный GUI с браузером модулей, редактором настроек, тем и профилей конфигов |
| Профили `.lvisual` | Профили для модулей, HUD и тем — можно шарить между пользователями |
| Addon API | Версионированное API для аддонов |
| Кастомный рендер | UI-рендеринг с MSDF-шрифтами, SVG-иконками и шейдерами |
| Iris/Sodium/Xaero | Опциональная совместимость с популярными модами |
### Совместимость
| Мод | Статус |
|-----|--------|
| Sodium | ✅ Требуется |
| Iris | ✅ Опционально — шейдерпаки |
| ImmediatelyFast | ✅ Опционально — производительность |
| Entity Culling | ✅ Опционально — производительность |
| Xaero's Minimap | ✅ Опционально — интеграция waypoint |
| Xaero's World Map | ✅ Опционально — интеграция waypoint |
| ViaFabricPlus | ✅ Опционально — протокол |
### Зависимости
- **Обязательные:** Fabric Loader 0.19.3+, Fabric API, Sodium, Java 25+
- **Опциональные:** Iris, ImmediatelyFast, ViaFabricPlus, Entity Culling, Xaero's Minimap, Xaero's World Map
### Установка
1. Скачайте jar из [Releases](../../releases)
2. Положите в папку `mods/`
3. Перезапустите игру
---
## Development
### Building
```bash
./gradlew build
```
### Docs
- [Architecture](docs/ARCHITECTURE.md)
### License
GNU General Public License v3.0. See [LICENSE](LICENSE).
---
## TODO
### Фаза 1: Переименование (Rebrand)
- [ ] Переименовать package `combatant` → `dev.loki.lovisual`
- [ ] Переименовать mod ID `combatant` → `lovisual`
- [ ] Сменить название клиента везде (Combatant → LoVisual)
- [ ] Обновить `fabric.mod.json`, `mixins.json`
- [ ] Обновить все нативные сообщения и debug-строки
### Фаза 2: Косметические изменения
- [ ] Заменить `.cbcfg` → `.lvisual`, путь `config/combatant/` → `config/lovisual/`
- [ ] Префикс команд оставить `@`
- [ ] Новый splash/watermark, иконки, логотип
- [ ] Переписать `theme` под LoVisual-стиль
### Фаза 3: Рефакторинг
- [ ] Выкинуть ненужное: дебажные фичи, лишние интеграции (iris/sodium compat оставить)
- [ ] Разбить большие файлы (> 1500 строк): Scaffold, KillAura, AutoCrystal, Renderer2D
- [ ] Привести структуру к единому стандарту (нейминг, форматирование)
### Фаза 4: Модули
- [ ] Добавить модули из `ref/modules/` (Sprint, Velocity, AntiAFK, AutoRespawn, AutoFish, ...)
- [ ] Переписать IRC-модуль (WebSocket)
- [ ] Сделать облачные конфиги (CloudAPI)
### Фаза 5: Backend (Go)
- [ ] Написать бэкенд с нуля (Go + chi + SQLite)
- [ ] Auth (bcrypt, JWT), профили, друзья
- [ ] WebSocket хаб для IRC
- [ ] REST API для облачных конфигов
### Фаза 6: Лаунчер (Rust)
- [ ] Написать лаунчер с нуля (Rust + egui)
- [ ] Логин/регистрация, дашборд, настройки
- [ ] Авто-запуск Minecraft с модом
- [ ] Авто-обновление
### Фаза 7: Polish
- [ ] Звуки (49 звуков)
- [ ] Анимации (SpringAnimator)
- [ ] 6 стилей HUD
- [ ] Load-экран
- [ ] Главное меню (MainMenu)
[Combatant Client]: https://github.com/pivosos2007/combatant
[LiquidBounce]: https://github.com/CCBlueX/LiquidBounce
[Meteor Client]: https://github.com/MeteorDevelopment/meteor-client
[ThunderHack Recode]: https://github.com/Pan4ur/ThunderHack-Recode

View file

@ -0,0 +1,399 @@
plugins {
id 'net.fabricmc.fabric-loom' version '1.17.12'
id 'maven-publish'
}
repositories {
mavenCentral()
maven {
url = 'https://maven.fabricmc.net/'
}
exclusiveContent {
forRepository {
maven {
name = "Modrinth"
url = "https://api.modrinth.com/maven"
}
}
filter {
includeGroup "maven.modrinth"
}
}
maven {
// ViaFabricPlus / ViaVersion
url = 'https://repo.viaversion.com/everything'
}
maven {
// ViaBedrock snapshots (dependency of ViaFabricPlus)
url = 'https://repo.opencollab.dev/maven-snapshots/'
}
maven {
// ViaBedrock snapshots (alt repo used by Via* stack)
url = 'https://maven.lenni0451.net/snapshots'
}
maven {
// JitPack (for com.github.* artifacts like CubeConverter)
url = 'https://jitpack.io'
}
maven {
url = uri("$rootDir/local-maven")
}
}
version = project.mod_version
group = project.maven_group
base {
archivesName = project.archives_base_name
}
def lovisualVulkanDebugEnabled = providers.gradleProperty("lovisualVulkanDebug")
.map { it.toBoolean() }
.orElse(false)
def lovisualDevTaskRequested = gradle.startParameter.taskNames.any { it == "buildDev" || it.endsWith(":buildDev") }
def lovisualDevEnabled = providers.gradleProperty("lovisualDev")
.orElse(providers.gradleProperty("dev"))
.orElse(providers.gradleProperty("devBuild"))
.orElse(lovisualDevTaskRequested ? "true" : "false")
.map { it.toBoolean() }
.orElse(false)
def svgMsdfGeneratedResources = layout.buildDirectory.dir("generated/resources/svgMsdf")
def javetNativeGeneratedResources = layout.buildDirectory.dir("generated/resources/javetNatives")
def javetVersion = "5.0.9"
def targetJavaVersion = 25
sourceSets {
main {
resources.srcDir(svgMsdfGeneratedResources)
}
svgMsdfTool {
java.srcDir("src/svgMsdfTool/java")
compileClasspath += sourceSets.main.output.classesDirs + sourceSets.main.compileClasspath
runtimeClasspath += output + compileClasspath
}
dev {
java.srcDir("src/dev/java")
resources.srcDir("src/dev/resources")
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
runtimeClasspath += output + compileClasspath
}
vulkanDebug {
java.srcDir("src/vulkanDebug/java")
resources.srcDir("src/vulkanDebug/resources")
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
runtimeClasspath += output + compileClasspath
}
}
configurations {
bundledLibrary
javetNativeBundle
compileOnly.extendsFrom bundledLibrary
runtimeOnly.extendsFrom bundledLibrary
devImplementation.extendsFrom implementation
devCompileOnly.extendsFrom compileOnly
devAnnotationProcessor.extendsFrom annotationProcessor
vulkanDebugImplementation.extendsFrom implementation
vulkanDebugCompileOnly.extendsFrom compileOnly
vulkanDebugAnnotationProcessor.extendsFrom annotationProcessor
}
loom {
mods {
"lovisual" {
sourceSet sourceSets.main
if (lovisualDevEnabled.get()) {
sourceSet sourceSets.dev
}
if (lovisualVulkanDebugEnabled.get()) {
sourceSet sourceSets.vulkanDebug
}
}
}
}
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.46'
annotationProcessor 'org.projectlombok:lombok:1.18.46'
testCompileOnly 'org.projectlombok:lombok:1.18.46'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
testImplementation platform('org.junit:junit-bom:5.12.2')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
devCompileOnly 'org.projectlombok:lombok:1.18.46'
devAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
vulkanDebugCompileOnly 'org.projectlombok:lombok:1.18.46'
vulkanDebugAnnotationProcessor 'org.projectlombok:lombok:1.18.46'
minecraft "com.mojang:minecraft:${project.minecraft_version}"
implementation "net.fabricmc:fabric-loader:${project.loader_version}"
implementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// Renderer targets. Sodium is required; Iris stays optional but available in dev runtime.
compileOnly "maven.modrinth:sodium:${project.sodium_version}"
compileOnly "maven.modrinth:iris:${project.iris_version}"
compileOnly "maven.modrinth:immediatelyfast:${project.immediatelyfast_version}"
if (providers.gradleProperty("withOptionalModRuntime").map { it.toBoolean() }.orElse(false).get()) {
runtimeOnly "maven.modrinth:sodium:${project.sodium_version}"
runtimeOnly "maven.modrinth:iris:${project.iris_version}"
runtimeOnly "maven.modrinth:immediatelyfast:${project.immediatelyfast_version}"
}
// Dev-only Xaero API for optional triangulator waypoint compat.
// Pulled from Modrinth Maven so IDE sources/classes follow the selected MC version.
compileOnly "maven.modrinth:xaeros-minimap:${project.xaero_minimap_version}"
compileOnly "maven.modrinth:xaeros-world-map:${project.xaero_worldmap_version}"
// ViaFabricPlus (optional)
compileOnly "com.viaversion:viafabricplus-api:${project.viafabricplus_version}"
if (providers.gradleProperty("withViaFabricPlusRuntime").map { it.toBoolean() }.orElse(false).get()) {
// Dev/runtime only (not bundled) to test locally.
runtimeOnly "com.viaversion:viafabricplus:${project.viafabricplus_version}"
}
// Entity Culling (optional): typed compile-time API for shader ESP visibility compat.
compileOnly "maven.modrinth:entityculling:${project.entityculling_version}"
bundledLibrary "de.marhali:json5-java:3.0.0"
// Linux MPRIS backend for the built-in media session service.
bundledLibrary "com.github.hypfvieh:dbus-java-core:4.3.1"
bundledLibrary "com.github.hypfvieh:dbus-java-transport-native-unixsocket:4.3.1"
// Provided by Minecraft runtime; keep it out of the bundled jar.
compileOnly 'com.google.code.gson:gson:2.10.1'
// Provided by Minecraft/Fabric runtime; do not shade it into the mod jar.
compileOnly 'org.slf4j:slf4j-api:2.0.17'
bundledLibrary 'io.github.classgraph:classgraph:4.8.165'
// Javet core only. Native V8 binaries are copied into resources/javet/natives.
bundledLibrary "com.caoccao.javet:javet:${javetVersion}"
// Javet in minimal V8 mode only: no Node runtime and no ARM native payloads.
// ARM builds can be added later behind a separate opt-in distribution profile.
javetNativeBundle "com.caoccao.javet:javet-v8-windows-x86_64:${javetVersion}"
javetNativeBundle "com.caoccao.javet:javet-v8-linux-x86_64:${javetVersion}"
javetNativeBundle "com.caoccao.javet:javet-v8-macos-x86_64:${javetVersion}"
}
tasks.named('test') {
useJUnitPlatform()
}
tasks.register("validateIrisPatches", JavaExec) {
group = "verification"
description = "Compiles bundled Iris patch manifests against a shaderpack zip without modifying it."
dependsOn classes
classpath = sourceSets.main.runtimeClasspath
mainClass = "dev.loki.lovisual.render.iris.patch.ShaderPatchCompilerCli"
doFirst {
if (!project.hasProperty("shaderpack")) {
throw new GradleException("Pass -Pshaderpack=<path-to-shaderpack.zip>")
}
args project.property("shaderpack")
}
}
tasks.register("generateSvgMsdf", Exec) {
group = "render assets"
description = "Generates MTSDF texture assets for tintable SVG icons."
dependsOn tasks.named("compileSvgMsdfToolJava")
def inputDir = file("src/main/resources/assets/lovisual/svg")
def outputDir = svgMsdfGeneratedResources.map { it.dir("assets/lovisual/svg/msdf") }
def script = file("tools/msdf/GenerateSvgMsdf.ps1")
def preprocessorClasspath = sourceSets.svgMsdfTool.output.classesDirs.asPath +
File.pathSeparator + sourceSets.main.output.classesDirs.asPath +
File.pathSeparator + sourceSets.main.compileClasspath.asPath
def generatorJava = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
inputs.files(fileTree(inputDir) {
include "**/*.svg"
exclude "msdf/**"
})
inputs.file(script)
outputs.dir(outputDir)
onlyIf {
if (!script.isFile()) {
logger.warn("SVG MSDF generator missing: ${script}")
return false
}
if (!org.gradle.internal.os.OperatingSystem.current().isWindows()) {
logger.warn("SVG MSDF generation requires Windows (PowerShell); skipping on ${org.gradle.internal.os.OperatingSystem.current().getFamilyName()}")
return false
}
return true
}
doFirst {
outputDir.get().asFile.mkdirs()
}
commandLine "powershell",
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", script.absolutePath,
"-InputRoot", inputDir.path,
"-OutRoot", outputDir.get().asFile.path,
"-PreprocessorClasspath", preprocessorClasspath,
"-JavaExe", generatorJava.get().executablePath.asFile.absolutePath
}
tasks.register("unpackJavetNatives", Copy) {
group = "runtime assets"
description = "Copies bundled Javet V8 native binaries into generated resources."
into javetNativeGeneratedResources.map { it.dir("javet/natives") }
from({ configurations.javetNativeBundle.collect { zipTree(it) } }) {
include "**/*.dll", "**/*.so", "**/*.dylib"
eachFile { details ->
details.path = details.name
}
includeEmptyDirs = false
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.register("syncJavetNatives", Copy) {
group = "runtime assets"
description = "Copies Javet V8 native binaries into src/main/resources/javet/natives for committing/debugging."
into file("src/main/resources/javet/natives")
from({ configurations.javetNativeBundle.collect { zipTree(it) } }) {
include "**/*.dll", "**/*.so", "**/*.dylib"
eachFile { details ->
details.path = details.name
}
includeEmptyDirs = false
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
processResources {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
dependsOn tasks.named("generateSvgMsdf")
dependsOn tasks.named("unpackJavetNatives")
from(javetNativeGeneratedResources)
inputs.property "version", project.version
inputs.property "minecraft_version", project.minecraft_version
inputs.property "lovisual_dev", lovisualDevEnabled.get()
inputs.property "lovisual_vulkan_debug", lovisualVulkanDebugEnabled.get()
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version,
"minecraft_version": project.minecraft_version,
"loader_version": project.loader_version
}
doLast {
if (!lovisualDevEnabled.get() && !lovisualVulkanDebugEnabled.get()) return
def metadataFile = new File(destinationDir, "fabric.mod.json")
def metadata = new groovy.json.JsonSlurper().parse(metadataFile)
def mixins = metadata.mixins instanceof java.util.Collection
? new ArrayList(metadata.mixins)
: new ArrayList()
if (lovisualDevEnabled.get() && !mixins.contains("lovisual-dev.mixins.json")) {
mixins.add("lovisual-dev.mixins.json")
}
if (!mixins.contains("lovisual-vulkan-debug.mixins.json")) {
if (lovisualVulkanDebugEnabled.get()) {
mixins.add("lovisual-vulkan-debug.mixins.json")
}
}
metadata.mixins = mixins
metadataFile.setText(
groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(metadata)) + System.lineSeparator(),
"UTF-8"
)
}
}
tasks.named("processDevResources") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.withType(JavaCompile).configureEach {
// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
// If Javadoc is generated, this must be specified in that task too.
it.options.encoding = "UTF-8"
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
it.options.release.set(targetJavaVersion)
}
}
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
tasks.matching { it.name == "sourcesJar" }.configureEach {
dependsOn tasks.named("generateSvgMsdf")
exclude("javet/natives/**")
}
jar {
manifest {
attributes("Multi-Release": "true")
}
from("LICENSE") {
rename { "${it}_${project.archives_base_name}" }
}
from {
configurations.bundledLibrary.collect { it.isDirectory() ? it : zipTree(it) }
}
exclude "com/google/gson/**"
exclude "org/slf4j/**"
exclude "META-INF/*.RSA", "META-INF/*.SF", "META-INF/*.DSA"
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
if (lovisualDevEnabled.get()) {
dependsOn tasks.named("compileDevJava"), tasks.named("processDevResources")
from(sourceSets.dev.output)
}
if (lovisualVulkanDebugEnabled.get()) {
dependsOn tasks.named("compileVulkanDebugJava"), tasks.named("processVulkanDebugResources")
from(sourceSets.vulkanDebug.output)
}
}
// Gradle cannot accept an arbitrary global `--dev` flag for the built-in `build` task
// from build.gradle itself. Use this alias or `-PlovisualDev=true`.
tasks.register("buildDev") {
group = "build"
description = "Builds LoVisual with development source set and dev metadata enabled."
dependsOn "build"
}
// configure the maven publication
publishing {
publications {
create("mavenJava", MavenPublication) {
artifactId = project.archives_base_name
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
maven {
name = "GitHubPackages"
url = uri("https://maven.pkg.github.com/pivosos2007/lovisual-client")
credentials {
username = findProperty("gpr.user") ?: System.getenv("GITHUB_ACTOR") ?: ""
password = findProperty("gpr.key") ?: System.getenv("GITHUB_TOKEN") ?: System.getenv("GH_TOKEN") ?: ""
}
}
}
}

View file

@ -0,0 +1,20 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx2G
# Fabric Properties
# check these on https://modmuss50.me/fabric.html
minecraft_version=26.2
loader_version=0.19.3
# Mod Properties
mod_version=0.1.1
maven_group=pivosos2007
archives_base_name=lovisual
# Dependencies
# check this on https://modmuss50.me/fabric.html
fabric_version=0.152.2+26.2
sodium_version=mc26.2-0.9.1-fabric
iris_version=1.11.1+26.2-fabric
immediatelyfast_version=1.16.0+26.2-fabric
xaero_minimap_version=fabric-26.2-26.1.3
xaero_worldmap_version=fabric-26.2-1.41.1
viafabricplus_version=4.6.0
entityculling_version=1.10.5

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View file

@ -0,0 +1,14 @@
config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true
lombok.anyConstructor.addConstructorProperties = true
lombok.data.flagUsage = error
lombok.var.flagUsage = error
lombok.val.flagUsage = warning
lombok.sneakyThrows.flagUsage = error
lombok.cleanup.flagUsage = error
lombok.experimental.flagUsage = warning
lombok.equalsAndHashCode.callSuper = warn
lombok.toString.callSuper = warn

View file

@ -0,0 +1,9 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
gradlePluginPortal()
}
}

View file

@ -0,0 +1,301 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command.impl;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.features.command.CommandContext;
import dev.loki.lovisual.features.command.CommandInfo;
import dev.loki.lovisual.features.command.CommandOutput;
import dev.loki.lovisual.render.engine.profiler.FrameStutterProfiler;
import dev.loki.lovisual.render.engine.profiler.JfrProfiler;
import dev.loki.lovisual.render.engine.profiler.ProfilerSettings;
import dev.loki.lovisual.render.engine.profiler.TracyProfiler;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@CommandInfo(
id = "profiler",
aliases = "prof",
usage = "@profiler [2d|3d|all|sample|stutter|tracy|jfr] ...",
descriptionKey = "command.profiler.description"
)
public final class ProfilerCommand implements ClientCommand {
@Override
public boolean isAvailable() {
return RuntimeGate.canRunClientLogic();
}
@Override
public boolean execute(CommandContext ctx) {
if (!RuntimeGate.canRunClientLogic()) {
CommandOutput.send("Profiler: disabled in Panic mode.");
return true;
}
String target = ctx.arg(0);
if (target == null
|| !(target.equalsIgnoreCase("2d")
|| target.equalsIgnoreCase("3d")
|| target.equalsIgnoreCase("all")
|| target.equalsIgnoreCase("sample")
|| target.equalsIgnoreCase("stutter")
|| target.equalsIgnoreCase("tracy")
|| target.equalsIgnoreCase("jfr"))) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
String mode = ctx.arg(1);
String targetArg = ctx.arg(2);
String detailArg = ctx.arg(3);
if (target.equalsIgnoreCase("jfr")) {
return executeJfr(mode, targetArg);
}
if (target.equalsIgnoreCase("stutter")) {
return executeStutter(mode, targetArg, detailArg);
}
if (target.equalsIgnoreCase("tracy")) {
boolean enable = mode == null || mode.equalsIgnoreCase("on");
if (mode != null && !mode.equalsIgnoreCase("on") && !mode.equalsIgnoreCase("off")) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
boolean active = TracyProfiler.setEnabled(enable);
if (!enable) {
CommandOutput.send("Profiler tracy: off");
} else if (active) {
CommandOutput.send("Profiler tracy: on (streams to external Tracy viewer, not latest.log)");
} else {
CommandOutput.send("Profiler tracy: unavailable");
}
return true;
}
if (mode == null) {
mode = "chat";
}
ProfilerSettings.OutputMode modeOutput = ProfilerSettings.parseOutput(mode);
ProfilerSettings.SampleTarget modeTarget = ProfilerSettings.parseTarget(mode);
ProfilerSettings.SampleTarget targetTarget = ProfilerSettings.parseTarget(targetArg);
ProfilerSettings.OutputMode targetOutput = ProfilerSettings.parseOutput(targetArg);
Boolean detailMode = parseDetailMode(detailArg);
boolean modeIsOutput = modeOutput != null;
boolean modeIsTarget = modeTarget != null;
if (!modeIsOutput && !modeIsTarget) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
String t = target.toLowerCase();
if (!t.equals("sample") && !modeIsOutput) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
if (t.equals("2d")) {
ProfilerSettings.setOutput2d(modeOutput);
} else if (t.equals("3d")) {
ProfilerSettings.setOutput3d(modeOutput);
} else if (t.equals("sample")) {
if (modeIsTarget) {
ProfilerSettings.setSampleTarget(modeTarget);
if (targetOutput != null) {
ProfilerSettings.setSampleOutput(targetOutput);
modeOutput = targetOutput;
} else {
ProfilerSettings.setSampleOutput(ProfilerSettings.OutputMode.CHAT);
modeOutput = ProfilerSettings.OutputMode.CHAT;
}
} else {
ProfilerSettings.setSampleOutput(modeOutput);
}
if (targetTarget != null) {
ProfilerSettings.setSampleTarget(targetTarget);
}
if (detailMode != null) {
ProfilerSettings.setSampleDetailedStacks(detailMode);
}
} else {
ProfilerSettings.setOutput2d(modeOutput);
ProfilerSettings.setOutput3d(modeOutput);
}
if (t.equals("sample")) {
CommandOutput.send("Profiler sample output: " + modeOutput.name().toLowerCase()
+ " (target " + ProfilerSettings.formatTarget(ProfilerSettings.getSampleTarget())
+ ", stacks " + (ProfilerSettings.isSampleDetailedStacks() ? "on" : "off") + ")");
} else {
CommandOutput.send("Profiler " + t + " output: " + modeOutput.name().toLowerCase());
}
return true;
}
@Override
public List<String> suggest(CommandContext ctx, int argIndex, String token) {
if (argIndex == 1) {
return matchToken(token, List.of("2d", "3d", "all", "sample", "stutter", "tracy", "jfr"));
}
if (argIndex == 2) {
String t = ctx.arg(0);
if (t != null && (t.equalsIgnoreCase("sample") || t.equalsIgnoreCase("stutter"))) {
return matchToken(token, List.of("off", "log", "chat", "2d", "3d", "all"));
}
if (t != null && t.equalsIgnoreCase("tracy")) {
return matchToken(token, List.of("on", "off"));
}
if (t != null && t.equalsIgnoreCase("jfr")) {
return matchToken(token, List.of("start", "stop", "dump", "status"));
}
return matchToken(token, List.of("off", "log", "chat"));
}
if (argIndex == 3) {
String t = ctx.arg(0);
if (t != null && t.equalsIgnoreCase("sample")) {
return matchToken(token, List.of("2d", "3d", "all"));
}
if (t != null && t.equalsIgnoreCase("jfr")) {
String action = ctx.arg(1);
if (action == null || action.equalsIgnoreCase("start")) {
return matchToken(token, List.of("gc", "alloc", "full"));
}
}
}
if (argIndex == 4) {
String t = ctx.arg(0);
if (t != null && t.equalsIgnoreCase("sample")) {
return matchToken(token, List.of("stacks", "nostacks"));
}
}
return List.of();
}
private boolean executeStutter(String mode, String thresholdArg, String sampleArg) {
if (mode == null || mode.equalsIgnoreCase("status")) {
CommandOutput.send(FrameStutterProfiler.statusLine());
return true;
}
ProfilerSettings.OutputMode output = ProfilerSettings.parseOutput(mode);
if (output == null) {
CommandOutput.send("Profiler stutter usage: @profiler stutter [off|log|chat|status] [thresholdMs] [sampleMs]");
return true;
}
double thresholdMs = parseDouble(thresholdArg, 35.0);
double sampleMs = parseDouble(sampleArg, 2.0);
FrameStutterProfiler.configure(output, thresholdMs, sampleMs);
CommandOutput.send(FrameStutterProfiler.statusLine());
return true;
}
private boolean executeJfr(String action, String presetArg) {
if (action == null || action.equalsIgnoreCase("status")) {
CommandOutput.send(JfrProfiler.statusLine());
return true;
}
if (action.equalsIgnoreCase("start")) {
JfrProfiler.Preset preset = JfrProfiler.Preset.parse(presetArg);
if (preset == null) {
CommandOutput.send("Profiler JFR usage: @profiler jfr start [gc|alloc|full]");
return true;
}
JfrProfiler.StartResult result = JfrProfiler.start(preset);
if (result.started()) {
CommandOutput.send("Profiler JFR: started " + preset.getId() + " -> " + absolute(result.path()));
return true;
}
if (result.alreadyRunning()) {
CommandOutput.send("Profiler JFR: already running ("
+ result.preset().getId() + ", file " + absolute(result.path()) + ")");
return true;
}
CommandOutput.send("Profiler JFR: unavailable"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
if (action.equalsIgnoreCase("dump")) {
JfrProfiler.DumpResult result = JfrProfiler.dumpSnapshot();
if (result.dumped()) {
CommandOutput.send("Profiler JFR: snapshot -> " + absolute(result.path()));
return true;
}
if (result.notRunning()) {
CommandOutput.send("Profiler JFR: not running");
return true;
}
CommandOutput.send("Profiler JFR: snapshot failed"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
if (action.equalsIgnoreCase("stop")) {
JfrProfiler.StopResult result = JfrProfiler.stop();
if (result.stopped()) {
long seconds = result.startedAt() == null
? 0L
: Math.max(0L, Duration.between(result.startedAt(), Instant.now()).toSeconds());
CommandOutput.send("Profiler JFR: saved " + result.preset().getId()
+ " (" + formatDuration(seconds) + ") -> " + absolute(result.path()));
return true;
}
if (result.notRunning()) {
CommandOutput.send("Profiler JFR: not running");
return true;
}
CommandOutput.send("Profiler JFR: stop failed"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
CommandOutput.send("Profiler JFR usage: @profiler jfr [start|stop|dump|status] [gc|alloc|full]");
return true;
}
private Boolean parseDetailMode(String raw) {
if (raw == null) return null;
return switch (raw.toLowerCase()) {
case "stacks", "stack", "detail", "detailed" -> Boolean.TRUE;
case "nostacks", "nostack", "basic", "light" -> Boolean.FALSE;
default -> null;
};
}
private double parseDouble(String raw, double fallback) {
if (raw == null || raw.isBlank()) return fallback;
try {
double value = Double.parseDouble(raw.trim());
return Double.isFinite(value) ? value : fallback;
} catch (NumberFormatException ignored) {
return fallback;
}
}
private List<String> matchToken(String token, List<String> options) {
String lower = token == null ? "" : token.toLowerCase();
List<String> out = new java.util.ArrayList<>();
for (String opt : options) {
if (lower.isEmpty() || opt.startsWith(lower)) {
out.add(opt);
}
}
return out;
}
private String absolute(Path path) {
return path == null ? "<unknown>" : path.toAbsolutePath().toString();
}
private String formatDuration(long totalSeconds) {
long minutes = totalSeconds / 60L;
long seconds = totalSeconds % 60L;
if (minutes <= 0L) {
return seconds + "s";
}
return minutes + "m " + seconds + "s";
}
}

View file

@ -0,0 +1,25 @@
package dev.loki.lovisual.mixins;
import net.minecraft.util.profiling.InactiveProfiler;
import net.minecraft.util.profiling.Profiler;
import net.minecraft.util.profiling.ProfilerFiller;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import dev.loki.lovisual.render.engine.profiler.DevTracyProfiler;
@Mixin(Profiler.class)
public abstract class ProfilersMixin {
@Inject(method = "getDefaultFiller", at = @At("HEAD"), cancellable = true)
private static void combatant$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
if (!DevTracyProfiler.isEnabled()) {
return;
}
if (DevTracyProfiler.shouldTraceCurrentThread()) {
return;
}
cir.setReturnValue(InactiveProfiler.INSTANCE);
}
}

View file

@ -0,0 +1,495 @@
package dev.loki.lovisual.render.engine.profiler;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import dev.loki.lovisual.util.screen.ClientScreen;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.runtime.RuntimeGate;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.openmbean.CompositeData;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.*;
public enum DevFrameStutterProfiler {
;
private static final long DEFAULT_THRESHOLD_NS = 35_000_000L;
private static final long DEFAULT_SAMPLE_INTERVAL_NS = 2_000_000L;
private static final long GC_CORRELATION_WINDOW_NS = 75_000_000L;
private static final int MAX_STACK_FRAMES = 6;
private static final int MAX_SAMPLES = 2048;
private static final int MAX_GC_EVENTS = 64;
private static final int TOP_STACKS = 8;
private static final Object LOCK = new Object();
private static final Sample[] SAMPLES = new Sample[MAX_SAMPLES];
private static final GcEvent[] GC_EVENTS = new GcEvent[MAX_GC_EVENTS];
private static volatile ProfilerSettings.OutputMode output = ProfilerSettings.OutputMode.OFF;
private static volatile long thresholdNs = DEFAULT_THRESHOLD_NS;
private static volatile long sampleIntervalNs = DEFAULT_SAMPLE_INTERVAL_NS;
private static volatile Thread renderThread;
private static volatile Thread samplerThread;
private static volatile boolean running;
private static volatile boolean gcListenerInstalled;
private static int sampleCursor;
private static int sampleCount;
private static int gcCursor;
private static int gcCount;
private static long lastPresentedNs;
private static long lastLoggedNs;
public static void configure(ProfilerSettings.OutputMode mode, double thresholdMs, double sampleMs) {
output = mode == null ? ProfilerSettings.OutputMode.OFF : mode;
thresholdNs = clampMs(thresholdMs, 1.0, 5000.0, DEFAULT_THRESHOLD_NS);
sampleIntervalNs = clampMs(sampleMs, 1.0, 100.0, DEFAULT_SAMPLE_INTERVAL_NS);
if (output == ProfilerSettings.OutputMode.OFF) {
stopSampler();
synchronized (LOCK) {
sampleCursor = 0;
sampleCount = 0;
lastPresentedNs = 0L;
lastLoggedNs = 0L;
}
return;
}
installGcListener();
ensureSampler();
}
public static String statusLine() {
if (output == ProfilerSettings.OutputMode.OFF) {
return "Profiler stutter: off";
}
return String.format(Locale.ROOT,
"Profiler stutter: %s (threshold %.1f ms, sample %.1f ms)",
output.name().toLowerCase(Locale.ROOT),
thresholdNs / 1_000_000.0,
sampleIntervalNs / 1_000_000.0);
}
public static boolean isEnabled() {
return output != ProfilerSettings.OutputMode.OFF;
}
public static void onFramePresented(RhiStatsSnapshot rhi,
UniformAllocatorStatsSnapshot uniforms,
RenderResourceStatsSnapshot resources) {
try {
if (!isEnabled()) return;
if (RuntimeGate.isPanic()) return;
renderThread = Thread.currentThread();
ensureSampler();
long now = System.nanoTime();
long previous;
synchronized (LOCK) {
previous = lastPresentedNs;
lastPresentedNs = now;
}
if (previous == 0L) return;
long elapsedNs = now - previous;
if (elapsedNs < thresholdNs) return;
if (now - lastLoggedNs < thresholdNs) return;
lastLoggedNs = now;
List<String> lines = buildReport(previous, now, elapsedNs, rhi, uniforms, resources);
emit(lines);
} catch (Throwable t) {
ProfilerLog.warn("[FrameStutter] disabled after profiler failure: %s",
t.getClass().getSimpleName() + ": " + t.getMessage());
configure(ProfilerSettings.OutputMode.OFF, 0.0, 0.0);
}
}
private static List<String> buildReport(long frameStartNs,
long frameEndNs,
long elapsedNs,
RhiStatsSnapshot rhi,
UniformAllocatorStatsSnapshot uniforms,
RenderResourceStatsSnapshot resources) {
List<Sample> samples = samplesInWindow(frameStartNs, frameEndNs);
List<GcEvent> gcEvents = gcNearWindow(frameStartNs, frameEndNs);
Minecraft mc = Minecraft.getInstance();
String screen = mc == null || ClientScreen.current() == null ? "none" : ClientScreen.current().getClass().getSimpleName();
String world = mc == null || mc.level == null ? "none" : mc.level.dimension().identifier().toString();
List<String> lines = new ArrayList<>();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] frame %.2f ms over %.2f ms, samples %d, screen=%s, world=%s",
elapsedNs / 1_000_000.0,
thresholdNs / 1_000_000.0,
samples.size(),
screen,
world));
if (rhi != null) {
long uploaded = rhi.uploadedVertexBytes() + rhi.uploadedIndexBytes();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] rhi draw=%d fs=%d meshUpload=%d/%s copies=%d/%d ringWrap=%d stall=%d fallback=%d backlog=%d",
rhi.drawCalls(),
rhi.fullscreenPasses(),
rhi.meshUploads(),
formatBytes(uploaded),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaBacklogEvents()));
}
if (uniforms != null || resources != null) {
long uniformWrites = uniforms == null ? 0L : uniforms.writes();
long uniformBytes = uniforms == null ? 0L : uniforms.uploadedBytes();
int retireBacklog = resources == null ? 0 : resources.retirementBacklog();
int leaks = resources == null ? 0 : resources.leakedResources();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] uniforms writes=%d/%s resourceBacklog=%d leaks=%d",
uniformWrites,
formatBytes(uniformBytes),
retireBacklog,
leaks));
}
if (gcEvents.isEmpty()) {
lines.add("[FrameStutter] gc nearby: none");
} else {
for (GcEvent gc : gcEvents) {
double relativeEndMs = (gc.endNs - frameStartNs) / 1_000_000.0;
lines.add(String.format(Locale.ROOT,
"[FrameStutter] gc nearby: %s %s %.2f ms at %+,.2f ms, freed %s",
gc.name,
gc.cause,
(double) gc.durationMs,
relativeEndMs,
formatBytes(gc.freedBytes)));
}
}
appendSampleSummary(lines, samples);
return lines;
}
private static void appendSampleSummary(List<String> lines, List<Sample> samples) {
if (samples.isEmpty()) {
lines.add("[FrameStutter] sample top: none");
return;
}
Map<String, Integer> counts = new HashMap<>();
int glWait = 0;
int glUpload = 0;
int glDraw = 0;
int glState = 0;
for (Sample sample : samples) {
counts.merge(sample.stack, 1, Integer::sum);
if (sample.stack.startsWith("GL WAIT:")) {
glWait++;
} else if (sample.stack.startsWith("GL UPLOAD:")) {
glUpload++;
} else if (sample.stack.startsWith("GL DRAW:")) {
glDraw++;
} else if (sample.stack.startsWith("GL STATE:")) {
glState++;
}
}
lines.add(String.format(Locale.ROOT,
"[FrameStutter] gl samples wait/upload/draw/state=%d/%d/%d/%d",
glWait,
glUpload,
glDraw,
glState));
List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
lines.add("[FrameStutter] sample top:");
int top = Math.min(TOP_STACKS, entries.size());
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> entry = entries.get(i);
double pct = entry.getValue() * 100.0 / samples.size();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] %d) %s (%d, %.1f%%)",
i + 1,
entry.getKey(),
entry.getValue(),
pct));
}
}
private static List<Sample> samplesInWindow(long startNs, long endNs) {
List<Sample> out = new ArrayList<>();
synchronized (LOCK) {
for (int i = 0; i < sampleCount; i++) {
Sample sample = SAMPLES[i];
if (sample != null && sample.timeNs >= startNs && sample.timeNs <= endNs) {
out.add(sample);
}
}
}
out.sort((a, b) -> Long.compare(a.timeNs, b.timeNs));
return out;
}
private static List<GcEvent> gcNearWindow(long startNs, long endNs) {
long from = startNs - GC_CORRELATION_WINDOW_NS;
long to = endNs + GC_CORRELATION_WINDOW_NS;
List<GcEvent> out = new ArrayList<>();
synchronized (LOCK) {
for (int i = 0; i < gcCount; i++) {
GcEvent event = GC_EVENTS[i];
if (event != null && event.endNs >= from && event.endNs <= to) {
out.add(event);
}
}
}
out.sort((a, b) -> Long.compare(a.endNs, b.endNs));
return out;
}
private static void ensureSampler() {
if (running || output == ProfilerSettings.OutputMode.OFF) return;
running = true;
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "Combatant-DevFrameStutterProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
private static void stopSampler() {
running = false;
Thread thread = samplerThread;
samplerThread = null;
if (thread != null) {
thread.interrupt();
}
renderThread = null;
}
private static void sampleLoop() {
long lastSampleNs = 0L;
while (running) {
if (output == ProfilerSettings.OutputMode.OFF || RuntimeGate.isPanic()) {
sleepMs(20L);
continue;
}
Thread target = renderThread;
if (target == null) {
sleepMs(10L);
continue;
}
long now = System.nanoTime();
if (now - lastSampleNs >= sampleIntervalNs) {
recordSample(now, target);
lastSampleNs = now;
}
sleepMs(1L);
}
}
private static void recordSample(long now, Thread target) {
StackTraceElement[] stack = target.getStackTrace();
if (stack == null || stack.length == 0) return;
String key = buildKey(stack);
if (key == null || key.isBlank()) return;
synchronized (LOCK) {
SAMPLES[sampleCursor] = new Sample(now, key);
sampleCursor = (sampleCursor + 1) % MAX_SAMPLES;
if (sampleCount < MAX_SAMPLES) {
sampleCount++;
}
}
}
private static String buildKey(StackTraceElement[] stack) {
StringBuilder sb = new StringBuilder(320);
String glCat = glCategory(stack);
if (glCat != null) {
sb.append("GL ").append(glCat).append(": ");
}
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isNoise(e)) continue;
if (added > 0) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? null : sb.toString();
}
private static String glCategory(StackTraceElement[] stack) {
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if (!isGlFrame(cls)) continue;
if (method == null) continue;
if (method.equals("glfwSwapBuffers")
|| method.equals("glClientWaitSync")
|| method.equals("nglClientWaitSync")
|| method.equals("glWaitSync")
|| method.equals("glFinish")) {
return "WAIT";
}
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
return "DRAW";
}
if (method.contains("BufferSubData")
|| method.contains("BufferData")
|| method.contains("TexImage")
|| method.contains("TexSubImage")
|| method.contains("FlushMapped")
|| method.contains("MapBuffer")
|| method.contains("MapBufferRange")
|| method.contains("UnmapBuffer")) {
return "UPLOAD";
}
if (method.startsWith("glUseProgram")
|| method.startsWith("glBind")
|| method.startsWith("glTexParameter")
|| method.startsWith("glBlend")
|| method.startsWith("glEnable")
|| method.startsWith("glDisable")
|| method.startsWith("glDepth")
|| method.startsWith("glColorMask")
|| method.startsWith("glViewport")
|| method.startsWith("glScissor")
|| method.startsWith("glActiveTexture")
|| method.startsWith("glUniform")
|| method.startsWith("glVertexAttrib")) {
return "STATE";
}
}
return null;
}
private static boolean isGlFrame(String cls) {
return cls != null
&& (cls.startsWith("org.lwjgl.opengl.")
|| cls.startsWith("org.lwjgl.glfw.")
|| cls.startsWith("com.mojang.blaze3d.platform.")
|| cls.startsWith("com.mojang.blaze3d.systems."));
}
private static boolean isNoise(StackTraceElement e) {
String cls = e.getClassName();
return cls.startsWith("java.lang.Thread")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevFrameStutterProfiler");
}
private static String formatElement(StackTraceElement e) {
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + e.getLineNumber() + ")";
}
private static void installGcListener() {
if (gcListenerInstalled) return;
synchronized (LOCK) {
if (gcListenerInstalled) return;
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (bean instanceof NotificationEmitter emitter) {
emitter.addNotificationListener(DevFrameStutterProfiler::onGcNotification, null, null);
}
}
gcListenerInstalled = true;
}
}
private static void onGcNotification(Notification notification, Object handback) {
if (output == ProfilerSettings.OutputMode.OFF) return;
if (!GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) return;
Object data = notification.getUserData();
if (!(data instanceof CompositeData compositeData)) return;
try {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(compositeData);
GcInfo gcInfo = info.getGcInfo();
long freed = usedBefore(gcInfo) - usedAfter(gcInfo);
GcEvent event = new GcEvent(
System.nanoTime(),
info.getGcName(),
info.getGcCause(),
Math.max(0L, gcInfo.getDuration()),
Math.max(0L, freed));
synchronized (LOCK) {
GC_EVENTS[gcCursor] = event;
gcCursor = (gcCursor + 1) % MAX_GC_EVENTS;
if (gcCount < MAX_GC_EVENTS) {
gcCount++;
}
}
} catch (Throwable ignored) {
}
}
private static long usedBefore(GcInfo info) {
return used(info == null ? null : info.getMemoryUsageBeforeGc());
}
private static long usedAfter(GcInfo info) {
return used(info == null ? null : info.getMemoryUsageAfterGc());
}
private static long used(Map<String, MemoryUsage> usage) {
if (usage == null || usage.isEmpty()) return 0L;
long total = 0L;
for (MemoryUsage value : usage.values()) {
if (value != null && value.getUsed() > 0L) {
total += value.getUsed();
}
}
return total;
}
private static void emit(List<String> lines) {
ProfilerSettings.OutputMode mode = output;
if (mode == ProfilerSettings.OutputMode.OFF || lines == null || lines.isEmpty()) return;
if (mode == ProfilerSettings.OutputMode.LOG) {
for (String line : lines) {
ProfilerLog.info("%s", line);
}
return;
}
if (mode == ProfilerSettings.OutputMode.CHAT) {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal(line));
}
}
}
private static long clampMs(double valueMs, double minMs, double maxMs, long fallbackNs) {
if (!Double.isFinite(valueMs) || valueMs <= 0.0) return fallbackNs;
double clamped = Math.max(minMs, Math.min(maxMs, valueMs));
return (long) (clamped * 1_000_000.0);
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void sleepMs(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
}
}
private record Sample(long timeNs, String stack) {
}
private record GcEvent(long endNs, String name, String cause, long durationMs, long freedBytes) {
}
}

View file

@ -0,0 +1,340 @@
package dev.loki.lovisual.render.engine.profiler;
import java.util.*;
public enum DevGlSyncTracker {
;
private static final int MAX_FENCES = 512;
private static final int TOP_PHASES = 4;
private static final int TOP_STACKS = 3;
private static final int MAX_STACK_FRAMES = 8;
private static final int MAX_SLOW_WAITS = 3;
private static final long SLOW_WAIT_THRESHOLD_NS = 1_000_000L;
private static final Object LOCK = new Object();
private static final LinkedHashMap<Long, FenceInfo> FENCE_INFOS = new LinkedHashMap<>();
private static final Map<String, Integer> WAIT_BY_FENCE_PHASE = new HashMap<>();
private static final Map<String, Integer> WAIT_BY_WAIT_PHASE = new HashMap<>();
private static final Map<String, Long> WAIT_TIME_BY_FENCE_PHASE = new HashMap<>();
private static final Map<String, Long> WAIT_TIME_BY_WAIT_PHASE = new HashMap<>();
private static final Map<String, StackAggregate> WAIT_BY_CREATE_STACK = new HashMap<>();
private static final List<SlowWait> SLOW_WAITS = new ArrayList<>();
private static final ThreadLocal<WaitState> WAIT_STATE =
ThreadLocal.withInitial(WaitState::new);
private static int waitTotal;
private static long waitTimeTotalNs;
private static int tracyWaitCallsFrame;
private static long tracyWaitTimeFrameNs;
public static void onFence(long sync) {
if (!shouldTrackWaits()) return;
if (sync == 0L) return;
String phase = DevProfilerPhase.current();
String createStack = shouldCaptureStacks() ? captureStackTrace() : null;
synchronized (LOCK) {
FENCE_INFOS.put(sync, new FenceInfo(phase, createStack));
trimFences();
}
}
public static void onWaitStart(long sync) {
if (!shouldTrackWaits()) return;
WaitState state = WAIT_STATE.get();
state.startNs = System.nanoTime();
state.waitPhase = DevProfilerPhase.current();
state.waitStack = null;
FenceInfo fenceInfo;
synchronized (LOCK) {
fenceInfo = FENCE_INFOS.remove(sync);
}
state.fencePhase = fenceInfo == null || fenceInfo.phase == null ? "unknown" : fenceInfo.phase;
state.createStack = fenceInfo == null ? null : fenceInfo.createStack;
state.active = true;
}
public static void onWaitEnd() {
WaitState state = WAIT_STATE.get();
if (state == null || !state.active) return;
state.active = false;
long durationNs = System.nanoTime() - state.startNs;
if (durationNs < 0L) durationNs = 0L;
if (!shouldTrackWaits()) return;
String fencePhase = state.fencePhase == null ? "unknown" : state.fencePhase;
String waitPhase = state.waitPhase == null ? "unknown" : state.waitPhase;
boolean captureStacks = shouldCaptureStacks();
String createStack = captureStacks ? normalizeStack(state.createStack) : null;
String waitStack = captureStacks && durationNs >= SLOW_WAIT_THRESHOLD_NS ? captureStackTrace() : null;
synchronized (LOCK) {
WAIT_BY_FENCE_PHASE.merge(fencePhase, 1, Integer::sum);
WAIT_BY_WAIT_PHASE.merge(waitPhase, 1, Integer::sum);
WAIT_TIME_BY_FENCE_PHASE.merge(fencePhase, durationNs, Long::sum);
WAIT_TIME_BY_WAIT_PHASE.merge(waitPhase, durationNs, Long::sum);
if (captureStacks) {
StackAggregate aggregate = WAIT_BY_CREATE_STACK.computeIfAbsent(
createStack,
key -> new StackAggregate(fencePhase, key)
);
aggregate.count += 1;
aggregate.timeNs += durationNs;
}
if (durationNs >= SLOW_WAIT_THRESHOLD_NS) {
recordSlowWait(new SlowWait(
durationNs,
fencePhase,
waitPhase,
createStack,
captureStacks ? normalizeStack(waitStack) : null
));
}
waitTotal += 1;
waitTimeTotalNs += durationNs;
tracyWaitCallsFrame += 1;
tracyWaitTimeFrameNs += durationNs;
}
}
public static void emitTracyFrame() {
if (!DevTracyProfiler.isEnabled()) return;
int calls;
long totalNs;
synchronized (LOCK) {
calls = tracyWaitCallsFrame;
totalNs = tracyWaitTimeFrameNs;
tracyWaitCallsFrame = 0;
tracyWaitTimeFrameNs = 0L;
}
DevTracyProfiler.plotGlWait(totalNs / 1_000_000.0, calls);
}
public static List<String> drainLines() {
if (!DevSamplingProfiler.isActive()) return List.of();
List<String> lines = new ArrayList<>();
Map<String, Integer> byFence;
Map<String, Integer> byWait;
Map<String, Long> timeByFence;
Map<String, Long> timeByWait;
List<StackAggregate> createStacks;
List<SlowWait> slowWaits;
int total;
long totalNs;
synchronized (LOCK) {
if (waitTotal == 0) return List.of();
total = waitTotal;
totalNs = waitTimeTotalNs;
byFence = new HashMap<>(WAIT_BY_FENCE_PHASE);
byWait = new HashMap<>(WAIT_BY_WAIT_PHASE);
timeByFence = new HashMap<>(WAIT_TIME_BY_FENCE_PHASE);
timeByWait = new HashMap<>(WAIT_TIME_BY_WAIT_PHASE);
createStacks = new ArrayList<>(WAIT_BY_CREATE_STACK.values());
slowWaits = new ArrayList<>(SLOW_WAITS);
WAIT_BY_FENCE_PHASE.clear();
WAIT_BY_WAIT_PHASE.clear();
WAIT_TIME_BY_FENCE_PHASE.clear();
WAIT_TIME_BY_WAIT_PHASE.clear();
WAIT_BY_CREATE_STACK.clear();
SLOW_WAITS.clear();
waitTotal = 0;
waitTimeTotalNs = 0L;
}
lines.add(String.format("gl wait calls: %d", total));
lines.add("gl wait phase (fence): " + formatTop(byFence, total));
lines.add("gl wait phase (wait): " + formatTop(byWait, total));
if (totalNs > 0L) {
lines.add(String.format("gl wait time total: %s", formatDuration(totalNs)));
lines.add("gl wait time (fence): " + formatTopTime(timeByFence, totalNs));
lines.add("gl wait time (wait): " + formatTopTime(timeByWait, totalNs));
}
String createStackSummary = formatTopCreateStacks(createStacks, totalNs);
if (createStackSummary != null) {
lines.add("gl wait source (create): " + createStackSummary);
}
if (!slowWaits.isEmpty()) {
lines.add("gl wait slow traces:");
for (int i = 0; i < slowWaits.size(); i++) {
SlowWait slow = slowWaits.get(i);
lines.add(String.format(
" %d) %s fence=%s wait=%s",
i + 1,
formatDuration(slow.durationNs),
slow.fencePhase,
slow.waitPhase
));
if (slow.createStack != null) {
lines.add(" create: " + slow.createStack);
}
if (slow.waitStack != null) {
lines.add(" wait: " + slow.waitStack);
}
}
}
return lines;
}
private static String formatTop(Map<String, Integer> src, int total) {
if (src.isEmpty()) return "n/a";
List<Map.Entry<String, Integer>> list = new ArrayList<>(src.entrySet());
list.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
int top = Math.min(TOP_PHASES, list.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> e = list.get(i);
double pct = total == 0 ? 0.0 : (e.getValue() * 100.0) / total;
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey()).append('=').append(e.getValue())
.append(String.format(" (%.1f%%)", pct));
}
return sb.toString();
}
private static String formatTopTime(Map<String, Long> src, long totalNs) {
if (src.isEmpty()) return "n/a";
List<Map.Entry<String, Long>> list = new ArrayList<>(src.entrySet());
list.sort((a, b) -> Long.compare(b.getValue(), a.getValue()));
int top = Math.min(TOP_PHASES, list.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
Map.Entry<String, Long> e = list.get(i);
double pct = totalNs == 0L ? 0.0 : (e.getValue() * 100.0) / totalNs;
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey()).append('=').append(formatDuration(e.getValue()))
.append(String.format(" (%.1f%%)", pct));
}
return sb.toString();
}
private static String formatDuration(long ns) {
double ms = ns / 1_000_000.0;
return String.format("%.2fms", ms);
}
private static void trimFences() {
if (FENCE_INFOS.size() <= MAX_FENCES) return;
int toRemove = FENCE_INFOS.size() - MAX_FENCES;
var it = FENCE_INFOS.keySet().iterator();
while (toRemove > 0 && it.hasNext()) {
it.next();
it.remove();
toRemove--;
}
}
private static String formatTopCreateStacks(List<StackAggregate> stacks, long totalNs) {
if (stacks == null || stacks.isEmpty()) return null;
stacks.sort((a, b) -> Long.compare(b.timeNs, a.timeNs));
int top = Math.min(TOP_STACKS, stacks.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
StackAggregate aggregate = stacks.get(i);
double pct = totalNs == 0L ? 0.0 : (aggregate.timeNs * 100.0) / totalNs;
if (sb.length() > 0) sb.append(" | ");
sb.append(aggregate.fencePhase)
.append('=')
.append(formatDuration(aggregate.timeNs))
.append(" x")
.append(aggregate.count)
.append(String.format(" (%.1f%%)", pct))
.append(" :: ")
.append(aggregate.createStack);
}
return sb.toString();
}
private static void recordSlowWait(SlowWait slowWait) {
SLOW_WAITS.add(slowWait);
SLOW_WAITS.sort((a, b) -> Long.compare(b.durationNs, a.durationNs));
while (SLOW_WAITS.size() > MAX_SLOW_WAITS) {
SLOW_WAITS.remove(SLOW_WAITS.size() - 1);
}
}
private static String captureStackTrace() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StringBuilder sb = new StringBuilder(256);
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isStackNoise(e)) continue;
if (added > 0) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? "unknown" : sb.toString();
}
private static String normalizeStack(String stack) {
return stack == null || stack.isBlank() ? "unknown" : stack;
}
private static boolean shouldCaptureStacks() {
return ProfilerSettings.isSampleDetailedStacks();
}
private static boolean shouldTrackWaits() {
return DevSamplingProfiler.isActive() || DevTracyProfiler.isEnabled();
}
private static boolean isStackNoise(StackTraceElement e) {
String cls = e.getClassName();
String method = e.getMethodName();
return cls.equals(Thread.class.getName())
|| cls.startsWith("java.lang.Thread")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("org.lwjgl.opengl.GL")
|| cls.startsWith("org.lwjgl.system.JNI")
|| cls.equals(DevGlSyncTracker.class.getName())
|| cls.equals("dev.loki.lovisual.mixins.GlStateManagerMixin")
|| (cls.equals("com.mojang.blaze3d.opengl.GlStateManager")
&& ("_glFenceSync".equals(method) || "_glClientWaitSync".equals(method)));
}
private static String formatElement(StackTraceElement e) {
String cls = e.getClassName();
int idx = cls.lastIndexOf('.');
String simple = idx >= 0 ? cls.substring(idx + 1) : cls;
return simple + "." + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")";
}
public static void reset() {
synchronized (LOCK) {
FENCE_INFOS.clear();
WAIT_BY_FENCE_PHASE.clear();
WAIT_BY_WAIT_PHASE.clear();
WAIT_TIME_BY_FENCE_PHASE.clear();
WAIT_TIME_BY_WAIT_PHASE.clear();
WAIT_BY_CREATE_STACK.clear();
SLOW_WAITS.clear();
waitTotal = 0;
waitTimeTotalNs = 0L;
}
}
private record FenceInfo(String phase, String createStack) {
}
private static final class StackAggregate {
final String fencePhase;
final String createStack;
int count;
long timeNs;
StackAggregate(String fencePhase, String createStack) {
this.fencePhase = fencePhase;
this.createStack = createStack;
}
}
private record SlowWait(long durationNs, String fencePhase, String waitPhase, String createStack,
String waitStack) {
}
private static final class WaitState {
long startNs;
String fencePhase;
String waitPhase;
String createStack;
String waitStack;
boolean active;
}
}

View file

@ -0,0 +1,253 @@
package dev.loki.lovisual.render.engine.profiler;
import jdk.jfr.EventSettings;
import jdk.jfr.Recording;
import net.minecraft.client.Minecraft;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public enum DevJfrProfiler {
;
private static final DateTimeFormatter FILE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
private static Recording recording;
private static Preset activePreset;
private static Instant startedAt;
private static Path outputPath;
public static synchronized StartResult start(Preset preset) {
if (recording != null) {
return StartResult.alreadyRunning(activePreset, outputPath, startedAt);
}
try {
Path dir = ensureOutputDirectory();
Path file = dir.resolve(defaultFileName(preset, false));
Recording next = new Recording();
next.setName("Combatant " + preset.getId());
next.setToDisk(true);
next.setDumpOnExit(false);
configure(next, preset);
next.start();
recording = next;
activePreset = preset;
startedAt = Instant.now();
outputPath = file;
ProfilerLog.info("JFR started (%s) -> %s", preset.getId(), file.toAbsolutePath());
return StartResult.started(preset, file, startedAt);
} catch (Throwable t) {
ProfilerLog.warn("JFR unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return StartResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized DumpResult dumpSnapshot() {
if (recording == null) {
return DumpResult.notRunningResult();
}
try {
Path dir = ensureOutputDirectory();
Path snapshot = dir.resolve(defaultFileName(activePreset, true));
recording.dump(snapshot);
ProfilerLog.info("JFR snapshot dumped -> %s", snapshot.toAbsolutePath());
return DumpResult.dumped(snapshot);
} catch (Throwable t) {
ProfilerLog.warn("JFR snapshot failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return DumpResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized StopResult stop() {
if (recording == null) {
return StopResult.notRunningResult();
}
Recording current = recording;
Preset preset = activePreset;
Instant started = startedAt;
Path destination = outputPath;
recording = null;
activePreset = null;
startedAt = null;
outputPath = null;
try {
current.stop();
Files.createDirectories(destination.getParent());
current.dump(destination);
current.close();
ProfilerLog.info("JFR stopped (%s) -> %s", preset.getId(), destination.toAbsolutePath());
return StopResult.stopped(preset, destination, started);
} catch (Throwable t) {
try {
current.close();
} catch (Throwable ignored) {
}
ProfilerLog.warn("JFR stop failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return StopResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized String statusLine() {
if (recording == null) {
return "Profiler JFR: off";
}
long seconds = Math.max(0L, Duration.between(startedAt, Instant.now()).toSeconds());
return "Profiler JFR: on (" + activePreset.getId()
+ ", " + formatDuration(seconds)
+ ", file " + outputPath.toAbsolutePath() + ")";
}
private static void configure(Recording recording, Preset preset) {
enable(recording, "jdk.GarbageCollection", true, null, null);
enable(recording, "jdk.GCHeapSummary", false, null, null);
enable(recording, "jdk.MetaspaceSummary", false, null, null);
enable(recording, "jdk.CPULoad", false, Duration.ofSeconds(1), null);
enable(recording, "jdk.JavaThreadStatistics", false, Duration.ofSeconds(1), null);
if (preset.capturesAllocations()) {
enable(recording, "jdk.ObjectAllocationSample", true, null, null);
}
if (preset == Preset.FULL) {
enable(recording, "jdk.ExecutionSample", true, Duration.ofMillis(20), null);
enable(recording, "jdk.NativeMethodSample", true, Duration.ofMillis(20), null);
enable(recording, "jdk.ThreadPark", true, null, Duration.ofMillis(1));
enable(recording, "jdk.JavaMonitorEnter", true, null, Duration.ofMillis(1));
}
}
private static void enable(
Recording recording,
String eventName,
boolean stackTrace,
Duration period,
Duration threshold
) {
try {
EventSettings settings = recording.enable(eventName);
settings = stackTrace ? settings.withStackTrace() : settings.withoutStackTrace();
if (period != null) {
settings = settings.withPeriod(period);
}
if (threshold != null) {
settings = settings.withThreshold(threshold);
}
} catch (IllegalArgumentException ignored) {
// Some runtimes ship a slightly different event set.
}
}
private static Path ensureOutputDirectory() throws Exception {
Minecraft mc = Minecraft.getInstance();
Path dir;
if (mc != null && mc.gameDirectory != null) {
dir = mc.gameDirectory.toPath().resolve("profile").resolve("jfr");
} else {
dir = Path.of("profile", "jfr");
}
Files.createDirectories(dir);
return dir;
}
private static String defaultFileName(Preset preset, boolean snapshot) {
String timestamp = FILE_TIME.format(LocalDateTime.now(ZoneId.systemDefault()));
String suffix = snapshot ? "-snapshot" : "";
return "combatant-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
}
private static String formatDuration(long totalSeconds) {
long minutes = totalSeconds / 60L;
long seconds = totalSeconds % 60L;
if (minutes <= 0L) {
return seconds + "s";
}
return minutes + "m " + seconds + "s";
}
public enum Preset {
GC("gc"),
ALLOC("alloc"),
FULL("full");
private final String id;
Preset(String id) {
this.id = id;
}
public static Preset parse(String raw) {
if (raw == null || raw.isBlank()) {
return FULL;
}
return switch (raw.toLowerCase()) {
case "gc" -> GC;
case "alloc", "allocation", "allocs" -> ALLOC;
case "full", "all", "profile" -> FULL;
default -> null;
};
}
public String id() {
return id;
}
public String getId() {
return id;
}
public boolean capturesAllocations() {
return this == ALLOC || this == FULL;
}
}
public record StartResult(boolean started, boolean alreadyRunning, Preset preset, Path path, Instant startedAt,
String error) {
private static StartResult started(Preset preset, Path path, Instant startedAt) {
return new StartResult(true, false, preset, path, startedAt, null);
}
private static StartResult alreadyRunning(Preset preset, Path path, Instant startedAt) {
return new StartResult(false, true, preset, path, startedAt, null);
}
private static StartResult failed(String error) {
return new StartResult(false, false, null, null, null, error);
}
}
public record DumpResult(boolean dumped, boolean notRunning, Path path, String error) {
private static DumpResult dumped(Path path) {
return new DumpResult(true, false, path, null);
}
private static DumpResult notRunningResult() {
return new DumpResult(false, true, null, null);
}
private static DumpResult failed(String error) {
return new DumpResult(false, false, null, error);
}
}
public record StopResult(boolean stopped, boolean notRunning, Preset preset, Path path, Instant startedAt,
String error) {
private static StopResult stopped(Preset preset, Path path, Instant startedAt) {
return new StopResult(true, false, preset, path, startedAt, null);
}
private static StopResult notRunningResult() {
return new StopResult(false, true, null, null, null, null);
}
private static StopResult failed(String error) {
return new StopResult(false, false, null, null, null, error);
}
}
}

View file

@ -0,0 +1,67 @@
package dev.loki.lovisual.render.engine.profiler;
import java.util.ArrayDeque;
public enum DevProfilerPhase {
;
private static final ThreadLocal<ArrayDeque<String>> STACK =
ThreadLocal.withInitial(ArrayDeque::new);
public static Scope scope(String label) {
if (label == null || label.isBlank()) return Scope.NOOP;
begin(label);
return new Scope(true);
}
public static void begin(String label) {
if (label == null || label.isBlank()) return;
if (!DevSamplingProfiler.isActive()) return;
STACK.get().push(label);
}
public static void end(String label) {
if (label == null || label.isBlank()) return;
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return;
String top = stack.peek();
if (label.equals(top)) {
pop();
}
}
public static String current() {
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return "unknown";
String v = stack.peek();
return v == null || v.isBlank() ? "unknown" : v;
}
public static void clearCurrent() {
ArrayDeque<String> stack = STACK.get();
if (stack != null) {
stack.clear();
}
}
private static void pop() {
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return;
stack.pop();
}
public static final class Scope implements AutoCloseable {
private static final Scope NOOP = new Scope(false);
private final boolean active;
private Scope(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
pop();
}
}
}

View file

@ -0,0 +1,457 @@
package dev.loki.lovisual.render.engine.profiler;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import java.util.*;
/**
* Low-overhead owner/effect profiler for the new RHI path.
*
* <p>The existing DevRenderProfiler2D/3D tree answers "which Java section is hot".
* This profiler answers the practical render question: which phase/widget/node/effect/pass
* consumed CPU time and caused RHI work (draws, uploads, fullscreen passes, copies, uniforms).</p>
*/
public enum DevRenderCostProfiler {
;
private static final int MAX_BUCKETS = 768;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_LOG_INTERVAL_FRAMES = 120;
private static final int DEFAULT_LOG_TOP = 20;
private static final double DEFAULT_LOG_MIN_MS = 0.02;
private static final String PROP_ENABLED = "combatant.profiler.renderCost";
private static final String PROP_LOG = "combatant.profiler.renderCost.log";
private static final String PROP_INTERVAL = "combatant.profiler.renderCost.interval";
private static final String PROP_TOP = "combatant.profiler.renderCost.top";
private static final String PROP_MIN_MS = "combatant.profiler.renderCost.minMs";
private static final LinkedHashMap<String, Bucket> buckets = new LinkedHashMap<>();
private static final HashMap<String, String> labelCache = new HashMap<>(256);
private static final ThreadLocal<Deque<Scope>> scopeStack = ThreadLocal.withInitial(ArrayDeque::new);
private static long frameId = Long.MIN_VALUE;
private static long lastLoggedFrameId = Long.MIN_VALUE;
private static boolean active;
private static Snapshot snapshot = Snapshot.EMPTY;
public static void beginFrame(long newFrameId) {
if (frameId == newFrameId) return;
frameId = newFrameId;
active = isProfilerEnabled();
if (!active) {
snapshot = Snapshot.EMPTY;
return;
}
buckets.clear();
scopeStack.get().clear();
}
public static void endFrame() {
if (!active) return;
snapshot = Snapshot.from(frameId, buckets);
emitLogIfDue(snapshot);
active = false;
}
public static Snapshot snapshot() {
return snapshot;
}
public static boolean isEnabled() {
return active;
}
public static boolean isConfigured() {
return Boolean.getBoolean(PROP_ENABLED);
}
public static Scope scope(String domain, String name) {
if (!active) return Scope.NOOP;
String d = clean(domain, "unknown");
String n = clean(name, "unnamed");
String owner = clean(DevProfilerPhase.current(), "unknown");
Bucket bucket = bucket(d, owner, n);
if (bucket == null) return Scope.NOOP;
Scope scope = new Scope(bucket, System.nanoTime(), Counters.capture(), true);
scopeStack.get().push(scope);
return scope;
}
public static Scope phase(String label) {
return scope("phase", label);
}
public static Scope uiNode(Object label) {
return scope("ui.node", String.valueOf(label));
}
public static Scope uiRuntime(String label) {
return scope("ui.runtime", label);
}
public static Scope uiEffect(String label) {
return scope("ui.effect", label);
}
public static Scope postPass(String label) {
return scope("post.pass", label);
}
public static Scope rhiDraw(String label) {
return scope("rhi.draw", label);
}
public static Scope itemRender(String label) {
return scope("item.render", label);
}
public static Scope worldEffect(String label) {
return scope("world.effect", label);
}
public static List<String> debugLines(String title, String domainPrefix, int limit, double minMs) {
Snapshot snap = snapshot;
if (snap == null || snap.entries.isEmpty()) return List.of();
String prefix = domainPrefix == null ? "" : domainPrefix;
List<Entry> filtered = new ArrayList<>();
for (Entry entry : snap.entries) {
if (prefix.isEmpty() || entry.domain.startsWith(prefix)) {
filtered.add(entry);
}
}
if (filtered.isEmpty()) return List.of();
filtered.sort(Comparator
.comparingLong((Entry e) -> e.totalNs).reversed()
.thenComparingLong((Entry e) -> e.uploadedBytes).reversed()
.thenComparingLong((Entry e) -> e.drawCalls).reversed());
List<String> lines = new ArrayList<>();
lines.add(title + ":");
int count = 0;
for (Entry e : filtered) {
double ms = e.totalNs / (double) NS_IN_MS;
if (ms < minMs) continue;
lines.add(String.format(Locale.ROOT,
" %d) [%s] %s:%s %.2f ms max %.2f calls %d | draw %d upload %d/%s fs %d copy %d/%d uni %d/%s",
count + 1,
shorten(e.owner, 42),
e.domain,
shorten(e.name, 56),
ms,
e.maxNs / (double) NS_IN_MS,
e.calls,
e.drawCalls,
e.meshUploads,
formatBytes(e.uploadedBytes),
e.fullscreenPasses,
e.fastCopies,
e.shaderCopies,
e.uniformWrites,
formatBytes(e.uniformBytes)));
count++;
if (count >= limit) break;
}
if (count == 0) return List.of();
return lines;
}
private static boolean isProfilerEnabled() {
return Boolean.getBoolean(PROP_ENABLED);
}
private static boolean shouldLogToLatest() {
if (!Boolean.getBoolean(PROP_ENABLED)) return false;
return Boolean.parseBoolean(System.getProperty(PROP_LOG, "true"));
}
private static void emitLogIfDue(Snapshot snap) {
if (!shouldLogToLatest()) return;
if (snap == null || snap.entries.isEmpty()) return;
int interval = intProperty(PROP_INTERVAL, DEFAULT_LOG_INTERVAL_FRAMES, 1, 60_000);
if (lastLoggedFrameId != Long.MIN_VALUE && snap.frameId - lastLoggedFrameId < interval) return;
lastLoggedFrameId = snap.frameId;
int top = intProperty(PROP_TOP, DEFAULT_LOG_TOP, 1, 200);
double minMs = doubleProperty(PROP_MIN_MS, DEFAULT_LOG_MIN_MS, 0.0, 1_000.0);
ProfilerLog.info("[RenderCost] frame=%d buckets=%d interval=%d top=%d minMs=%.3f", snap.frameId, snap.entries.size(), interval, top, minMs);
emitDomainToLog("phases", "phase", top, minMs);
emitDomainToLog("ui runtime", "ui.runtime", top, minMs);
emitDomainToLog("ui nodes", "ui.node", top, minMs);
emitDomainToLog("ui effects", "ui.effect", top, minMs);
emitDomainToLog("item render", "item.render", top, minMs);
emitDomainToLog("world effects", "world.effect", top, minMs);
emitDomainToLog("post passes", "post.pass", top, minMs);
emitDomainToLog("rhi draws", "rhi.draw", top, minMs);
}
private static void emitDomainToLog(String title, String prefix, int top, double minMs) {
List<String> lines = debugLines("[RenderCost] " + title, prefix, top, minMs);
for (String line : lines) {
ProfilerLog.info("%s", line);
}
}
private static int intProperty(String key, int fallback, int min, int max) {
String raw = System.getProperty(key);
if (raw == null || raw.isBlank()) return fallback;
try {
int value = Integer.parseInt(raw.trim());
return Math.max(min, Math.min(max, value));
} catch (NumberFormatException ignored) {
return fallback;
}
}
private static double doubleProperty(String key, double fallback, double min, double max) {
String raw = System.getProperty(key);
if (raw == null || raw.isBlank()) return fallback;
try {
double value = Double.parseDouble(raw.trim());
if (!Double.isFinite(value)) return fallback;
return Math.max(min, Math.min(max, value));
} catch (NumberFormatException ignored) {
return fallback;
}
}
private static Bucket bucket(String domain, String owner, String name) {
String key = domain + '\u001F' + owner + '\u001F' + name;
Bucket existing = buckets.get(key);
if (existing != null) return existing;
if (buckets.size() >= MAX_BUCKETS) {
key = "overflow\u001F" + owner + "\u001Fother";
existing = buckets.get(key);
if (existing != null) return existing;
if (buckets.size() >= MAX_BUCKETS + 1) return null;
Bucket overflow = new Bucket("overflow", owner, "other");
buckets.put(key, overflow);
return overflow;
}
Bucket created = new Bucket(domain, owner, name);
buckets.put(key, created);
return created;
}
private static String clean(String raw, String fallback) {
if (raw == null || raw.isBlank()) return fallback;
String s = raw.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim();
return s.isEmpty() ? fallback : s;
}
private static String shorten(String s, int max) {
if (s == null) return "";
if (s.length() <= max) return s;
if (max <= 3) return s.substring(0, max);
return s.substring(0, max - 3) + "...";
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
public static final class Scope implements AutoCloseable {
private static final Scope NOOP = new Scope(null, 0L, Counters.ZERO, false);
private final Bucket bucket;
private final long startNs;
private final Counters begin;
private final boolean enabled;
private boolean closed;
private long childNs;
private Counters childCounters = Counters.ZERO;
private Scope(Bucket bucket, long startNs, Counters begin, boolean enabled) {
this.bucket = bucket;
this.startNs = startNs;
this.begin = begin;
this.enabled = enabled;
}
@Override
public void close() {
if (!enabled || closed || bucket == null) return;
closed = true;
long elapsed = Math.max(0L, System.nanoTime() - startNs);
Counters rawDelta = begin.deltaTo(Counters.capture());
Deque<Scope> stack = scopeStack.get();
if (!stack.isEmpty() && stack.peek() == this) {
stack.pop();
} else {
stack.remove(this);
}
if (!stack.isEmpty()) {
Scope parent = stack.peek();
parent.childNs += elapsed;
parent.childCounters = parent.childCounters.plus(rawDelta);
}
long bucketNs = elapsed;
Counters bucketCounters = rawDelta;
if ("ui.node".equals(bucket.domain)) {
bucketNs = Math.max(0L, elapsed - childNs);
bucketCounters = rawDelta.minus(childCounters);
}
bucket.add(bucketNs, bucketCounters);
}
}
private static final class Bucket {
final String domain;
final String owner;
final String name;
long calls;
long totalNs;
long maxNs;
long drawCalls;
long meshUploads;
long fullscreenPasses;
long fastCopies;
long shaderCopies;
long uploadedBytes;
long uniformWrites;
long uniformBytes;
private Bucket(String domain, String owner, String name) {
this.domain = domain;
this.owner = owner;
this.name = name;
}
void add(long ns, Counters d) {
calls++;
totalNs += ns;
maxNs = Math.max(maxNs, ns);
if (d == null) return;
drawCalls += d.drawCalls;
meshUploads += d.meshUploads;
fullscreenPasses += d.fullscreenPasses;
fastCopies += d.fastCopies;
shaderCopies += d.shaderCopies;
uploadedBytes += d.uploadedBytes;
uniformWrites += d.uniformWrites;
uniformBytes += d.uniformBytes;
}
}
private record Counters(long drawCalls,
long meshUploads,
long fullscreenPasses,
long fastCopies,
long shaderCopies,
long uploadedBytes,
long uniformWrites,
long uniformBytes) {
static final Counters ZERO = new Counters(0, 0, 0, 0, 0, 0, 0, 0);
static Counters capture() {
try {
long uploaded = CombatantRenderSystem.rhi().stats().uploadedVertexBytes()
+ CombatantRenderSystem.rhi().stats().uploadedIndexBytes();
return new Counters(
CombatantRenderSystem.rhi().stats().drawCalls(),
CombatantRenderSystem.rhi().stats().meshUploads(),
CombatantRenderSystem.rhi().stats().fullscreenPasses(),
CombatantRenderSystem.rhi().stats().textureFastCopies(),
CombatantRenderSystem.rhi().stats().textureShaderCopies(),
uploaded,
CombatantRenderSystem.uniforms().stats().writes(),
CombatantRenderSystem.uniforms().stats().uploadedBytes()
);
} catch (Throwable ignored) {
return ZERO;
}
}
Counters deltaTo(Counters end) {
if (end == null) return ZERO;
return new Counters(
Math.max(0L, end.drawCalls - drawCalls),
Math.max(0L, end.meshUploads - meshUploads),
Math.max(0L, end.fullscreenPasses - fullscreenPasses),
Math.max(0L, end.fastCopies - fastCopies),
Math.max(0L, end.shaderCopies - shaderCopies),
Math.max(0L, end.uploadedBytes - uploadedBytes),
Math.max(0L, end.uniformWrites - uniformWrites),
Math.max(0L, end.uniformBytes - uniformBytes)
);
}
Counters plus(Counters other) {
if (other == null) return this;
return new Counters(
drawCalls + other.drawCalls,
meshUploads + other.meshUploads,
fullscreenPasses + other.fullscreenPasses,
fastCopies + other.fastCopies,
shaderCopies + other.shaderCopies,
uploadedBytes + other.uploadedBytes,
uniformWrites + other.uniformWrites,
uniformBytes + other.uniformBytes
);
}
Counters minus(Counters other) {
if (other == null) return this;
return new Counters(
Math.max(0L, drawCalls - other.drawCalls),
Math.max(0L, meshUploads - other.meshUploads),
Math.max(0L, fullscreenPasses - other.fullscreenPasses),
Math.max(0L, fastCopies - other.fastCopies),
Math.max(0L, shaderCopies - other.shaderCopies),
Math.max(0L, uploadedBytes - other.uploadedBytes),
Math.max(0L, uniformWrites - other.uniformWrites),
Math.max(0L, uniformBytes - other.uniformBytes)
);
}
}
public record Snapshot(long frameId, List<Entry> entries) {
static final Snapshot EMPTY = new Snapshot(Long.MIN_VALUE, List.of());
static Snapshot from(long frameId, Map<String, Bucket> buckets) {
if (buckets == null || buckets.isEmpty()) return EMPTY;
List<Entry> out = new ArrayList<>(buckets.size());
for (Bucket b : buckets.values()) {
out.add(new Entry(
b.domain,
b.owner,
b.name,
b.calls,
b.totalNs,
b.maxNs,
b.drawCalls,
b.meshUploads,
b.fullscreenPasses,
b.fastCopies,
b.shaderCopies,
b.uploadedBytes,
b.uniformWrites,
b.uniformBytes
));
}
return new Snapshot(frameId, List.copyOf(out));
}
}
public record Entry(String domain,
String owner,
String name,
long calls,
long totalNs,
long maxNs,
long drawCalls,
long meshUploads,
long fullscreenPasses,
long fastCopies,
long shaderCopies,
long uploadedBytes,
long uniformWrites,
long uniformBytes) {
}
}

View file

@ -0,0 +1,135 @@
package dev.loki.lovisual.render.engine.profiler;
import dev.loki.lovisual.render.engine.core.RenderPhase;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
/**
* Single profiler bridge for the RHI/FrameGraph lifecycle.
* Existing DevRenderProfiler2D/3D trees are preserved, but phase ownership moves here.
*/
public enum DevRenderFrameProfiler {
;
private static boolean worldFrameOpen;
private static boolean uiFrameOpen;
public static void beginFrame(long frameId) {
// The sampling profiler is still driven by 2D/3D beginFrame calls below.
DevRenderCostProfiler.beginFrame(frameId);
}
public static PhaseScope phase(RenderPhase phase, String label) {
RenderPhase actualPhase = phase == null ? RenderPhase.NONE : phase;
String actualLabel = label == null || label.isBlank() ? defaultLabel(actualPhase) : label;
DevProfilerPhase.Scope cpu = DevProfilerPhase.scope(actualLabel);
DevRenderCostProfiler.Scope cost = DevRenderCostProfiler.phase(actualLabel);
DevTracyGpuProfiler.Scope gpu = DevTracyGpuProfiler.beginZone(actualLabel);
AutoCloseable tree = beginTreeSection(actualPhase, actualLabel);
return new PhaseScope(cpu, cost, gpu, tree);
}
public static void endFrame(RhiStatsSnapshot rhi, UniformAllocatorStatsSnapshot uniforms) {
DevRenderCostProfiler.endFrame();
if (worldFrameOpen) {
DevRenderProfiler3D.endFrame();
worldFrameOpen = false;
}
if (uiFrameOpen) {
DevRenderProfiler2D.endFrame();
uiFrameOpen = false;
}
DevGlSyncTracker.emitTracyFrame();
DevTracyProfiler.markFrame();
}
private static AutoCloseable beginTreeSection(RenderPhase phase, String label) {
if (isWorld(phase)) {
if (!worldFrameOpen) {
DevRenderProfiler3D.beginFrame("world");
worldFrameOpen = true;
}
return DevRenderProfiler3D.section(stripDomain(label));
}
if (isUi(phase)) {
if (!uiFrameOpen) {
DevRenderProfiler2D.beginFrame("ui");
uiFrameOpen = true;
}
return DevRenderProfiler2D.section(stripDomain(label));
}
return () -> {
};
}
private static boolean isWorld(RenderPhase phase) {
return phase == RenderPhase.WORLD_BEFORE_ENTITIES
|| phase == RenderPhase.WORLD_AFTER_ENTITIES
|| phase == RenderPhase.WORLD_BEFORE_TRANSLUCENT
|| phase == RenderPhase.WORLD_AFTER_TRANSLUCENT
|| phase == RenderPhase.WORLD_POST_PRE_HAND
|| phase == RenderPhase.WORLD_POST_HAND;
}
private static boolean isUi(RenderPhase phase) {
return phase == RenderPhase.HUD_CAPTURE
|| phase == RenderPhase.HUD_MAIN
|| phase == RenderPhase.HUD_EFFECTS
|| phase == RenderPhase.SCREEN_TOP
|| phase == RenderPhase.SCREEN;
}
private static String defaultLabel(RenderPhase phase) {
return switch (phase) {
case WORLD_BEFORE_ENTITIES -> "3d:world_before_entities";
case WORLD_AFTER_ENTITIES -> "3d:world_after_entities";
case WORLD_BEFORE_TRANSLUCENT -> "3d:world_before_translucent";
case WORLD_AFTER_TRANSLUCENT -> "3d:world_after_translucent";
case WORLD_POST_PRE_HAND -> "3d:post_pre_hand";
case WORLD_POST_HAND -> "3d:post_hand";
case HUD_CAPTURE -> "2d:hud_capture";
case HUD_MAIN -> "2d:hud_main";
case HUD_EFFECTS -> "2d:hud_effects";
case SCREEN_TOP -> "2d:screen_top";
case SCREEN -> "2d:screen";
case LEGACY_SHADOW_TERRAIN -> "3d:shadow_terrain_legacy";
default -> "render:none";
};
}
private static String stripDomain(String label) {
int idx = label.indexOf(':');
if (idx >= 0 && idx + 1 < label.length()) {
return label.substring(idx + 1);
}
return label;
}
public static final class PhaseScope implements AutoCloseable {
private final DevProfilerPhase.Scope cpu;
private final DevRenderCostProfiler.Scope cost;
private final DevTracyGpuProfiler.Scope gpu;
private final AutoCloseable tree;
private boolean closed;
private PhaseScope(DevProfilerPhase.Scope cpu, DevRenderCostProfiler.Scope cost, DevTracyGpuProfiler.Scope gpu, AutoCloseable tree) {
this.cpu = cpu;
this.cost = cost;
this.gpu = gpu;
this.tree = tree;
}
@Override
public void close() {
if (closed) return;
closed = true;
try {
if (tree != null) tree.close();
} catch (Exception ignored) {
}
if (gpu != null) gpu.close();
if (cost != null) cost.close();
if (cpu != null) cpu.close();
}
}
}

View file

@ -0,0 +1,499 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.command.UiStatsSnapshot;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.ui.runtime.script.CachedUiScriptRuntime;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.render.engine.text.TextCommandStatsSnapshot;
import dev.loki.lovisual.render.engine.text.TextRenderSystem;
import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.*;
public enum DevRenderProfiler2D {
;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_TOP_LIMIT = 6;
private static final int DEFAULT_TREE_DEPTH = 32;
private static final double DEFAULT_MIN_MS = 0.0;
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
private static boolean active;
private static Node root;
private static Node snapshot;
private static long lastEmitNs;
public static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static void beginFrame(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
if (!isEnabled()) return;
CachedUiScriptRuntime.resetFrameStats();
MeshBuilder.resetFrameStats();
active = true;
root = new Node(name, null);
stack.clear();
stack.push(root);
root.startNs = System.nanoTime();
}
public static boolean beginFrameIfNeeded(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
if (!isEnabled() || active) return false;
beginFrame(name);
return true;
}
public static void endFrame() {
if (!isEnabled() || !active) return;
long now = System.nanoTime();
while (stack.size() > 1) {
endSection();
}
Node r = stack.peek();
if (r != null) {
r.calls = Math.max(1, r.calls);
r.totalNs += now - r.startNs;
r.startNs = 0L;
snapshot = r;
DevTracyProfiler.plotUiFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
}
active = false;
emitIfDue(now);
}
public static Section section(String name) {
if (!isEnabled() || !active) return Section.NOOP;
beginSection(name);
return new Section(true);
}
private static void beginSection(String name) {
Node parent = stack.peek();
if (parent == null) return;
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
child.calls += 1;
child.startNs = System.nanoTime();
stack.push(child);
}
private static void endSection() {
Node node = stack.poll();
if (node == null) return;
long now = System.nanoTime();
node.totalNs += now - node.startNs;
node.startNs = 0L;
}
public static List<String> getDebugLines() {
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
}
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
if (!isEnabled()) return List.of();
Node snap = snapshot;
if (snap == null) return List.of();
List<String> lines = new ArrayList<>();
double totalMs = snap.totalNs / (double) NS_IN_MS;
lines.add(String.format("ui prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
appendRuntimeCounters(lines);
List<Node> flat = new ArrayList<>();
collectFlat(snap, flat);
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
int top = Math.min(topLimit, flat.size());
if (top > 0) {
lines.add("ui prof top:");
for (int i = 0; i < top; i++) {
Node n = flat.get(i);
double ms = n.totalNs / (double) NS_IN_MS;
if (ms < minMs) break;
double selfMs = selfNs(n) / (double) NS_IN_MS;
Node hot = hottestChild(n);
if (hot != null) {
double hotMs = hot.totalNs / (double) NS_IN_MS;
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
hot.name,
hotMs,
n.calls
));
} else {
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
n.calls
));
}
}
}
lines.add("ui prof tree:");
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
return lines;
}
private static void appendRuntimeCounters(List<String> lines) {
CachedUiScriptRuntime.FrameStatsSnapshot ui = CachedUiScriptRuntime.frameStatsSnapshot();
if (ui.bakeCalls() > 0 || ui.jsRenders() > 0 || ui.layoutPasses() > 0 || ui.propPatches() > 0 || ui.boundsPatches() > 0) {
lines.add(String.format(
"ui runtime: bake %d, js %d, layout %d, propPatch %d/%d, boundsPatch %d/%d, blocked %d, fail %d",
ui.bakeCalls(),
ui.jsRenders(),
ui.layoutPasses(),
ui.propPatchPasses(),
ui.propPatches(),
ui.boundsPatchPasses(),
ui.boundsPatches(),
ui.blockedCalls(),
ui.failedRenders()
));
}
TextCommandStatsSnapshot textStats = CombatantRenderSystem.textStatsSnapshot();
if (textStats.recorded() > 0 || textStats.meshUploads() > 0 || textStats.glyphs() > 0) {
lines.add(String.format(
"text: rec/sub %d/%d, backend vanilla/bitmap/msdf/world %d/%d/%d/%d, effect/clip %d/%d, glyphs %d, meshUploads %d, router hit/miss/fallback %d/%d/%d, adjacent %d, uploaded v/i %s/%s",
textStats.recorded(),
textStats.submitted(),
textStats.vanilla(),
textStats.bitmap(),
textStats.msdf(),
textStats.world(),
textStats.effect(),
textStats.clipped(),
textStats.glyphs(),
textStats.meshUploads(),
textStats.routerCacheHits(),
textStats.routerCacheMisses(),
textStats.routerFallbackMisses(),
textStats.adjacentBatchedCommands(),
formatBytes(textStats.uploadedVertexBytes()),
formatBytes(textStats.uploadedIndexBytes())
));
}
var glyphStats = TextRenderSystem.glyphAtlases().stats();
if (glyphStats.pageCount() > 0 || glyphStats.dirtyUploads() > 0) {
lines.add(String.format(
"glyph atlas: pages %d, glyphs %d, dirtyUploads %d, uploaded %s",
glyphStats.pageCount(),
glyphStats.glyphCount(),
glyphStats.dirtyUploads(),
formatBytes(glyphStats.uploadedBytes())
));
}
UiStatsSnapshot uiDraw = Renderer2D.getUiStatsSnapshot();
if (uiDraw.recordedCommands() > 0 || uiDraw.compiledBatches() > 0) {
lines.add(String.format(
"ui commands: total %d, shape/path/tex/text/item/effect %d/%d/%d/%d/%d/%d, compiled %d, backend %d",
uiDraw.recordedCommands(),
uiDraw.shapeCommands(),
uiDraw.pathCommands(),
uiDraw.textureCommands(),
uiDraw.textCommands(),
uiDraw.itemCommands(),
uiDraw.effectCommands(),
uiDraw.compiledBatches(),
uiDraw.backendCommands()
));
}
Renderer2D.BatchStats batch = Renderer2D.getBatchStats();
int frameBatches = batch.getFrameBatches();
int frameDraws = batch.getFrameDraws();
int frameVertices = batch.getFrameVertices();
int frameIndices = batch.getFrameIndices();
Map<Renderer2D.FlushReason, Integer> flushReasons = batch.getFrameFlushReasons();
if (frameBatches > 0 || frameDraws > 0 || frameVertices > 0 || frameIndices > 0 || !flushReasons.isEmpty()) {
lines.add(String.format(
"ui batch: batches %d, draws %d, vertices %d, indices %d, pool %d, last %d/%d/%d, flush %s %s",
frameBatches,
frameDraws,
frameVertices,
frameIndices,
batch.getPoolTotal(),
batch.getLastOrder(),
batch.getLastDraws(),
batch.getLastVertices(),
batch.getLastFlushReason(),
formatFlushReasons(flushReasons)
));
}
if (!batch.getLastError().isEmpty()) {
lines.add("ui batch error: " + batch.getLastError());
}
MeshBuilder.FrameStatsSnapshot mesh = MeshBuilder.frameStatsSnapshot();
if (mesh.initialAllocations() > 0 || mesh.vertexReallocs() > 0 || mesh.indexReallocs() > 0) {
lines.add(String.format(
"ui mesh: alloc %d, realloc v/i %d/%d, bytes %s, max v/i %s/%s",
mesh.initialAllocations(),
mesh.vertexReallocs(),
mesh.indexReallocs(),
formatBytes(mesh.allocatedBytes()),
formatBytes(mesh.maxVertexBytes()),
formatBytes(mesh.maxIndexBytes())
));
}
appendRhiCounters(lines);
var immediatelyFast = CombatantRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
appendCostCounters(lines);
}
private static String formatFlushReasons(Map<Renderer2D.FlushReason, Integer> reasons) {
if (reasons == null || reasons.isEmpty()) return "{}";
List<String> parts = new ArrayList<>();
for (Map.Entry<Renderer2D.FlushReason, Integer> entry : reasons.entrySet()) {
if (entry.getValue() != null && entry.getValue() > 0) {
parts.add(entry.getKey().name().toLowerCase(Locale.ROOT) + "=" + entry.getValue());
}
}
return parts.isEmpty() ? "{}" : "{" + String.join(",", parts) + "}";
}
private static void appendCostCounters(List<String> lines) {
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
if (!phase.isEmpty()) lines.addAll(phase);
List<String> runtime = DevRenderCostProfiler.debugLines("ui cost runtime", "ui.runtime", 8, 0.02);
if (!runtime.isEmpty()) lines.addAll(runtime);
List<String> nodes = DevRenderCostProfiler.debugLines("ui cost nodes", "ui.node", 10, 0.02);
if (!nodes.isEmpty()) lines.addAll(nodes);
List<String> effects = DevRenderCostProfiler.debugLines("ui cost effects", "ui.effect", 8, 0.02);
if (!effects.isEmpty()) lines.addAll(effects);
List<String> items = DevRenderCostProfiler.debugLines("ui cost item render", "item.render", 8, 0.02);
if (!items.isEmpty()) lines.addAll(items);
List<String> rhi = DevRenderCostProfiler.debugLines("ui cost rhi draws", "rhi.draw", 8, 0.02);
if (!rhi.isEmpty()) lines.addAll(rhi);
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
rhi.drawCalls(),
rhi.renderPasses(),
rhi.renderPassAttachmentSwitches(),
rhi.meshUploads(),
rhi.fullscreenPasses(),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
formatBytes(rhi.uploadedVertexBytes()),
formatBytes(rhi.uploadedIndexBytes())
));
}
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
lines.add(String.format(
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaReuses(),
rhi.dynamicArenaRetires()
));
}
if (rhi.legacyPathUses() > 0) {
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
}
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
lines.add(String.format(
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
uniforms.writes(),
formatBytes(uniforms.uploadedBytes()),
uniforms.activeStreams(),
uniforms.ringRotations(),
uniforms.ringGrows(),
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = CombatantRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
resources.persistentFramebuffers(),
resources.temporaryFramebuffers(),
resources.framebufferCreates(),
resources.framebufferResizes(),
resources.framebufferBorrows(),
resources.framebufferReleases(),
resources.retirementBacklog(),
resources.leakedResources()
));
}
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void collectFlat(Node node, List<Node> out) {
for (Node child : node.children.values()) {
out.add(child);
collectFlat(child, out);
}
}
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
if (node == null) return;
double ms = node.totalNs / (double) NS_IN_MS;
if (depth > 0 && ms < minMs) return;
double selfMs = selfNs(node) / (double) NS_IN_MS;
String line = depth == 0
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
out.add(line);
if (depth >= maxDepth) return;
List<Node> children = new ArrayList<>(node.children.values());
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
String childIndent = indent + "| ";
for (Node child : children) {
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
}
}
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (RuntimeGate.isPanic()) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;
if (mode == ProfilerSettings.OutputMode.LOG) {
emitToLog();
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
emitToChat();
}
}
private static ProfilerSettings.OutputMode getOutputMode() {
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
return getOutputModeRaw();
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getOutput2d();
}
private static void emitToLog() {
List<String> lines = getDebugLines();
if (lines.isEmpty()) return;
for (String line : lines) {
ProfilerLog.info("[UIProfiler] %s", line);
}
}
private static void emitToChat() {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
List<String> lines = getDebugLines(4, 2, 0.05);
if (lines.isEmpty()) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[UIProfiler] " + line));
}
}
private static long selfNs(Node node) {
if (node == null) return 0L;
long childrenNs = 0L;
for (Node child : node.children.values()) {
childrenNs += child.totalNs;
}
long self = node.totalNs - childrenNs;
return Math.max(0L, self);
}
private static Node hottestChild(Node node) {
if (node == null || node.children.isEmpty()) return null;
Node best = null;
long bestNs = 0L;
for (Node child : node.children.values()) {
if (best == null || child.totalNs > bestNs) {
best = child;
bestNs = child.totalNs;
}
}
return best;
}
private static String nodePath(Node node) {
if (node == null) return "";
List<String> parts = new ArrayList<>();
Node cur = node;
while (cur != null) {
parts.add(cur.name);
cur = cur.parent;
}
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0; i--) {
if (sb.length() > 0) sb.append(" > ");
sb.append(parts.get(i));
}
return sb.toString();
}
public static final class Section implements AutoCloseable {
private static final Section NOOP = new Section(false);
private final boolean active;
private Section(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
endSection();
}
}
private static final class Node {
final String name;
final Node parent;
final Map<String, Node> children = new HashMap<>();
long totalNs;
long startNs;
int calls;
private Node(String name, Node parent) {
this.name = name;
this.parent = parent;
}
int countNodes() {
int count = 1;
for (Node child : children.values()) {
count += child.countNodes();
}
return count;
}
}
}

View file

@ -0,0 +1,421 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.render.engine.world.WorldRenderStatsSnapshot;
import dev.loki.lovisual.render.iris.IrisRuntimeSnapshot;
import dev.loki.lovisual.render.sodium.SodiumTerrainInteropStatsSnapshot;
import dev.loki.lovisual.render.sodium.SodiumVisibilityStatsSnapshot;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.*;
public enum DevRenderProfiler3D {
;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_TOP_LIMIT = 6;
private static final int DEFAULT_TREE_DEPTH = 32;
private static final double DEFAULT_MIN_MS = 0.0;
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
private static boolean active;
private static Node root;
private static Node snapshot;
private static long lastEmitNs;
public static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static void beginFrame(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
if (!isEnabled()) return;
active = true;
root = new Node(name, null);
stack.clear();
stack.push(root);
root.startNs = System.nanoTime();
}
public static boolean beginFrameIfNeeded(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
if (!isEnabled() || active) return false;
beginFrame(name);
return true;
}
public static void endFrame() {
if (!isEnabled() || !active) return;
long now = System.nanoTime();
while (stack.size() > 1) {
endSection();
}
Node r = stack.peek();
if (r != null) {
r.calls = Math.max(1, r.calls);
r.totalNs += now - r.startNs;
r.startNs = 0L;
snapshot = r;
DevTracyProfiler.plotWorldFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
}
active = false;
emitIfDue(now);
}
public static Section section(String name) {
if (!isEnabled() || !active) return Section.NOOP;
beginSection(name);
return new Section(true);
}
private static void beginSection(String name) {
Node parent = stack.peek();
if (parent == null) return;
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
child.calls += 1;
child.startNs = System.nanoTime();
stack.push(child);
}
private static void endSection() {
Node node = stack.poll();
if (node == null) return;
long now = System.nanoTime();
node.totalNs += now - node.startNs;
node.startNs = 0L;
}
public static List<String> getDebugLines() {
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
}
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
if (!isEnabled()) return List.of();
Node snap = snapshot;
if (snap == null) return List.of();
List<String> lines = new ArrayList<>();
double totalMs = snap.totalNs / (double) NS_IN_MS;
lines.add(String.format("world prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
appendRhiCounters(lines);
appendCostCounters(lines);
List<Node> flat = new ArrayList<>();
collectFlat(snap, flat);
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
int top = Math.min(topLimit, flat.size());
if (top > 0) {
lines.add("world prof top:");
for (int i = 0; i < top; i++) {
Node n = flat.get(i);
double ms = n.totalNs / (double) NS_IN_MS;
if (ms < minMs) break;
double selfMs = selfNs(n) / (double) NS_IN_MS;
Node hot = hottestChild(n);
if (hot != null) {
double hotMs = hot.totalNs / (double) NS_IN_MS;
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
hot.name,
hotMs,
n.calls
));
} else {
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
n.calls
));
}
}
}
lines.add("world prof tree:");
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
return lines;
}
private static void appendCostCounters(List<String> lines) {
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
if (!phase.isEmpty()) lines.addAll(phase);
List<String> post = DevRenderCostProfiler.debugLines("world cost post", "post.pass", 8, 0.02);
if (!post.isEmpty()) lines.addAll(post);
List<String> effects = DevRenderCostProfiler.debugLines("world cost effects", "world.effect", 8, 0.02);
if (!effects.isEmpty()) lines.addAll(effects);
List<String> rhi = DevRenderCostProfiler.debugLines("world cost rhi draws", "rhi.draw", 8, 0.02);
if (!rhi.isEmpty()) lines.addAll(rhi);
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
rhi.drawCalls(),
rhi.renderPasses(),
rhi.renderPassAttachmentSwitches(),
rhi.meshUploads(),
rhi.fullscreenPasses(),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
formatBytes(rhi.uploadedVertexBytes()),
formatBytes(rhi.uploadedIndexBytes())
));
}
WorldRenderStatsSnapshot world = CombatantRenderSystem.worldRenderStatsSnapshot();
if (world.recordedCommands() > 0 || world.submittedCommands() > 0 || world.skippedEmptyCommands() > 0) {
lines.add(String.format(
"world3d: commands rec/sub/skip %d/%d/%d, vertices/indices %d/%d, fog %d, depth pre/main/none %d/%d/%d",
world.recordedCommands(),
world.submittedCommands(),
world.skippedEmptyCommands(),
world.submittedVertices(),
world.submittedIndices(),
world.fogBindings(),
world.depthPrePassBindings(),
world.depthMainBindings(),
world.depthDisabledBindings()
));
}
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
lines.add(String.format(
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaReuses(),
rhi.dynamicArenaRetires()
));
}
if (rhi.legacyPathUses() > 0) {
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
}
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
lines.add(String.format(
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
uniforms.writes(),
formatBytes(uniforms.uploadedBytes()),
uniforms.activeStreams(),
uniforms.ringRotations(),
uniforms.ringGrows(),
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = CombatantRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
resources.persistentFramebuffers(),
resources.temporaryFramebuffers(),
resources.framebufferCreates(),
resources.framebufferResizes(),
resources.framebufferBorrows(),
resources.framebufferReleases(),
resources.retirementBacklog(),
resources.leakedResources()
));
}
IrisRuntimeSnapshot iris = CombatantRenderSystem.irisSnapshot();
if (iris.modLoaded() || iris.shaderpackInUse()) {
lines.add(iris.shortLine());
}
var immediatelyFast = CombatantRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
SodiumVisibilityStatsSnapshot sodiumVisibility = CombatantRenderSystem.sodiumVisibilityStatsSnapshot();
if (sodiumVisibility.queries() > 0 || sodiumVisibility.errors() > 0) {
lines.add(String.format(
"sodium vis: queries %d, accepts/rejects %d/%d, bypass %d (unavail %d, optout %d), errors %d",
sodiumVisibility.queries(),
sodiumVisibility.accepts(),
sodiumVisibility.rejects(),
sodiumVisibility.bypasses(),
sodiumVisibility.unavailableBypasses(),
sodiumVisibility.optOutBypasses(),
sodiumVisibility.errors()
));
}
SodiumTerrainInteropStatsSnapshot sodiumTerrain = CombatantRenderSystem.sodiumTerrainStatsSnapshot();
if (sodiumTerrain.terrainUpdatesScheduled() > 0
|| sodiumTerrain.rebuildsScheduled() > 0
|| sodiumTerrain.interopErrors() > 0) {
lines.add(String.format(
"sodium terrain: updates %d, rebuilds %d, errors %d",
sodiumTerrain.terrainUpdatesScheduled(),
sodiumTerrain.rebuildsScheduled(),
sodiumTerrain.interopErrors()
));
}
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void collectFlat(Node node, List<Node> out) {
for (Node child : node.children.values()) {
out.add(child);
collectFlat(child, out);
}
}
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
if (node == null) return;
double ms = node.totalNs / (double) NS_IN_MS;
if (depth > 0 && ms < minMs) return;
double selfMs = selfNs(node) / (double) NS_IN_MS;
String line = depth == 0
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
out.add(line);
if (depth >= maxDepth) return;
List<Node> children = new ArrayList<>(node.children.values());
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
String childIndent = indent + "| ";
for (Node child : children) {
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
}
}
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (RuntimeGate.isPanic()) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;
if (mode == ProfilerSettings.OutputMode.LOG) {
emitToLog();
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
emitToChat();
}
}
private static ProfilerSettings.OutputMode getOutputMode() {
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
return getOutputModeRaw();
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getOutput3d();
}
private static void emitToLog() {
List<String> lines = getDebugLines();
if (lines.isEmpty()) return;
for (String line : lines) {
ProfilerLog.info("[WorldProfiler] %s", line);
}
}
private static void emitToChat() {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
List<String> lines = getDebugLines(4, 2, 0.05);
if (lines.isEmpty()) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[WorldProfiler] " + line));
}
}
private static long selfNs(Node node) {
if (node == null) return 0L;
long childrenNs = 0L;
for (Node child : node.children.values()) {
childrenNs += child.totalNs;
}
long self = node.totalNs - childrenNs;
return Math.max(0L, self);
}
private static Node hottestChild(Node node) {
if (node == null || node.children.isEmpty()) return null;
Node best = null;
long bestNs = 0L;
for (Node child : node.children.values()) {
if (best == null || child.totalNs > bestNs) {
best = child;
bestNs = child.totalNs;
}
}
return best;
}
private static String nodePath(Node node) {
if (node == null) return "";
List<String> parts = new ArrayList<>();
Node cur = node;
while (cur != null) {
parts.add(cur.name);
cur = cur.parent;
}
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0; i--) {
if (sb.length() > 0) sb.append(" > ");
sb.append(parts.get(i));
}
return sb.toString();
}
public static final class Section implements AutoCloseable {
private static final Section NOOP = new Section(false);
private final boolean active;
private Section(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
endSection();
}
}
private static final class Node {
final String name;
final Node parent;
final Map<String, Node> children = new HashMap<>();
long totalNs;
long startNs;
int calls;
private Node(String name, Node parent) {
this.name = name;
this.parent = parent;
}
int countNodes() {
int count = 1;
for (Node child : children.values()) {
count += child.countNodes();
}
return count;
}
}
}

View file

@ -0,0 +1,447 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.runtime.RuntimeGate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public enum DevSamplingProfiler {
;
private static final long SAMPLE_INTERVAL_NS = 10_000_000L; // 10 ms
private static final long EMIT_INTERVAL_NS = 1_000_000_000L; // 1 s
private static final int TOP_LIMIT = 8;
private static final int TOP_LIMIT_NON_GL = 4;
private static final int TOP_LIMIT_GL_WAIT = 3;
private static final int MAX_STACK_FRAMES = 4;
private static final int MAX_ENTRIES = 256;
private static final Object LOCK = new Object();
private static final Map<String, Integer> COUNTS = new HashMap<>();
private static int idleSamples;
private static volatile Thread targetThread;
private static volatile Thread samplerThread;
private static volatile boolean running;
private static volatile long lastEmitNs;
private static volatile List<String> pendingChatLines;
private static volatile Target lastSource = Target.WORLD;
public static void onClientFrame(Target source) {
if (!isEnabled()) {
DevProfilerPhase.clearCurrent();
stopIfRunning();
return;
}
if (RuntimeGate.isPanic()) return;
lastSource = source;
flushPendingChat();
if (!matchesTarget(source)) return;
targetThread = Thread.currentThread();
ensureRunning();
}
private static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static boolean isActive() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
private static void ensureRunning() {
if (running) return;
running = true;
samplerThread = new Thread(DevSamplingProfiler::runLoop, "Combatant-DevSamplingProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
private static void stopIfRunning() {
if (!running) return;
running = false;
Thread t = samplerThread;
samplerThread = null;
if (t != null) t.interrupt();
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
DevGlSyncTracker.reset();
pendingChatLines = null;
}
private static void runLoop() {
long lastSampleNs = 0L;
while (running) {
if (!isEnabled()) {
running = false;
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
DevGlSyncTracker.reset();
pendingChatLines = null;
break;
}
if (RuntimeGate.isPanic()) {
sleepMs(20);
continue;
}
Thread t = targetThread;
if (t == null) {
sleepMs(10);
continue;
}
long now = System.nanoTime();
if (now - lastSampleNs >= SAMPLE_INTERVAL_NS) {
if (matchesTarget(lastSource)) {
sample(t);
}
lastSampleNs = now;
}
if (now - lastEmitNs >= EMIT_INTERVAL_NS) {
emit(now);
}
sleepMs(2);
}
}
private static void sample(Thread t) {
StackTraceElement[] stack = t.getStackTrace();
if (stack == null || stack.length == 0) return;
if (isIdleStack(stack)) {
synchronized (LOCK) {
idleSamples += 1;
}
return;
}
String key = buildKey(stack);
if (key == null || key.isEmpty()) return;
synchronized (LOCK) {
COUNTS.merge(key, 1, Integer::sum);
if (COUNTS.size() > MAX_ENTRIES) {
trimToLimit();
}
}
}
private static void emit(long now) {
ProfilerSettings.OutputMode mode = getOutputModeRaw();
if (mode == ProfilerSettings.OutputMode.OFF) return;
List<String> lines = buildOutputLines();
if (lines.isEmpty()) return;
lastEmitNs = now;
if (mode == ProfilerSettings.OutputMode.LOG) {
for (String line : lines) {
ProfilerLog.info("[SampleProfiler] %s", line);
}
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
pendingChatLines = lines;
}
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
}
private static List<String> buildOutputLines() {
List<Map.Entry<String, Integer>> entries;
int total;
int idle;
synchronized (LOCK) {
if (COUNTS.isEmpty() && idleSamples == 0) return List.of();
entries = new ArrayList<>(COUNTS.entrySet());
int sum = 0;
for (Integer count : COUNTS.values()) {
if (count != null) {
sum += count;
}
}
total = sum;
idle = idleSamples;
}
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
List<String> lines = new ArrayList<>();
int all = total + idle;
double idlePct = all == 0 ? 0.0 : (idle * 100.0) / all;
lines.add(String.format("sample prof: %d samples, idle %d (%.1f%%), entries %d", all, idle, idlePct, entries.size()));
int glWait = 0;
int glUpload = 0;
int glDraw = 0;
int glState = 0;
int glWaitClient = 0;
int glWaitSwap = 0;
int glWaitFinish = 0;
int glWaitSync = 0;
int glWaitOther = 0;
List<Map.Entry<String, Integer>> nonGl = new ArrayList<>();
List<Map.Entry<String, Integer>> glWaitList = new ArrayList<>();
for (Map.Entry<String, Integer> e : entries) {
String k = e.getKey();
int c = e.getValue();
if (k.startsWith("GL WAIT:")) {
glWait += c;
glWaitList.add(e);
if (containsAny(k, "glClientWaitSync", "nglClientWaitSync")) {
glWaitClient += c;
} else if (containsAny(k, "glfwSwapBuffers")) {
glWaitSwap += c;
} else if (containsAny(k, "glFinish", "nglFinish")) {
glWaitFinish += c;
} else if (containsAny(k, "glWaitSync", "nglWaitSync")) {
glWaitSync += c;
} else {
glWaitOther += c;
}
} else if (k.startsWith("GL UPLOAD:")) {
glUpload += c;
} else if (k.startsWith("GL DRAW:")) {
glDraw += c;
} else if (k.startsWith("GL STATE:")) {
glState += c;
} else {
nonGl.add(e);
}
}
int glTotal = glWait + glUpload + glDraw + glState;
if (glTotal > 0) {
double waitPct = all == 0 ? 0.0 : (glWait * 100.0) / all;
double uploadPct = all == 0 ? 0.0 : (glUpload * 100.0) / all;
double drawPct = all == 0 ? 0.0 : (glDraw * 100.0) / all;
double statePct = all == 0 ? 0.0 : (glState * 100.0) / all;
lines.add(String.format(
"gl samples: wait %d (%.1f%%), upload %d (%.1f%%), draw %d (%.1f%%), state %d (%.1f%%)",
glWait, waitPct, glUpload, uploadPct, glDraw, drawPct, glState, statePct
));
if (glWait > 0) {
lines.add(String.format(
"gl wait breakdown: client %d, swap %d, finish %d, waitsync %d, other %d",
glWaitClient, glWaitSwap, glWaitFinish, glWaitSync, glWaitOther
));
}
}
List<String> waitPhaseLines = DevGlSyncTracker.drainLines();
if (!waitPhaseLines.isEmpty()) {
lines.addAll(waitPhaseLines);
}
lines.add("sample prof top:");
int top = Math.min(TOP_LIMIT, entries.size());
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> e = entries.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
if (!nonGl.isEmpty()) {
int topNon = Math.min(TOP_LIMIT_NON_GL, nonGl.size());
lines.add("sample prof top non-gl:");
for (int i = 0; i < topNon; i++) {
Map.Entry<String, Integer> e = nonGl.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
}
if (!glWaitList.isEmpty()) {
int topWait = Math.min(TOP_LIMIT_GL_WAIT, glWaitList.size());
lines.add("sample prof top gl wait:");
for (int i = 0; i < topWait; i++) {
Map.Entry<String, Integer> e = glWaitList.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
}
return lines;
}
private static void flushPendingChat() {
List<String> lines = pendingChatLines;
if (lines == null || lines.isEmpty()) return;
pendingChatLines = null;
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[SampleProfiler] " + line));
}
}
private static String buildKey(StackTraceElement[] stack) {
StringBuilder sb = new StringBuilder();
String glCat = glCategory(stack);
boolean hasPrefix = false;
if (glCat != null) {
sb.append("GL ").append(glCat).append(": ");
hasPrefix = true;
}
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isNoise(e)) continue;
if (added > 0 || (sb.length() > 0 && !hasPrefix)) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? null : sb.toString();
}
private static boolean isNoise(StackTraceElement e) {
String cls = e.getClassName();
return cls.startsWith("java.lang.Thread")
|| cls.startsWith("java.util.concurrent")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevSamplingProfiler");
}
private static String glCategory(StackTraceElement[] stack) {
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if (!isGlFrame(cls)) continue;
String cat = glCategoryForMethod(method);
if (cat != null) return cat;
}
return null;
}
private static boolean isGlFrame(String cls) {
if (cls == null) return false;
return cls.startsWith("org.lwjgl.opengl.")
|| cls.startsWith("org.lwjgl.glfw.")
|| cls.startsWith("com.mojang.blaze3d.platform.")
|| cls.startsWith("com.mojang.blaze3d.systems.");
}
private static String glCategoryForMethod(String method) {
if (method == null) return null;
if (method.equals("glfwSwapBuffers")
|| method.equals("glClientWaitSync")
|| method.equals("glWaitSync")
|| method.equals("glFinish")) {
return "WAIT";
}
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
return "DRAW";
}
if (method.contains("BufferSubData")
|| method.contains("BufferData")
|| method.contains("TexImage")
|| method.contains("TexSubImage")
|| method.contains("CompressedTex")
|| method.contains("FlushMapped")
|| method.contains("MapBuffer")
|| method.contains("MapBufferRange")
|| method.contains("UnmapBuffer")) {
return "UPLOAD";
}
if (method.startsWith("glUseProgram")
|| method.startsWith("glBind")
|| method.startsWith("glTexParameter")
|| method.startsWith("glBlendFunc")
|| method.startsWith("glBlendEquation")
|| method.startsWith("glEnable")
|| method.startsWith("glDisable")
|| method.startsWith("glDepthFunc")
|| method.startsWith("glDepthMask")
|| method.startsWith("glColorMask")
|| method.startsWith("glCullFace")
|| method.startsWith("glFrontFace")
|| method.startsWith("glViewport")
|| method.startsWith("glScissor")
|| method.startsWith("glPolygonMode")
|| method.startsWith("glActiveTexture")
|| method.startsWith("glUniform")
|| method.startsWith("glVertexAttrib")) {
return "STATE";
}
return null;
}
private static boolean containsAny(String text, String... needles) {
if (text == null) return false;
for (String n : needles) {
if (n != null && !n.isEmpty() && text.contains(n)) return true;
}
return false;
}
private static boolean isIdleStack(StackTraceElement[] stack) {
boolean hasWait = false;
boolean hasLimit = false;
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if ("org.lwjgl.glfw.GLFW".equals(cls) && "glfwWaitEventsTimeout".equals(method)) {
hasWait = true;
}
if ("com.mojang.blaze3d.systems.RenderSystem".equals(cls) && "limitDisplayFPS".equals(method)) {
hasLimit = true;
}
if (hasWait || hasLimit) {
return true;
}
}
return false;
}
private static String formatElement(StackTraceElement e) {
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
int line = e.getLineNumber();
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + line + ")";
}
private static boolean matchesTarget(Target source) {
if (source == null) return true;
Target target = getTargetRaw();
return target == Target.ALL || target == source;
}
private static Target getTargetRaw() {
ProfilerSettings.SampleTarget target = ProfilerSettings.getSampleTarget();
if (target == null) return Target.ALL;
return switch (target) {
case D2 -> Target.UI;
case D3 -> Target.WORLD;
case ALL -> Target.ALL;
};
}
private static void trimToLimit() {
if (COUNTS.size() <= MAX_ENTRIES) return;
List<Map.Entry<String, Integer>> entries = new ArrayList<>(COUNTS.entrySet());
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
for (int i = MAX_ENTRIES; i < entries.size(); i++) {
COUNTS.remove(entries.get(i).getKey());
}
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getSampleOutput();
}
private static void sleepMs(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
// ignore
}
}
public enum Target {
ALL,
UI,
WORLD
}
}

View file

@ -0,0 +1,150 @@
package dev.loki.lovisual.render.engine.profiler;
import com.mojang.jtracy.GpuApi;
import com.mojang.jtracy.GpuContext;
import com.mojang.jtracy.TracyClient;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL15C;
import org.lwjgl.opengl.GL33C;
import org.lwjgl.opengl.GLCapabilities;
import dev.loki.lovisual.render.engine.guard.LegacyRenderPath;
import dev.loki.lovisual.render.engine.guard.RenderBoundaryExempt;
import java.util.ArrayDeque;
@RenderBoundaryExempt(value = LegacyRenderPath.DIRECT_GL_OUTSIDE_BACKEND, reason = "Profiler-only timer query path; not part of renderer submission architecture")
public enum DevTracyGpuProfiler {
;
private static final Scope NOOP_SCOPE = new Scope(false);
private static final Object LOCK = new Object();
private static final ArrayDeque<QueryEvent> PENDING = new ArrayDeque<>();
private static final ArrayDeque<Integer> FREE_GL_QUERIES = new ArrayDeque<>();
private static volatile boolean initAttempted;
private static volatile boolean available;
private static volatile GpuContext context;
private static int nextQueryId = 1;
public static boolean isEnabled() {
return DevTracyProfiler.isEnabled() && isAvailable();
}
public static Scope beginZone(String name) {
if (!isEnabled() || name == null || name.isBlank()) {
return NOOP_SCOPE;
}
int beginId = allocateQueryId();
int beginQuery = allocateGlQuery();
context.beginZone(beginId, name, "", "", 0);
GL33C.glQueryCounter(beginQuery, GL33C.GL_TIMESTAMP);
enqueue(beginId, beginQuery);
return new Scope(true);
}
public static void onFrameEnd() {
if (!isEnabled()) {
return;
}
pump();
}
private static boolean isAvailable() {
ensureContext();
return available;
}
private static void ensureContext() {
if (initAttempted) {
return;
}
synchronized (LOCK) {
if (initAttempted) {
return;
}
initAttempted = true;
try {
GLCapabilities caps = GL.getCapabilities();
boolean timerQuery = caps.OpenGL33 || caps.GL_ARB_timer_query;
if (!timerQuery) {
available = false;
ProfilerLog.warn("Tracy GPU unavailable: timer queries are not supported by this OpenGL context");
return;
}
long gpuTimestamp = GL33C.glGetInteger64(GL33C.GL_TIMESTAMP);
context = TracyClient.createGpuContext(GpuApi.OPENGL, gpuTimestamp, 1.0f);
context.setName("main");
available = true;
ProfilerLog.info("Tracy GPU context initialized");
} catch (Throwable t) {
available = false;
ProfilerLog.warn("Tracy GPU unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
}
private static void pump() {
synchronized (LOCK) {
while (!PENDING.isEmpty()) {
QueryEvent event = PENDING.peekFirst();
if (GL15C.glGetQueryObjecti(event.glQuery, GL15C.GL_QUERY_RESULT_AVAILABLE) == 0) {
break;
}
long timestamp = GL33C.glGetQueryObjecti64(event.glQuery, GL15C.GL_QUERY_RESULT);
context.submitQueryTimestamp(event.queryId, timestamp);
PENDING.removeFirst();
FREE_GL_QUERIES.addLast(event.glQuery);
}
}
}
private static void enqueue(int queryId, int glQuery) {
synchronized (LOCK) {
PENDING.addLast(new QueryEvent(queryId, glQuery));
}
}
private static int allocateQueryId() {
synchronized (LOCK) {
int id = nextQueryId++;
if (id <= 0) {
nextQueryId = 1;
id = nextQueryId++;
}
return id;
}
}
private static int allocateGlQuery() {
synchronized (LOCK) {
Integer existing = FREE_GL_QUERIES.pollFirst();
if (existing != null) {
return existing;
}
}
return GL15C.glGenQueries();
}
private record QueryEvent(int queryId, int glQuery) {
}
public static final class Scope implements AutoCloseable {
private final boolean active;
private Scope(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active || !isEnabled()) {
return;
}
int endId = allocateQueryId();
int endQuery = allocateGlQuery();
context.endZone(endId);
GL33C.glQueryCounter(endQuery, GL33C.GL_TIMESTAMP);
enqueue(endId, endQuery);
}
}
}

View file

@ -0,0 +1,230 @@
package dev.loki.lovisual.render.engine.profiler;
import com.mojang.jtracy.Plot;
import com.mojang.jtracy.TracyClient;
import com.mojang.jtracy.Zone;
public enum DevTracyProfiler {
;
private static final Scope NOOP_SCOPE = new Scope(null);
private static final ThreadLocal<Boolean> THREAD_NAMED =
ThreadLocal.withInitial(() -> Boolean.FALSE);
private static volatile boolean loadAttempted;
private static volatile boolean available;
private static volatile Plot uiFrameMsPlot;
private static volatile Plot uiNodeCountPlot;
private static volatile Plot worldFrameMsPlot;
private static volatile Plot worldNodeCountPlot;
private static volatile Plot glWaitMsPlot;
private static volatile Plot glWaitCallsPlot;
private static volatile Plot uiBatchDrawsPlot;
private static volatile Plot uiBatchVerticesPlot;
public static boolean isEnabled() {
return ProfilerSettings.isTracyEnabled() && isAvailable();
}
public static boolean isAvailable() {
ensureLoaded();
return available;
}
public static synchronized boolean setEnabled(boolean enabled) {
ProfilerSettings.setTracyEnabled(enabled);
if (!enabled) {
ProfilerLog.info("Tracy disabled");
return false;
}
boolean active = isAvailable();
if (active) {
ProfilerLog.info("Tracy enabled; data is streamed to the external Tracy viewer, not latest.log");
TracyClient.message("Combatant Tracy enabled");
}
return active;
}
public static Scope beginZone(String name) {
if (!isEnabled() || name == null || name.isBlank()) {
return NOOP_SCOPE;
}
ensureThreadNamed();
return new Scope(TracyClient.beginZone(name, false));
}
public static void markFrame() {
if (!isEnabled()) return;
ensureThreadNamed();
TracyClient.markFrame();
}
public static boolean shouldTraceCurrentThread() {
String threadName = Thread.currentThread().getName();
if (threadName == null || threadName.isBlank()) {
return false;
}
return "Render thread".equals(threadName)
|| threadName.startsWith("Render thread")
|| "main".equals(threadName)
|| "Main thread".equals(threadName);
}
public static void plotUiFrame(double ms, int nodes) {
if (!isEnabled()) return;
plotUiFrameMs().setValue(ms);
plotUiNodeCount().setValue(nodes);
}
public static void plotWorldFrame(double ms, int nodes) {
if (!isEnabled()) return;
plotWorldFrameMs().setValue(ms);
plotWorldNodeCount().setValue(nodes);
}
public static void plotGlWait(double ms, int calls) {
if (!isEnabled()) return;
plotGlWaitMs().setValue(ms);
plotGlWaitCalls().setValue(calls);
}
public static void plotUiBatch(int draws, int vertices) {
if (!isEnabled()) return;
plotUiBatchDraws().setValue(draws);
plotUiBatchVertices().setValue(vertices);
}
private static void ensureLoaded() {
if (loadAttempted) {
return;
}
synchronized (DevTracyProfiler.class) {
if (loadAttempted) {
return;
}
loadAttempted = true;
try {
TracyClient.load();
TracyClient.reportAppInfo("Combatant render profiler");
available = TracyClient.isAvailable();
if (available) {
ProfilerLog.info("Tracy client loaded");
}
} catch (Throwable t) {
available = false;
ProfilerLog.warn("Tracy unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
}
private static void ensureThreadNamed() {
if (Boolean.TRUE.equals(THREAD_NAMED.get())) {
return;
}
TracyClient.setThreadName(Thread.currentThread().getName(), 0);
THREAD_NAMED.set(Boolean.TRUE);
}
private static Plot plotUiFrameMs() {
Plot plot = uiFrameMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiFrameMsPlot == null) {
uiFrameMsPlot = TracyClient.createPlot("render.ui.ms");
}
return uiFrameMsPlot;
}
}
private static Plot plotUiNodeCount() {
Plot plot = uiNodeCountPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiNodeCountPlot == null) {
uiNodeCountPlot = TracyClient.createPlot("render.ui.nodes");
}
return uiNodeCountPlot;
}
}
private static Plot plotWorldFrameMs() {
Plot plot = worldFrameMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (worldFrameMsPlot == null) {
worldFrameMsPlot = TracyClient.createPlot("render.world.ms");
}
return worldFrameMsPlot;
}
}
private static Plot plotWorldNodeCount() {
Plot plot = worldNodeCountPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (worldNodeCountPlot == null) {
worldNodeCountPlot = TracyClient.createPlot("render.world.nodes");
}
return worldNodeCountPlot;
}
}
private static Plot plotGlWaitMs() {
Plot plot = glWaitMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (glWaitMsPlot == null) {
glWaitMsPlot = TracyClient.createPlot("render.gl_wait.ms");
}
return glWaitMsPlot;
}
}
private static Plot plotGlWaitCalls() {
Plot plot = glWaitCallsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (glWaitCallsPlot == null) {
glWaitCallsPlot = TracyClient.createPlot("render.gl_wait.calls");
}
return glWaitCallsPlot;
}
}
private static Plot plotUiBatchDraws() {
Plot plot = uiBatchDrawsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiBatchDrawsPlot == null) {
uiBatchDrawsPlot = TracyClient.createPlot("render.ui_batch.draws");
}
return uiBatchDrawsPlot;
}
}
private static Plot plotUiBatchVertices() {
Plot plot = uiBatchVerticesPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiBatchVerticesPlot == null) {
uiBatchVerticesPlot = TracyClient.createPlot("render.ui_batch.vertices");
}
return uiBatchVerticesPlot;
}
}
public static final class Scope implements AutoCloseable {
private final Zone zone;
private Scope(Zone zone) {
this.zone = zone;
}
@Override
public void close() {
if (zone != null) {
zone.close();
}
}
}
}

View file

@ -0,0 +1,16 @@
{
"required": true,
"plugin": "dev.loki.lovisual.mixins.LoVisualMixinPlugin",
"minVersion": "0.8",
"package": "dev.loki.lovisual.mixins",
"compatibilityLevel": "JAVA_21",
"client": [
"ProfilersMixin"
],
"injectors": {
"defaultRequire": 1
},
"overwrites": {
"requireAnnotations": true
}
}

View file

@ -0,0 +1,525 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual;
import dev.loki.lovisual.events.impl.GameTickEvent;
import dev.loki.lovisual.runtime.*;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.rendering.v1.hud.HudElementRegistry;
import net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements;
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.resources.Identifier;
import dev.loki.lovisual.addon.AddonManager;
import dev.loki.lovisual.addon.AddonRenderPipelineManager;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import dev.loki.lovisual.config.MainConfig;
import dev.loki.lovisual.events.Events;
import dev.loki.lovisual.features.account.AccountConfig;
import dev.loki.lovisual.features.command.CommandManager;
import dev.loki.lovisual.features.command.VanillaChatRuntimeCleanup;
import dev.loki.lovisual.features.gui.clickgui.ClickGuiRenderer;
import dev.loki.lovisual.features.gui.clickgui.settings.I18nPreflightContributors;
import dev.loki.lovisual.features.gui.hud.HudElements;
import dev.loki.lovisual.features.gui.hud.HudRenderSpace;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementBootstrap;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.impl.SwapTooltip;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.mixininterface.IGuiGraphics;
import dev.loki.lovisual.render.effects.NetherPortalRiftPass;
import dev.loki.lovisual.render.effects.SleepOverlayPass;
import dev.loki.lovisual.render.engine.CombatantRenderEngineBootstrap;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.RenderPhase;
import dev.loki.lovisual.render.engine.core.RenderPhaseScope;
import dev.loki.lovisual.render.engine.core.ViewportContext;
import dev.loki.lovisual.render.engine.postprocess.PostProcessManager;
import dev.loki.lovisual.render.engine.profiler.ProfilerPhase;
import dev.loki.lovisual.render.engine.profiler.RenderProfiler2D;
import dev.loki.lovisual.render.engine.renderer.FullScreenRenderer;
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmContributors;
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmManager;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
import dev.loki.lovisual.render.helpers.SystemCursor;
import dev.loki.lovisual.render.helpers.TickDelta;
import dev.loki.lovisual.util.aiming.RotationManager;
import dev.loki.lovisual.util.block.bed.SelfBedTracker;
import dev.loki.lovisual.util.click.AttackPressing;
import dev.loki.lovisual.util.combat.AntiBotTracker;
import dev.loki.lovisual.util.combat.protocol.CombatProtocolHeuristics;
import dev.loki.lovisual.util.combat.SprintController;
import dev.loki.lovisual.util.combat.VulcanReachController;
import dev.loki.lovisual.util.entity.simulation.BoatSimulationCache;
import dev.loki.lovisual.util.media.MediaSessionService;
import dev.loki.lovisual.util.network.BacktrackController;
import dev.loki.lovisual.util.network.BlinkManager;
import dev.loki.lovisual.util.proxy.ProxyBackend;
import dev.loki.lovisual.util.network.FakeLagController;
import dev.loki.lovisual.util.player.inventory.InventorySwap;
import dev.loki.lovisual.util.player.simulation.PlayerSimulationCache;
import dev.loki.lovisual.util.pvp.PvpTargetTracker;
import dev.loki.lovisual.util.pvp.PvpTracker;
import dev.loki.lovisual.util.target.TargetManager;
import dev.loki.lovisual.util.time.TimerController;
public class LoVisual implements ClientModInitializer {
private static void registerRuntimeLifecycle() {
AddonManager.registerRuntimeLifecycle();
ClientRuntime.setCallbackCounter(Events.BUS::listenerCount);
ClientRuntime.setModuleCounter(ModuleManager::registeredCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ModuleManager.shutdownForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void resume(String reason) {
ModuleManager.restoreAfterSoftPanic(reason);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "clickgui";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ClickGuiRenderer.shutdownForRuntime();
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "vanilla_chat";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
VanillaChatRuntimeCleanup.clearVanillaChatCache();
context.increment("vanillaChatCleared", 1);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "hud";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
DraggableHudElementRegistry.clearRuntimeReferences();
StaticHudElementRegistry.clearRuntimeReferences();
}
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "render";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
PostProcessManager.shutdownForRuntime();
CombatantRenderSystem.shutdown();
}
}
});
}
private static void renderWorldPhase(WorldPhase phase,
com.mojang.blaze3d.vertex.PoseStack matrices,
net.minecraft.client.renderer.SubmitNodeCollector consumers) {
if (!RuntimeGate.canRunRender()) return;
ModuleManager.renderWorld(
phase,
matrices,
consumers,
TickDelta.tickProgress(false)
);
}
private static void refreshHudFrameTiming(DeltaTracker tickCounter) {
CombatantRenderSystem.updateFrameTiming(
TickDelta.tickProgress(tickCounter, false),
TickDelta.frameDeltaTicks(tickCounter),
TickDelta.fixedDeltaTicks(tickCounter)
);
}
private static void renderHudPhase(HudPhase phase, GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
if (!RuntimeGate.canRunHud()) return;
float tickProgress = TickDelta.tickProgress(tickCounter, false);
ModuleManager.renderHud(phase, ctx, tickProgress);
Renderer2D.Deferred2DLayer layer = deferredLayerForHudPhase(phase);
if (renderHudEngine(phase, layer, ctx, tickCounter)) {
appendHudDeferredMarker(layer, ctx);
}
}
private static boolean renderHudEngine(HudPhase phase,
Renderer2D.Deferred2DLayer layer,
GuiGraphicsExtractor ctx,
DeltaTracker tickCounter) {
boolean rawMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW);
boolean scaledMain = hasHudMainPassWork(phase, HudRenderSpace.SCALED)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED);
boolean logicalMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL);
boolean rawForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW_FOREGROUND);
boolean scaledForeground = hasHudForegroundPassWork(phase, HudRenderSpace.SCALED)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED_FOREGROUND);
boolean logicalForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND);
if (!rawMain && !scaledMain && !logicalMain && !rawForeground && !scaledForeground && !logicalForeground) {
return false;
}
float tickProgress = TickDelta.tickProgress(tickCounter, false);
TextRenderer textRenderer = TextRenderer.get();
FullScreenRenderer.ensureInit();
ViewportContext.beginUnscaled(ctx);
refreshHudFrameTiming(tickCounter);
Renderer2D.withDeferredLayer(layer, () -> {
SystemCursor.beginFrame(ctx);
try (RenderPhaseScope hudPhase = CombatantRenderSystem.phase(RenderPhase.HUD_MAIN, "2d:phase:" + phase.name())) {
// Raw HUD pass
if (rawMain) {
Renderer2D.COLOR.begin();
ModuleManager.renderHudEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
// Scaled fixed HUD pass
if (scaledMain) {
ViewportContext.beginScaled(ctx);
Renderer2D.COLOR.begin();
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
// Logical HUD pass
if (logicalMain) {
ViewportContext.beginUnscaledLogical(ctx);
Renderer2D.COLOR.begin();
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
DraggableHudElementRegistry.renderAllEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
// Raw foreground
if (rawForeground) {
ViewportContext.beginUnscaled(ctx);
Renderer2D.COLOR.begin();
ModuleManager.renderHudEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
// Scaled fixed HUD foreground
if (scaledForeground) {
ViewportContext.beginScaled(ctx);
Renderer2D.COLOR.begin();
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
// Logical foreground
if (logicalForeground) {
ViewportContext.beginUnscaledLogical(ctx);
Renderer2D.COLOR.begin();
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
DraggableHudElementRegistry.renderAllEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
Renderer2D.COLOR.render();
}
} finally {
SystemCursor.endFrame();
ViewportContext.end(ctx);
}
});
return true;
}
private static void renderHudAfterHotbar(GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
if (!RuntimeGate.canRunHud()) return;
boolean swapTooltipWork = SwapTooltip.hasWork();
boolean targetHudWork = DraggableHudElementRegistry.hasEngineWidgetWork("target_hud");
if (!swapTooltipWork && !targetHudWork) return;
float tickProgress = TickDelta.tickProgress(tickCounter, false);
TextRenderer textRenderer = TextRenderer.get();
Renderer2D.Deferred2DLayer layer = Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
FullScreenRenderer.ensureInit();
ViewportContext.beginUnscaled(ctx);
refreshHudFrameTiming(tickCounter);
Renderer2D.withDeferredLayer(layer, () -> {
SystemCursor.beginFrame(ctx);
try (RenderPhaseScope hudPhase = CombatantRenderSystem.phase(RenderPhase.HUD_EFFECTS, "2d:after_hotbar")) {
// Raw pass
if (swapTooltipWork) {
try (ProfilerPhase.Scope tooltipsScope = ProfilerPhase.scope("2d:after_hotbar:swap_tooltip");
RenderProfiler2D.Section ignoredTooltips = RenderProfiler2D.section("swap_tooltip")) {
Renderer2D.COLOR.begin();
SwapTooltip.render();
Renderer2D.COLOR.render();
}
}
// Logical pass
if (targetHudWork) {
ViewportContext.beginUnscaledLogical(ctx);
try (ProfilerPhase.Scope targetHudScope = ProfilerPhase.scope("2d:after_hotbar:target_hud");
RenderProfiler2D.Section ignoredTargetHud = RenderProfiler2D.section("target_hud")) {
Renderer2D.COLOR.begin();
DraggableHudElementRegistry.renderEngineWidget(
"target_hud",
Renderer2D.COLOR,
textRenderer,
ctx,
tickProgress
);
Renderer2D.COLOR.render();
}
}
} finally {
SystemCursor.endFrame();
ViewportContext.end(ctx);
}
});
appendHudDeferredMarker(layer, ctx);
}
private static void appendHudDeferredMarker(Renderer2D.Deferred2DLayer layer, GuiGraphicsExtractor ctx) {
if (!(ctx instanceof IGuiGraphics graphics)) return;
ctx.nextStratum();
graphics.combatant$addDeferredHudMarker(layer);
ctx.nextStratum();
}
private static Renderer2D.Deferred2DLayer deferredLayerForHudPhase(HudPhase phase) {
if (phase == null) return Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
return switch (phase) {
case NONE -> Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
case FIRST -> Renderer2D.Deferred2DLayer.HUD_FIRST;
case BEFORE_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_BEFORE_MISC_OVERLAYS;
case AFTER_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
case AFTER_BOSS_BAR -> Renderer2D.Deferred2DLayer.HUD_AFTER_BOSS_BAR;
case BEFORE_DEMO_TIMER -> Renderer2D.Deferred2DLayer.HUD_BEFORE_DEMO_TIMER;
case BEFORE_CHAT -> Renderer2D.Deferred2DLayer.HUD_BEFORE_CHAT;
case AFTER_SUBTITLES -> Renderer2D.Deferred2DLayer.HUD_AFTER_SUBTITLES;
case LAST -> Renderer2D.Deferred2DLayer.HUD_LAST;
};
}
private static boolean hasHudMainPassWork(HudPhase phase, HudRenderSpace space) {
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineWork(phase);
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, false);
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, false);
return moduleWork || staticWork || draggableWork;
}
private static boolean hasHudForegroundPassWork(HudPhase phase, HudRenderSpace space) {
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineForegroundWork(phase);
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, true);
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, true);
return moduleWork || staticWork || draggableWork;
}
@Override
public void onInitializeClient() {
CombatantRenderEngineBootstrap.init();
PostProcessManager.register(new NetherPortalRiftPass());
PostProcessManager.register(new SleepOverlayPass());
MainConfig.get(); // Load global settings (debug flag)
AccountConfig.get();
ProxyBackend.init();
CommandManager.init();
MediaSessionService.get().init();
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> MediaSessionService.get().shutdown());
// -------- CONFIG + BINDS ----------
// Enabled addons declare built-in module exclusions before auto-discovery.
AddonManager.prepareModuleLoading();
ModuleAutoLoader.load("dev.loki.lovisual.features.module.modules");
AddonManager.init();
// Initialize modules' enabled state and settings from new config system
ModuleManager.loadAllModuleConfigs();
AddonManager.notifyClientReady();
// Key binds are restored via Module config (KeyBindSetting) in ModuleManager.loadAllModuleConfigs()
HudElements.init(); // init HUD config + widgets
StaticHudElementBootstrap.init(); // init vanilla HUD elements config
Events.BUS.register(I18nPreflightContributors.INSTANCE);
Events.BUS.register(RenderPrewarmContributors.INSTANCE);
Events.BUS.register(RotationManager.INSTANCE);
Events.BUS.register(AttackPressing.INSTANCE);
Events.BUS.register(InventorySwap.INSTANCE);
Events.BUS.register(SprintController.INSTANCE);
Events.BUS.register(AntiBotTracker.INSTANCE);
Events.BUS.register(VulcanReachController.INSTANCE);
Events.BUS.register(CombatProtocolHeuristics.INSTANCE);
Events.BUS.register(PvpTracker.INSTANCE);
Events.BUS.register(PvpTargetTracker.INSTANCE);
Events.BUS.register(SelfBedTracker.INSTANCE);
Events.BUS.register(BoatSimulationCache.INSTANCE);
Events.BUS.register(PlayerSimulationCache.INSTANCE);
Events.BUS.register(BlinkManager.INSTANCE);
Events.BUS.register(FakeLagController.INSTANCE);
Events.BUS.register(BacktrackController.INSTANCE);
Events.BUS.register(TimerController.INSTANCE);
// -------- КЛЮЧЕВЫЕ ИВЕНТЫ --------
// === ТИКИ ===
ClientTickEvents.START_CLIENT_TICK.register(client -> {
if (client.player == null) return;
if (!RuntimeGate.canRunClientLogic()) return;
Events.BUS.post(new GameTickEvent());
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
ModuleManager.tickRuntimeControllers();
if (!RuntimeGate.canRunClientLogic()) return;
if (!ClickGuiRenderer.isBlockingModuleKeybinds()) {
ModuleManager.handleModuleKeybinds();
}
TargetManager.tick();
ModuleManager.tickAll();
DraggableHudElementRegistry.tickAll();
StaticHudElementRegistry.tickAll();
});
/* ====================== WORLD RENDER ====================== */
LevelRenderEvents.COLLECT_SUBMITS.register(ctx -> renderWorldPhase(
WorldPhase.BEFORE_ENTITIES,
ctx.poseStack(),
ctx.submitNodeCollector()
));
LevelRenderEvents.AFTER_SOLID_FEATURES.register(ctx -> renderWorldPhase(
WorldPhase.AFTER_ENTITIES,
ctx.poseStack(),
ctx.submitNodeCollector()
));
LevelRenderEvents.BEFORE_TRANSLUCENT_TERRAIN.register(ctx -> renderWorldPhase(
WorldPhase.BEFORE_TRANSLUCENT,
ctx.poseStack(),
ctx.submitNodeCollector()
));
LevelRenderEvents.END_MAIN.register(ctx -> renderWorldPhase(
WorldPhase.END_MAIN,
ctx.poseStack(),
ctx.submitNodeCollector()
));
// === HUD 2D OVERLAYS ===
HudElementRegistry.addFirst(
Identifier.fromNamespaceAndPath("lovisual", "hud_first"),
(ctx, tc) -> renderHudPhase(HudPhase.FIRST, ctx, tc)
);
HudElementRegistry.addLast(
Identifier.fromNamespaceAndPath("lovisual", "hud_last"),
(ctx, tc) -> renderHudPhase(HudPhase.LAST, ctx, tc)
);
// остальные позиции HUD:
HudElementRegistry.attachElementBefore(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
Identifier.fromNamespaceAndPath("lovisual", "hud_before_misc"),
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_MISC_OVERLAYS, ctx, tc)
);
HudElementRegistry.attachElementAfter(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
Identifier.fromNamespaceAndPath("lovisual", "hud_after_misc"),
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_MISC_OVERLAYS, ctx, tc)
);
HudElementRegistry.attachElementAfter(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SLEEP,
Identifier.fromNamespaceAndPath("lovisual", "hud_after_boss"),
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_BOSS_BAR, ctx, tc)
);
HudElementRegistry.attachElementBefore(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.DEMO_TIMER,
Identifier.fromNamespaceAndPath("lovisual", "hud_before_demo"),
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_DEMO_TIMER, ctx, tc)
);
HudElementRegistry.attachElementBefore(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.CHAT,
Identifier.fromNamespaceAndPath("lovisual", "hud_before_chat"),
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_CHAT, ctx, tc)
);
HudElementRegistry.attachElementAfter(
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SUBTITLES,
Identifier.fromNamespaceAndPath("lovisual", "hud_after_subtitles"),
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_SUBTITLES, ctx, tc)
);
HudElementRegistry.attachElementAfter(
VanillaHudElements.HOTBAR,
Identifier.fromNamespaceAndPath("lovisual", "hud_after_hotbar"),
(ctx, tc) -> renderHudAfterHotbar(ctx, tc)
);
registerRuntimeLifecycle();
ClientRuntime.markActive("client initialized");
RenderPrewarmManager.prewarm("client initialized");
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import java.util.List;
record AddonDescriptor(
String id,
String name,
String version,
String description,
List<String> authors,
String iconPath,
int apiVersion,
String entrypointDefinition
) {
}

View file

@ -0,0 +1,21 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
public record AddonIssue(
String addonId,
Severity severity,
String message,
String detail
) {
public enum Severity {
INFO,
WARNING,
ERROR
}
}

View file

@ -0,0 +1,540 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.runtime.ClientRuntime;
import dev.loki.lovisual.runtime.RuntimeResumeParticipant;
import dev.loki.lovisual.runtime.RuntimeShutdownContext;
import dev.loki.lovisual.runtime.RuntimeShutdownParticipant;
import dev.loki.lovisual.util.logging.DebugLog;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.metadata.CustomValue;
import net.fabricmc.loader.api.metadata.ModMetadata;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public enum AddonManager {
;
public static final String ADDON_METADATA_KEY = "combatant:addon";
private static final Map<String, AddonRegistration> ADDONS = new LinkedHashMap<>();
private static final Map<String, Boolean> ENABLED_OVERRIDES = new LinkedHashMap<>();
private static final Map<String, String> MODULE_OWNERS = new LinkedHashMap<>();
private static final Map<String, String> DRAGGABLE_HUD_OWNERS = new LinkedHashMap<>();
private static final Map<String, String> STATIC_HUD_OWNERS = new LinkedHashMap<>();
private static boolean discovered;
private static boolean moduleLoadingPrepared;
private static boolean initialized;
private static boolean clientReady;
/**
* Discovers enabled addon entrypoints and lets them configure built-in module
* exclusions before {@code ModuleAutoLoader} starts instantiating modules.
*/
public static void prepareModuleLoading() {
ensureDiscovered();
if (moduleLoadingPrepared) return;
moduleLoadingPrepared = true;
configureEnabledAddons();
}
public static void init() {
if (initialized) return;
prepareModuleLoading();
if (!ModuleAutoLoader.isDiscoveryFinished()) {
return;
}
reconcileModuleExclusions();
initialized = true;
initializeEnabledAddons();
}
/**
* Completes addon startup after module configs have been loaded and applied.
*/
public static void notifyClientReady() {
init();
if (!initialized) return;
clientReady = true;
for (AddonRegistration registration : ADDONS.values()) {
notifyClientReady(registration);
}
}
private static void ensureDiscovered() {
if (discovered) return;
discovered = true;
ENABLED_OVERRIDES.clear();
ENABLED_OVERRIDES.putAll(AddonStateStore.loadEnabledOverrides());
discoverEntrypoints();
}
public static void registerRuntimeLifecycle() {
ClientRuntime.setAddonCounter(AddonManager::activeCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
suspendForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void resume(String reason) {
resumeAfterRuntime(reason);
}
});
}
public static List<AddonSnapshot> snapshots() {
init();
return ADDONS.values().stream()
.map(AddonRegistration::snapshot)
.sorted(Comparator.comparing(AddonSnapshot::name, String.CASE_INSENSITIVE_ORDER))
.toList();
}
public static AddonSnapshot snapshot(String id) {
init();
AddonRegistration registration = ADDONS.get(normalizeId(id));
return registration == null ? null : registration.snapshot();
}
public static boolean isActive(String id) {
init();
AddonRegistration registration = ADDONS.get(normalizeId(id));
return registration != null && registration.enabled && registration.status == AddonStatus.ACTIVE;
}
public static List<AddonIssue> scan() {
init();
List<AddonIssue> out = new ArrayList<>();
for (AddonRegistration registration : ADDONS.values()) {
validateRegistration(registration);
out.addAll(registration.issues);
}
if (out.isEmpty()) {
out.add(new AddonIssue("combatant", AddonIssue.Severity.INFO, "No addon errors found", ""));
}
return List.copyOf(out);
}
public static String moduleProfileOwnerId(String moduleId) {
String addonId = MODULE_OWNERS.get(normalizeId(moduleId));
return addonId == null ? "module:" + moduleId : "addon:" + addonId + ":module:" + moduleId;
}
public static String draggableHudProfileOwnerId(String elementId) {
String addonId = DRAGGABLE_HUD_OWNERS.get(normalizeId(elementId));
return addonId == null ? "hud.draggable:" + elementId : "addon:" + addonId + ":hud.draggable:" + elementId;
}
public static String staticHudProfileOwnerId(String elementId) {
String addonId = STATIC_HUD_OWNERS.get(normalizeId(elementId));
return addonId == null ? "hud.static:" + elementId : "addon:" + addonId + ":hud.static:" + elementId;
}
public static String profileDisplayName(String ownerId, String displayName) {
String addonId = addonIdFromProfileOwner(ownerId);
if (addonId == null) return displayName;
AddonRegistration registration = ADDONS.get(addonId);
String addonName = registration == null ? addonId : registration.descriptor.name();
return addonName + " / " + displayName;
}
public static String addonIdFromProfileOwner(String ownerId) {
if (ownerId == null || !ownerId.startsWith("addon:")) return null;
int start = "addon:".length();
int end = ownerId.indexOf(':', start);
if (end <= start) return null;
return normalizeId(ownerId.substring(start, end));
}
public static boolean setEnabled(String id, boolean enabled) {
init();
String normalizedId = normalizeId(id);
AddonRegistration registration = ADDONS.get(normalizedId);
if (registration == null) return false;
if (registration.enabled == enabled) return true;
registration.enabled = enabled;
registration.restartRequired = false;
ENABLED_OVERRIDES.put(normalizedId, enabled);
AddonStateStore.saveEnabledOverrides(ENABLED_OVERRIDES);
if (enabled) {
if (!registration.moduleConfigurationApplied) {
configureAddonModules(registration);
}
if (!registration.initialized) {
initializeAddon(registration);
} else {
resumeRuntimeContributions(registration);
resumeAddon(registration, "enabled by user");
if (registration.status != AddonStatus.ERROR) {
registration.status = AddonStatus.ACTIVE;
}
}
if (clientReady) {
notifyClientReady(registration);
}
return true;
}
registration.restartRequired = !registration.disabledBuiltInModules.isEmpty();
if (!registration.initialized) {
registration.status = AddonStatus.DISABLED;
return true;
}
suspendRuntimeContributions(registration);
suspendAddon(registration, "disabled by user");
registration.status = AddonStatus.DISABLED;
return true;
}
public static int activeCount() {
int count = 0;
for (AddonRegistration registration : ADDONS.values()) {
if (registration.status == AddonStatus.ACTIVE) count++;
}
return count;
}
private static void discoverEntrypoints() {
for (var entrypoint : FabricLoader.getInstance()
.getEntrypointContainers(LoVisualAddon.ENTRYPOINT_KEY, LoVisualAddon.class)) {
ModMetadata metadata = entrypoint.getProvider().getMetadata();
String id = normalizeId(metadata.getId());
AddonDescriptor descriptor = descriptor(metadata, entrypoint.getDefinition());
boolean enabled = ENABLED_OVERRIDES.getOrDefault(id, true);
AddonStatus status = enabled ? AddonStatus.DISCOVERED : AddonStatus.DISABLED;
AddonRegistration duplicate = ADDONS.get(id);
if (duplicate != null) {
duplicate.issue(AddonIssue.Severity.ERROR, "Duplicate addon id", metadata.getId());
continue;
}
AddonRegistration registration = new AddonRegistration(descriptor, entrypoint, enabled, status);
validateRegistration(registration);
ADDONS.put(id, registration);
}
}
private static void configureEnabledAddons() {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.enabled) {
configureAddonModules(registration);
}
}
}
private static void configureAddonModules(AddonRegistration registration) {
if (registration.moduleConfigurationApplied || !registration.enabled || registration.status == AddonStatus.ERROR) {
return;
}
try {
LoVisualAddon addon = addonInstance(registration);
LoVisualModuleLoadContextImpl context = new LoVisualModuleLoadContextImpl(registration);
addon.onConfigureModules(context);
context.commit();
registration.moduleConfigurationApplied = true;
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Module configuration failed", t.toString());
DebugLog.error("Addon module configuration failed: %s", t, registration.descriptor.id());
}
}
private static void reconcileModuleExclusions() {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.disabledBuiltInModules.isEmpty()) continue;
registration.disabledBuiltInModules.removeIf(reference -> {
if (ModuleAutoLoader.wasDisableRequestMatched(reference, registration.descriptor.id())) {
return false;
}
registration.issue(
AddonIssue.Severity.WARNING,
"Built-in module exclusion target was not found",
reference
);
return true;
});
}
}
private static void initializeEnabledAddons() {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.enabled && registration.status != AddonStatus.ERROR) {
initializeAddon(registration);
}
}
}
private static void initializeAddon(AddonRegistration registration) {
if (registration.initialized || !registration.enabled || registration.status == AddonStatus.ERROR) return;
if (!registration.moduleConfigurationApplied) {
configureAddonModules(registration);
if (registration.status == AddonStatus.ERROR) return;
}
try {
LoVisualAddon addon = addonInstance(registration);
addon.onInitialize(new LoVisualAddonContextImpl(registration));
registration.initialized = true;
registration.status = AddonStatus.ACTIVE;
DebugLog.info("Addon initialized: %s", registration.descriptor.id());
if (clientReady) {
notifyClientReady(registration);
}
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Initialization failed", t.toString());
DebugLog.error("Addon initialization failed: %s", t, registration.descriptor.id());
}
}
private static void notifyClientReady(AddonRegistration registration) {
if (registration == null
|| registration.clientReadyNotified
|| !registration.initialized
|| !registration.enabled
|| registration.status != AddonStatus.ACTIVE) {
return;
}
try {
registration.addon.onClientReady(
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
);
registration.clientReadyNotified = true;
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Client ready callback failed", t.toString());
DebugLog.error("Addon client ready callback failed: %s", t, registration.descriptor.id());
}
}
private static LoVisualAddon addonInstance(AddonRegistration registration) {
LoVisualAddon addon = registration.addon;
if (addon == null) {
addon = registration.entrypoint.getEntrypoint();
registration.addon = addon;
}
return addon;
}
private static void suspendForRuntime(RuntimeShutdownContext context) {
int suspended = 0;
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.ACTIVE) continue;
try {
if (context.jarReplacement()) {
shutdownAddon(registration, context.reason());
registration.status = AddonStatus.SHUTDOWN;
} else {
registration.addon.onRuntimeSuspended(
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
);
registration.status = AddonStatus.SUSPENDED;
}
suspended++;
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Runtime suspend failed", t.toString());
DebugLog.error("Addon runtime suspend failed: %s", t, registration.descriptor.id());
}
}
context.increment("addons_suspended", suspended);
}
private static void resumeAfterRuntime(String reason) {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.SUSPENDED || !registration.enabled) {
continue;
}
resumeAddon(registration, reason);
if (registration.status != AddonStatus.ERROR) {
registration.status = AddonStatus.ACTIVE;
}
}
}
private static void suspendAddon(AddonRegistration registration, String reason) {
if (registration.addon == null) return;
try {
registration.addon.onRuntimeSuspended(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Runtime suspend failed", t.toString());
DebugLog.error("Addon runtime suspend failed: %s", t, registration.descriptor.id());
}
}
private static void resumeAddon(AddonRegistration registration, String reason) {
if (registration.addon == null) return;
try {
registration.addon.onRuntimeResumed(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
} catch (Throwable t) {
registration.status = AddonStatus.ERROR;
registration.issue(AddonIssue.Severity.ERROR, "Runtime resume failed", t.toString());
DebugLog.error("Addon runtime resume failed: %s", t, registration.descriptor.id());
}
}
private static void shutdownAddon(AddonRegistration registration, String reason) {
if (registration.addon == null) return;
try {
registration.addon.onShutdown(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
} catch (Throwable t) {
registration.issue(AddonIssue.Severity.ERROR, "Shutdown failed", t.toString());
DebugLog.error("Addon shutdown failed: %s", t, registration.descriptor.id());
}
}
private static void suspendRuntimeContributions(AddonRegistration registration) {
registration.suspendedModules.clear();
registration.suspendedDraggableHudElements.clear();
registration.suspendedStaticHudElements.clear();
for (String id : registration.modules) {
Module module = ModuleManager.get(id);
if (module != null) {
registration.suspendedModules.put(id, module.isEnabled());
ModuleManager.setRuntimeEnabledTransient(id, false);
}
}
for (String id : registration.draggableHudElements) {
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
if (element != null) {
registration.suspendedDraggableHudElements.put(id, element.isEnabled());
element.setRuntimeEnabledTransient(false);
}
}
for (String id : registration.staticHudElements) {
AbstractHudElement element = StaticHudElementRegistry.getById(id);
if (element != null) {
registration.suspendedStaticHudElements.put(id, element.isEnabled());
element.setRuntimeEnabledTransient(false);
}
}
}
private static void resumeRuntimeContributions(AddonRegistration registration) {
for (String id : registration.modules) {
Boolean enabled = registration.suspendedModules.get(id);
if (enabled != null) {
ModuleManager.setRuntimeEnabledTransient(id, enabled);
}
}
for (String id : registration.draggableHudElements) {
Boolean enabled = registration.suspendedDraggableHudElements.get(id);
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
if (enabled != null && element != null) {
element.setRuntimeEnabledTransient(enabled);
}
}
for (String id : registration.staticHudElements) {
Boolean enabled = registration.suspendedStaticHudElements.get(id);
AbstractHudElement element = StaticHudElementRegistry.getById(id);
if (enabled != null && element != null) {
element.setRuntimeEnabledTransient(enabled);
}
}
registration.suspendedModules.clear();
registration.suspendedDraggableHudElements.clear();
registration.suspendedStaticHudElements.clear();
}
static void noteModuleOwner(String addonId, String moduleId) {
if (moduleId != null && !moduleId.isBlank()) {
MODULE_OWNERS.put(normalizeId(moduleId), normalizeId(addonId));
}
}
static void noteDraggableHudOwner(String addonId, String elementId) {
if (elementId != null && !elementId.isBlank()) {
DRAGGABLE_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
}
}
static void noteStaticHudOwner(String addonId, String elementId) {
if (elementId != null && !elementId.isBlank()) {
STATIC_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
}
}
private static void validateRegistration(AddonRegistration registration) {
if (registration.descriptor.apiVersion() != LoVisualAddon.API_VERSION) {
registration.issue(
AddonIssue.Severity.WARNING,
"Addon API version differs from client API",
"addon=" + registration.descriptor.apiVersion() + ", client=" + LoVisualAddon.API_VERSION
);
}
if (registration.descriptor.iconPath() == null || registration.descriptor.iconPath().isBlank()) {
registration.issue(AddonIssue.Severity.WARNING, "Addon icon is missing", "Add icon in fabric.mod.json");
}
if (registration.descriptor.entrypointDefinition() == null
|| registration.descriptor.entrypointDefinition().isBlank()) {
registration.issue(AddonIssue.Severity.WARNING, "Entrypoint definition is unavailable", "");
}
}
private static AddonDescriptor descriptor(ModMetadata metadata, String entrypointDefinition) {
List<String> authors = metadata.getAuthors().stream()
.map(person -> person.getName() == null ? "" : person.getName())
.filter(name -> !name.isBlank())
.toList();
return new AddonDescriptor(
normalizeId(metadata.getId()),
blankFallback(metadata.getName(), metadata.getId()),
String.valueOf(metadata.getVersion()),
metadata.getDescription() == null ? "" : metadata.getDescription(),
authors,
metadata.getIconPath(64).or(() -> metadata.getIconPath(32)).orElse(""),
apiVersion(metadata),
entrypointDefinition
);
}
private static int apiVersion(ModMetadata metadata) {
CustomValue value = metadata.getCustomValue(ADDON_METADATA_KEY);
if (value == null || value.getType() != CustomValue.CvType.OBJECT) return LoVisualAddon.API_VERSION;
CustomValue api = value.getAsObject().get("api");
if (api == null || api.getType() != CustomValue.CvType.NUMBER) return LoVisualAddon.API_VERSION;
return api.getAsNumber().intValue();
}
private static String blankFallback(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
}
private static String normalizeId(String id) {
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
}
}

View file

@ -0,0 +1,79 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
import net.fabricmc.loader.api.entrypoint.EntrypointContainer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
final class AddonRegistration {
final AddonDescriptor descriptor;
final EntrypointContainer<LoVisualAddon> entrypoint;
final List<String> modules = new ArrayList<>();
final List<String> disabledBuiltInModules = new ArrayList<>();
final List<String> draggableHudElements = new ArrayList<>();
final List<String> staticHudElements = new ArrayList<>();
final List<String> commands = new ArrayList<>();
final List<String> clickGuiSections = new ArrayList<>();
final List<String> moduleExtensions = new ArrayList<>();
final List<String> irisPatchManifests = new ArrayList<>();
final List<String> renderCallbacks = new ArrayList<>();
final List<String> postProcessPasses = new ArrayList<>();
final List<AddonIssue> issues = new ArrayList<>();
final Map<String, Boolean> suspendedModules = new LinkedHashMap<>();
final Map<String, Boolean> suspendedDraggableHudElements = new LinkedHashMap<>();
final Map<String, Boolean> suspendedStaticHudElements = new LinkedHashMap<>();
LoVisualAddon addon;
boolean moduleConfigurationApplied;
boolean initialized;
boolean clientReadyNotified;
AddonStatus status;
boolean enabled;
boolean restartRequired;
AddonRegistration(AddonDescriptor descriptor,
EntrypointContainer<LoVisualAddon> entrypoint,
boolean enabled,
AddonStatus status) {
this.descriptor = descriptor;
this.entrypoint = entrypoint;
this.enabled = enabled;
this.status = status;
}
AddonSnapshot snapshot() {
return new AddonSnapshot(
descriptor.id(),
descriptor.name(),
descriptor.version(),
descriptor.description(),
descriptor.authors(),
descriptor.iconPath(),
descriptor.apiVersion(),
status,
enabled,
restartRequired,
modules.size(),
draggableHudElements.size(),
staticHudElements.size(),
commands.size(),
clickGuiSections.size(),
moduleExtensions.size(),
irisPatchManifests.size(),
List.copyOf(issues)
);
}
void issue(AddonIssue.Severity severity, String message, String detail) {
issues.add(new AddonIssue(descriptor.id(), severity, message, detail));
}
}

View file

@ -0,0 +1,193 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.vertex.PoseStack;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessContext;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderContext;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.render.engine.postprocess.PostProcessManager;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public enum AddonRenderPipelineManager {
;
private static final Map<LoVisualRenderStage, List<RegisteredRenderCallback>> CALLBACKS =
new EnumMap<>(LoVisualRenderStage.class);
static {
for (LoVisualRenderStage stage : LoVisualRenderStage.values()) {
CALLBACKS.put(stage, new ArrayList<>());
}
}
public static synchronized boolean register(String addonId,
String callbackId,
LoVisualRenderStage stage,
LoVisualRenderCallback callback) {
String normalizedAddonId = normalize(addonId);
String normalizedCallbackId = normalize(callbackId);
if (normalizedAddonId.isBlank() || normalizedCallbackId.isBlank() || stage == null || callback == null) {
return false;
}
List<RegisteredRenderCallback> callbacks = CALLBACKS.get(stage);
for (RegisteredRenderCallback registered : callbacks) {
if (registered.addonId().equals(normalizedAddonId) && registered.callbackId().equals(normalizedCallbackId)) {
return false;
}
}
callbacks.add(new RegisteredRenderCallback(normalizedAddonId, normalizedCallbackId, callback));
return true;
}
public static boolean hasActiveCallbacks(LoVisualRenderStage stage) {
if (stage == null) return false;
List<RegisteredRenderCallback> callbacks;
synchronized (AddonRenderPipelineManager.class) {
callbacks = List.copyOf(CALLBACKS.get(stage));
}
for (RegisteredRenderCallback callback : callbacks) {
if (AddonManager.isActive(callback.addonId())) return true;
}
return false;
}
public static boolean registerPostProcess(String addonId,
String passId,
PostProcessPass.Phase phase,
int priority,
LoVisualPostProcessCallback callback) {
String normalizedAddonId = normalize(addonId);
String normalizedPassId = normalize(passId);
if (normalizedAddonId.isBlank() || normalizedPassId.isBlank() || phase == null || callback == null) {
return false;
}
PostProcessManager.register(new AddonPostProcessPass(normalizedAddonId, normalizedPassId, phase, priority, callback));
return true;
}
public static void render2D(LoVisualRenderStage stage,
HudPhase hudPhase,
Renderer2D renderer,
TextRenderer textRenderer,
GuiGraphicsExtractor guiContext,
float tickDelta) {
render(stage, hudPhase, null, renderer, null, null, textRenderer, guiContext, null, tickDelta);
}
public static void render3D(LoVisualRenderStage stage,
WorldPhase worldPhase,
Renderer3D renderer,
Renderer3D depthRenderer,
PoseStack poseStack,
float tickDelta) {
render(stage, null, worldPhase, null, renderer, depthRenderer, null, null, poseStack, tickDelta);
}
public static synchronized void unregisterAddon(String addonId) {
String normalizedAddonId = normalize(addonId);
for (List<RegisteredRenderCallback> callbacks : CALLBACKS.values()) {
callbacks.removeIf(callback -> callback.addonId().equals(normalizedAddonId));
}
}
private static void render(LoVisualRenderStage stage,
HudPhase hudPhase,
WorldPhase worldPhase,
Renderer2D renderer2D,
Renderer3D renderer3D,
Renderer3D depthRenderer3D,
TextRenderer textRenderer,
GuiGraphicsExtractor guiContext,
PoseStack poseStack,
float tickDelta) {
List<RegisteredRenderCallback> callbacks;
synchronized (AddonRenderPipelineManager.class) {
callbacks = List.copyOf(CALLBACKS.get(stage));
}
for (RegisteredRenderCallback registered : callbacks) {
if (!AddonManager.isActive(registered.addonId())) continue;
try {
registered.callback().render(new LoVisualRenderContext(
registered.addonId(),
registered.callbackId(),
stage,
hudPhase,
worldPhase,
renderer2D,
renderer3D,
depthRenderer3D,
textRenderer,
guiContext,
poseStack,
tickDelta
));
} catch (Throwable t) {
DebugLog.error("[Addons] Render callback failed: addon=%s id=%s",
t, registered.addonId(), registered.callbackId());
}
}
}
private static String normalize(String id) {
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
}
private record RegisteredRenderCallback(String addonId,
String callbackId,
LoVisualRenderCallback callback) {
}
private record AddonPostProcessPass(String addonId,
String passId,
PostProcessPass.Phase phase,
int priority,
LoVisualPostProcessCallback callback) implements PostProcessPass {
@Override
public boolean isActive() {
return AddonManager.isActive(addonId);
}
@Override
public boolean render(GpuTextureView src, GpuTextureView dst, float tickDelta) {
if (!isActive()) return false;
try {
return callback.render(new LoVisualPostProcessContext(addonId, passId, phase, src, dst, tickDelta));
} catch (Throwable t) {
DebugLog.error("[Addons] Post-process callback failed: addon=%s id=%s", t, addonId, passId);
return false;
}
}
@Override
public int getPriority() {
return priority;
}
@Override
public Phase getPhase() {
return phase;
}
}
}

View file

@ -0,0 +1,32 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import java.util.List;
public record AddonSnapshot(
String id,
String name,
String version,
String description,
List<String> authors,
String iconPath,
int apiVersion,
AddonStatus status,
boolean enabled,
boolean restartRequired,
int modules,
int draggableHudElements,
int staticHudElements,
int commands,
int clickGuiSections,
int moduleExtensions,
int irisPatchManifests,
List<AddonIssue> issues
) {
}

View file

@ -0,0 +1,63 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
final class AddonStateStore {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private AddonStateStore() {
}
static Map<String, Boolean> loadEnabledOverrides() {
Path file = stateFile();
if (!Files.isRegularFile(file)) return new HashMap<>();
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
State state = GSON.fromJson(reader, State.class);
if (state == null || state.enabled == null) return new HashMap<>();
return new HashMap<>(state.enabled);
} catch (Throwable ignored) {
return new HashMap<>();
}
}
static void saveEnabledOverrides(Map<String, Boolean> enabled) {
Path file = stateFile();
try {
Files.createDirectories(file.getParent());
State state = new State();
state.enabled = new HashMap<>(enabled);
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
GSON.toJson(state, writer);
}
} catch (IOException ignored) {
}
}
private static Path stateFile() {
return FabricLoader.getInstance().getConfigDir()
.resolve("combatant")
.resolve("addons.json");
}
private static final class State {
Map<String, Boolean> enabled = new HashMap<>();
}
}

View file

@ -0,0 +1,17 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
public enum AddonStatus {
DISCOVERED,
DISABLED,
ACTIVE,
SUSPENDED,
ERROR,
SHUTDOWN
}

View file

@ -0,0 +1,144 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiRenderContext;
import dev.loki.lovisual.features.gui.clickgui.ClickGuiRenderer;
import dev.loki.lovisual.features.gui.clickgui.sections.ClickGuiSection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public enum ClickGuiSectionManager {
;
private static final Map<String, Entry> SECTIONS = new LinkedHashMap<>();
public static synchronized boolean register(String addonId,
String sectionId,
String label,
LoVisualClickGuiSection section) {
String normalizedAddonId = normalize(addonId);
String normalizedSectionId = normalize(sectionId);
if (normalizedAddonId.isBlank() || normalizedSectionId.isBlank() || section == null) {
return false;
}
String id = normalizedAddonId + ":" + normalizedSectionId;
if (SECTIONS.containsKey(id)) {
return false;
}
String title = label == null || label.isBlank() ? normalizedSectionId : label.trim();
SECTIONS.put(id, new Entry(
normalizedAddonId,
id,
normalizedSectionId,
title,
new AddonSectionAdapter(section)
));
return true;
}
public static synchronized void unregisterAddon(String addonId) {
String normalizedAddonId = normalize(addonId);
SECTIONS.entrySet().removeIf(entry -> {
if (!entry.getValue().addonId().equals(normalizedAddonId)) {
return false;
}
try {
entry.getValue().section().onDeselected();
} catch (Throwable ignored) {
}
return true;
});
}
public static synchronized List<Entry> sections() {
return SECTIONS.values().stream()
.filter(entry -> AddonManager.isActive(entry.addonId()))
.toList();
}
private static String normalize(String value) {
return value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
}
public record Entry(String addonId,
String id,
String localId,
String label,
ClickGuiSection section) {
}
private record AddonSectionAdapter(LoVisualClickGuiSection section) implements ClickGuiSection {
@Override
public void layout(float x, float y, float w, float h) {
section.layout(x, y, w, h);
}
@Override
public void render(float mouseX, float mouseY) {
section.render(
new LoVisualClickGuiRenderContext(
ClickGuiRenderer.currentRenderer(),
ClickGuiRenderer.getInterRegular(),
ClickGuiRenderer.getInterMedium()
),
mouseX,
mouseY
);
}
@Override
public void renderGlassPass(float alphaFactor) {
section.renderGlassPass(alphaFactor);
}
@Override
public boolean mousePressed(float mouseX, float mouseY, int button) {
return section.mousePressed(mouseX, mouseY, button);
}
@Override
public void mouseReleased(float mouseX, float mouseY, int button) {
section.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean mouseScrolled(float mouseX, float mouseY, double amount) {
return section.mouseScrolled(mouseX, mouseY, amount);
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return section.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public boolean charTyped(char chr, int modifiers) {
return section.charTyped(chr, modifiers);
}
@Override
public void onSelected() {
section.onSelected();
}
@Override
public void onDeselected() {
section.onDeselected();
}
@Override
public boolean isVisible() {
return section.isVisible();
}
}
}

View file

@ -0,0 +1,206 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddonContext;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.features.command.CommandManager;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.render.engine.pipeline.CombatantRenderPipelines;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import dev.loki.lovisual.render.iris.patch.ShaderPatchEngine;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import java.nio.file.Path;
final class LoVisualAddonContextImpl implements LoVisualAddonContext {
private final AddonRegistration registration;
LoVisualAddonContextImpl(AddonRegistration registration) {
this.registration = registration;
}
@Override
public String addonId() {
return registration.descriptor.id();
}
@Override
public LoVisualClientApi client() {
return LoVisualClientApi.get();
}
@Override
public ModContainer modContainer() {
return registration.entrypoint.getProvider();
}
@Override
public Path gameDir() {
return FabricLoader.getInstance().getGameDir();
}
@Override
public Path configDir() {
return FabricLoader.getInstance().getConfigDir();
}
@Override
public Path addonConfigDir() {
return configDir().resolve("lovisual").resolve("addons").resolve(addonId());
}
@Override
public void registerModule(Module module) {
if (module == null) return;
module.postInit();
registration.modules.add(module.name());
AddonManager.noteModuleOwner(addonId(), module.name());
}
@Override
public void registerDraggableHudElement(DraggableHudElement element) {
if (element == null) return;
DraggableHudElementRegistry.register(element);
registration.draggableHudElements.add(element.getId());
AddonManager.noteDraggableHudOwner(addonId(), element.getId());
}
@Override
public void registerStaticHudElement(AbstractHudElement element) {
if (element == null) return;
StaticHudElementRegistry.register(element);
registration.staticHudElements.add(element.getId());
AddonManager.noteStaticHudOwner(addonId(), element.getId());
}
@Override
public void registerCommand(ClientCommand command) {
if (command == null) return;
CommandManager.register(new AddonClientCommand(addonId(), command));
registration.commands.add(command.metadata().id());
}
@Override
public void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section) {
if (ClickGuiSectionManager.register(addonId(), sectionId, label, section)) {
registration.clickGuiSections.add(sectionId);
} else {
registration.issue(AddonIssue.Severity.WARNING, "ClickGui section registration failed", sectionId);
}
}
@Override
public void registerModuleExtension(String moduleId, LoVisualModuleExtension extension) {
if (ModuleExtensionManager.register(addonId(), moduleId, extension)) {
registration.moduleExtensions.add(moduleId);
} else {
registration.issue(AddonIssue.Severity.WARNING, "Module extension target is unavailable", moduleId);
}
}
@Override
public void registerIrisShaderPatchManifest(String manifestResourcePath) {
if (ShaderPatchEngine.registerManifestResource(manifestResourcePath)) {
registration.irisPatchManifests.add(manifestResourcePath);
} else {
registration.issue(AddonIssue.Severity.WARNING, "Iris patch manifest registration failed", manifestResourcePath);
}
}
@Override
public void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback) {
if (AddonRenderPipelineManager.register(addonId(), callbackId, stage, callback)) {
registration.renderCallbacks.add(stage.name().toLowerCase(java.util.Locale.ROOT) + ":" + callbackId);
} else {
registration.issue(AddonIssue.Severity.WARNING, "Render callback registration failed", callbackId);
}
}
@Override
public void registerPostProcessPass(String passId,
PostProcessPass.Phase phase,
int priority,
LoVisualPostProcessCallback callback) {
if (AddonRenderPipelineManager.registerPostProcess(addonId(), passId, phase, priority, callback)) {
registration.postProcessPasses.add(phase.name().toLowerCase(java.util.Locale.ROOT) + ":" + passId);
} else {
registration.issue(AddonIssue.Severity.WARNING, "Post-process registration failed", passId);
}
}
@Override
public RenderPipeline registerRenderPipeline(RenderPipeline pipeline) {
if (pipeline == null) return null;
RenderPipeline registered = CombatantRenderPipelines.registerAddonPipeline(pipeline);
registration.renderCallbacks.add("pipeline:" + pipeline.getLocation());
return registered;
}
private record AddonClientCommand(String addonId, ClientCommand delegate) implements ClientCommand {
@Override
public dev.loki.lovisual.features.command.CommandMetadata metadata() {
return delegate.metadata();
}
@Deprecated(forRemoval = true)
@Override
@SuppressWarnings("removal")
public String name() {
return delegate.name();
}
@Deprecated(forRemoval = true)
@Override
@SuppressWarnings("removal")
public java.util.List<String> aliases() {
return delegate.aliases();
}
@Deprecated(forRemoval = true)
@Override
@SuppressWarnings("removal")
public String usage() {
return delegate.usage();
}
@Deprecated(forRemoval = true)
@Override
@SuppressWarnings("removal")
public String description() {
return delegate.description();
}
@Override
public boolean isAvailable() {
return AddonManager.isActive(addonId) && delegate.isAvailable();
}
@Override
public java.util.List<String> suggest(dev.loki.lovisual.features.command.CommandContext ctx, int argIndex, String token) {
return delegate.suggest(ctx, argIndex, token);
}
@Override
public boolean execute(dev.loki.lovisual.features.command.CommandContext ctx) {
return isAvailable() && delegate.execute(ctx);
}
}
}

View file

@ -0,0 +1,29 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddonRuntimeContext;
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
final class LoVisualAddonRuntimeContextImpl implements LoVisualAddonRuntimeContext {
private final String addonId;
LoVisualAddonRuntimeContextImpl(String addonId) {
this.addonId = addonId;
}
@Override
public String addonId() {
return addonId;
}
@Override
public LoVisualClientApi client() {
return LoVisualClientApi.get();
}
}

View file

@ -0,0 +1,68 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualModuleLoadContext;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import java.util.ArrayList;
import java.util.List;
final class LoVisualModuleLoadContextImpl implements LoVisualModuleLoadContext {
private final AddonRegistration registration;
private final List<String> pendingExclusions = new ArrayList<>();
LoVisualModuleLoadContextImpl(AddonRegistration registration) {
this.registration = registration;
}
@Override
public String addonId() {
return registration.descriptor.id();
}
@Override
public boolean disableBuiltInModule(String moduleReference) {
String reference = moduleReference == null ? "" : moduleReference.trim();
if (reference.isEmpty()) return false;
if (!ModuleAutoLoader.acceptsDisableRequests()) {
noteRestartRequired(reference);
return false;
}
if (!pendingExclusions.contains(reference)) {
pendingExclusions.add(reference);
}
return true;
}
void commit() {
for (String reference : pendingExclusions) {
if (!registration.disabledBuiltInModules.contains(reference)) {
registration.disabledBuiltInModules.add(reference);
}
if (!ModuleAutoLoader.requestDisable(reference, addonId())) {
noteRestartRequired(reference);
}
}
pendingExclusions.clear();
}
private void noteRestartRequired(String reference) {
if (!registration.disabledBuiltInModules.contains(reference)) {
registration.disabledBuiltInModules.add(reference);
}
registration.restartRequired = true;
registration.issue(
AddonIssue.Severity.WARNING,
"Built-in module exclusion requires restart",
reference
);
}
}

View file

@ -0,0 +1,55 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.module.ModuleExtensionContext;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.config.values.ModeValue;
import dev.loki.lovisual.features.module.Module;
final class ModuleExtensionContextImpl implements ModuleExtensionContext {
private final String addonId;
private final Module module;
ModuleExtensionContextImpl(String addonId, Module module) {
this.addonId = addonId;
this.module = module;
}
@Override
public String addonId() {
return addonId;
}
@Override
public String moduleId() {
return module.name();
}
@Override
public Module module() {
return module;
}
@Override
public void addSetting(SettingDef setting) {
module.addExtensionSetting(setting);
}
@Override
public ConfigValue<?> getConfigValue(String configName) {
return module.getConfigValue(configName);
}
@Override
public boolean addModeOption(String configName, String option) {
ConfigValue<?> value = getConfigValue(configName);
return value instanceof ModeValue mode && mode.addOption(option);
}
}

View file

@ -0,0 +1,171 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public enum ModuleExtensionManager {
;
private static final Map<String, List<RegisteredExtension>> EXTENSIONS = new LinkedHashMap<>();
public static boolean register(String addonId, String moduleId, LoVisualModuleExtension extension) {
if (extension == null || moduleId == null || moduleId.isBlank()) return false;
Module module = ModuleManager.get(moduleId);
if (module == null) {
DebugLog.warn("[Addons] Module extension target missing: addon=%s module=%s", addonId, moduleId);
return false;
}
String normalized = normalize(moduleId);
RegisteredExtension registered = new RegisteredExtension(addonId, extension);
EXTENSIONS.computeIfAbsent(normalized, ignored -> new ArrayList<>()).add(registered);
try {
extension.onRegister(new ModuleExtensionContextImpl(addonId, module));
} catch (Throwable t) {
DebugLog.error("[Addons] Module extension registration failed: %s", t, normalized);
return false;
}
return true;
}
public static int count() {
int count = 0;
for (List<RegisteredExtension> list : EXTENSIONS.values()) {
count += list.size();
}
return count;
}
public static boolean beforeEnable(Module module) {
return all(module, extension -> extension.beforeEnable(module));
}
public static void afterEnable(Module module) {
each(module, extension -> extension.afterEnable(module));
}
public static boolean beforeDisable(Module module) {
return all(module, extension -> extension.beforeDisable(module));
}
public static void afterDisable(Module module) {
each(module, extension -> extension.afterDisable(module));
}
public static boolean beforeTick(Module module) {
return all(module, extension -> extension.beforeTick(module));
}
public static void afterTick(Module module) {
each(module, extension -> extension.afterTick(module));
}
public static boolean beforeFrame(Module module, float frameDeltaTicks) {
return all(module, extension -> extension.beforeFrame(module, frameDeltaTicks));
}
public static void afterFrame(Module module, float frameDeltaTicks) {
each(module, extension -> extension.afterFrame(module, frameDeltaTicks));
}
public static boolean beforeHudRender(Module module,
Renderer2D renderer,
TextRenderer textRenderer,
GuiGraphicsExtractor ctx,
float tickDelta) {
return all(module, extension -> extension.beforeHudRender(module, renderer, textRenderer, ctx, tickDelta));
}
public static void afterHudRender(Module module,
Renderer2D renderer,
TextRenderer textRenderer,
GuiGraphicsExtractor ctx,
float tickDelta) {
each(module, extension -> extension.afterHudRender(module, renderer, textRenderer, ctx, tickDelta));
}
public static boolean beforeWorldRender(Module module,
Renderer3D renderer,
Renderer3D depthRenderer,
float tickDelta) {
return all(module, extension -> extension.beforeWorldRender(module, renderer, depthRenderer, tickDelta));
}
public static void afterWorldRender(Module module,
Renderer3D renderer,
Renderer3D depthRenderer,
float tickDelta) {
each(module, extension -> extension.afterWorldRender(module, renderer, depthRenderer, tickDelta));
}
private static boolean all(Module module, ExtensionBooleanCall call) {
List<RegisteredExtension> extensions = extensions(module);
if (extensions.isEmpty()) return true;
boolean proceed = true;
for (RegisteredExtension registered : extensions) {
if (!AddonManager.isActive(registered.addonId())) continue;
try {
proceed &= call.invoke(registered.extension());
} catch (Throwable t) {
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
t, registered.addonId(), module == null ? "" : module.name());
}
}
return proceed;
}
private static void each(Module module, ExtensionVoidCall call) {
List<RegisteredExtension> extensions = extensions(module);
if (extensions.isEmpty()) return;
for (RegisteredExtension registered : extensions) {
if (!AddonManager.isActive(registered.addonId())) continue;
try {
call.invoke(registered.extension());
} catch (Throwable t) {
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
t, registered.addonId(), module == null ? "" : module.name());
}
}
}
private static List<RegisteredExtension> extensions(Module module) {
if (module == null) return List.of();
List<RegisteredExtension> list = EXTENSIONS.get(normalize(module.name()));
return list == null ? List.of() : List.copyOf(list);
}
private static String normalize(String id) {
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
}
@FunctionalInterface
private interface ExtensionBooleanCall {
boolean invoke(LoVisualModuleExtension extension);
}
@FunctionalInterface
private interface ExtensionVoidCall {
void invoke(LoVisualModuleExtension extension);
}
private record RegisteredExtension(String addonId, LoVisualModuleExtension extension) {
}
}

View file

@ -0,0 +1,45 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
/**
* Fabric entrypoint contract for Combatant addons.
*
* <p>Declare it in fabric.mod.json under the {@value #ENTRYPOINT_KEY} entrypoint.
*/
public interface LoVisualAddon {
String ENTRYPOINT_KEY = "combatant:addon";
int API_VERSION = 0;
/**
* Called before LoVisual auto-loads its built-in modules.
*
* <p>Use this hook only for startup module exclusions. Normal addon registration
* still belongs in {@link #onInitialize(LoVisualAddonContext)}.</p>
*/
default void onConfigureModules(LoVisualModuleLoadContext context) {
}
void onInitialize(LoVisualAddonContext context);
/**
* Called after all built-in and addon module configs have been loaded and applied.
* This is the safe startup hook for mutating settings of existing modules.
*/
default void onClientReady(LoVisualAddonRuntimeContext context) {
}
default void onRuntimeSuspended(LoVisualAddonRuntimeContext context) {
}
default void onRuntimeResumed(LoVisualAddonRuntimeContext context) {
}
default void onShutdown(LoVisualAddonRuntimeContext context) {
}
}

View file

@ -0,0 +1,55 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
import dev.loki.lovisual.events.UsedImplicitly;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import net.fabricmc.loader.api.ModContainer;
import java.nio.file.Path;
public interface LoVisualAddonContext extends LoVisualAddonRuntimeContext {
@UsedImplicitly
ModContainer modContainer();
@UsedImplicitly
Path gameDir();
Path configDir();
@UsedImplicitly
Path addonConfigDir();
@UsedImplicitly
void registerModule(Module module);
@UsedImplicitly
void registerDraggableHudElement(DraggableHudElement element);
@UsedImplicitly
void registerStaticHudElement(AbstractHudElement element);
@UsedImplicitly
void registerCommand(ClientCommand command);
@UsedImplicitly
void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section);
@UsedImplicitly
void registerModuleExtension(String moduleId, LoVisualModuleExtension extension);
@UsedImplicitly
void registerIrisShaderPatchManifest(String manifestResourcePath);
@UsedImplicitly
void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback);
@UsedImplicitly
void registerPostProcessPass(String passId, PostProcessPass.Phase phase, int priority, LoVisualPostProcessCallback callback);
@UsedImplicitly
RenderPipeline registerRenderPipeline(RenderPipeline pipeline);
}

View file

@ -0,0 +1,16 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
public interface LoVisualAddonRuntimeContext {
String addonId();
LoVisualClientApi client();
}

View file

@ -0,0 +1,43 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
import dev.loki.lovisual.events.UsedImplicitly;
import dev.loki.lovisual.features.module.Module;
/**
* Early addon context used before Combatant's built-in modules are instantiated.
*
* <p>Only enabled addons receive this callback. Exclusions are startup-only: changing
* an addon's enabled state after module discovery requires a client restart for the
* built-in module set to be rebuilt.</p>
*/
public interface LoVisualModuleLoadContext {
@UsedImplicitly
String addonId();
/**
* Prevents an auto-loaded built-in module from being instantiated.
*
* <p>The reference may be a {@code ModuleInfo.id}, module alias, simple class name,
* or fully-qualified class name.</p>
*
* @return {@code true} when the exclusion was accepted for the current startup;
* {@code false} when the reference is invalid or module discovery has already started
*/
@UsedImplicitly
boolean disableBuiltInModule(String moduleReference);
/**
* Class-based convenience overload for addons that directly depend on a built-in module type.
*/
@UsedImplicitly
default boolean disableBuiltInModule(Class<? extends Module> moduleType) {
return moduleType != null && disableBuiltInModule(moduleType.getName());
}
}

View file

@ -0,0 +1,18 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.clickgui;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
public record LoVisualClickGuiRenderContext(
Renderer2D renderer,
TextRenderer regularFont,
TextRenderer mediumFont
) {
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.clickgui;
public interface LoVisualClickGuiSection {
default void layout(float x, float y, float w, float h) {
}
default void render(LoVisualClickGuiRenderContext context, float mouseX, float mouseY) {
}
default void renderGlassPass(float alphaFactor) {
}
default boolean mousePressed(float mouseX, float mouseY, int button) {
return false;
}
default void mouseReleased(float mouseX, float mouseY, int button) {
}
default boolean mouseScrolled(float mouseX, float mouseY, double amount) {
return false;
}
default boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return false;
}
default boolean charTyped(char chr, int modifiers) {
return false;
}
default void onSelected() {
}
default void onDeselected() {
}
default boolean isVisible() {
return true;
}
}

View file

@ -0,0 +1,40 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.client;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleManager;
import java.util.List;
public final class LoVisualClientApi {
private static final LoVisualClientApi INSTANCE = new LoVisualClientApi();
private LoVisualClientApi() {
}
public static LoVisualClientApi get() {
return INSTANCE;
}
public List<Module> modules() {
return ModuleManager.getModules();
}
public Module module(String id) {
return ModuleManager.get(id);
}
public boolean isModuleEnabled(String id) {
return ModuleManager.isEnabled(id);
}
public void setModuleEnabled(String id, boolean enabled) {
ModuleManager.setEnabled(id, enabled);
}
}

View file

@ -0,0 +1,75 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.module;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
import net.minecraft.client.gui.GuiGraphicsExtractor;
public interface LoVisualModuleExtension {
default void onRegister(ModuleExtensionContext context) {
}
default boolean beforeEnable(Module module) {
return true;
}
default void afterEnable(Module module) {
}
default boolean beforeDisable(Module module) {
return true;
}
default void afterDisable(Module module) {
}
default boolean beforeTick(Module module) {
return true;
}
default void afterTick(Module module) {
}
default boolean beforeFrame(Module module, float frameDeltaTicks) {
return true;
}
default void afterFrame(Module module, float frameDeltaTicks) {
}
default boolean beforeHudRender(Module module,
Renderer2D renderer,
TextRenderer textRenderer,
GuiGraphicsExtractor ctx,
float tickDelta) {
return true;
}
default void afterHudRender(Module module,
Renderer2D renderer,
TextRenderer textRenderer,
GuiGraphicsExtractor ctx,
float tickDelta) {
}
default boolean beforeWorldRender(Module module,
Renderer3D renderer,
Renderer3D depthRenderer,
float tickDelta) {
return true;
}
default void afterWorldRender(Module module,
Renderer3D renderer,
Renderer3D depthRenderer,
float tickDelta) {
}
}

View file

@ -0,0 +1,26 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.module;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.features.module.Module;
public interface ModuleExtensionContext {
String addonId();
String moduleId();
Module module();
void addSetting(SettingDef setting);
ConfigValue<?> getConfigValue(String configName);
boolean addModeOption(String configName, String option);
}

View file

@ -0,0 +1,13 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
@FunctionalInterface
public interface LoVisualPostProcessCallback {
boolean render(LoVisualPostProcessContext context);
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.textures.GpuTextureView;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import net.minecraft.client.Minecraft;
public record LoVisualPostProcessContext(
String addonId,
String passId,
PostProcessPass.Phase phase,
GpuTextureView source,
GpuTextureView destination,
float tickDelta
) {
public Minecraft client() {
return Minecraft.getInstance();
}
}

View file

@ -0,0 +1,13 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
@FunctionalInterface
public interface LoVisualRenderCallback {
void render(LoVisualRenderContext context);
}

View file

@ -0,0 +1,36 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.vertex.PoseStack;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.TextRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
public record LoVisualRenderContext(
String addonId,
String callbackId,
LoVisualRenderStage stage,
HudPhase hudPhase,
WorldPhase worldPhase,
Renderer2D renderer2D,
Renderer3D renderer3D,
Renderer3D depthRenderer3D,
TextRenderer textRenderer,
GuiGraphicsExtractor guiContext,
PoseStack poseStack,
float tickDelta
) {
public Minecraft client() {
return Minecraft.getInstance();
}
}

View file

@ -0,0 +1,109 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.PrimitiveTopology;
import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.shaders.UniformType;
import com.mojang.blaze3d.vertex.VertexFormat;
import dev.loki.lovisual.render.engine.pipeline.CombatantRenderPipelines;
import dev.loki.lovisual.render.engine.pipeline.DepthTestFunction;
import dev.loki.lovisual.render.engine.pipeline.ExtendedRenderPipelineBuilder;
import dev.loki.lovisual.render.engine.rhi.clip.ShapeClipRenderPassContract;
import net.minecraft.resources.Identifier;
@SuppressWarnings("unused")
public final class LoVisualRenderPipelineBuilder {
private final ExtendedRenderPipelineBuilder delegate;
private LoVisualRenderPipelineBuilder(RenderPipeline.Snippet... snippets) {
this.delegate = new ExtendedRenderPipelineBuilder(snippets);
}
public static LoVisualRenderPipelineBuilder create(RenderPipeline.Snippet... snippets) {
return new LoVisualRenderPipelineBuilder(snippets);
}
public static RenderPipeline.Snippet meshUniforms() {
return CombatantRenderPipelines.meshUniforms();
}
public LoVisualRenderPipelineBuilder location(Identifier id) {
delegate.withLocation(id);
return this;
}
public LoVisualRenderPipelineBuilder vertexFormat(VertexFormat format, PrimitiveTopology mode) {
delegate.withVertexFormat(format, mode);
return this;
}
public LoVisualRenderPipelineBuilder vertexShader(Identifier id) {
delegate.withVertexShader(id);
return this;
}
public LoVisualRenderPipelineBuilder fragmentShader(Identifier id) {
delegate.withFragmentShader(id);
return this;
}
public LoVisualRenderPipelineBuilder depthTest(DepthTestFunction function) {
delegate.withDepthTestFunction(function);
return this;
}
public LoVisualRenderPipelineBuilder depthWrite(boolean write) {
delegate.withDepthWrite(write);
return this;
}
public LoVisualRenderPipelineBuilder blend(BlendFunction blend) {
delegate.withBlend(blend);
return this;
}
public LoVisualRenderPipelineBuilder cull(boolean cull) {
delegate.withCull(cull);
return this;
}
public LoVisualRenderPipelineBuilder sampler(String name) {
delegate.withSampler(name);
return this;
}
public LoVisualRenderPipelineBuilder uniform(String name, UniformType type) {
delegate.withUniform(name, type);
return this;
}
public LoVisualRenderPipelineBuilder lineSmooth() {
delegate.withLineSmooth();
return this;
}
public LoVisualRenderPipelineBuilder shapeClipSupport() {
delegate.withShapeClipSupport();
return this;
}
public LoVisualRenderPipelineBuilder shapeClipContract(ShapeClipRenderPassContract contract) {
delegate.withShapeClipContract(contract);
return this;
}
public RenderPipeline build() {
return delegate.build();
}
public RenderPipeline buildAndRegister() {
return CombatantRenderPipelines.registerAddonPipeline(build());
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
public enum LoVisualRenderStage {
HUD_RAW,
HUD_SCALED,
HUD_LOGICAL,
HUD_RAW_FOREGROUND,
HUD_SCALED_FOREGROUND,
HUD_LOGICAL_FOREGROUND,
WORLD_BEFORE_TRANSLUCENT,
WORLD_END_MAIN,
WORLD_POST_PROCESS,
SCREEN_BEFORE_VANILLA_GUI,
SCREEN_AFTER_VANILLA_GUI
}

View file

@ -0,0 +1,74 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.buffers.GpuBufferSlice;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import java.nio.ByteBuffer;
@SuppressWarnings("unused")
public enum LoVisualUniforms {
;
public static GpuBufferSlice write(String name,
int std140Size,
int expectedWritesPerFrame,
UniformWriter writer) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Uniform name cannot be blank");
}
if (std140Size <= 0) {
throw new IllegalArgumentException("Uniform std140 size must be positive");
}
if (writer == null) {
throw new IllegalArgumentException("Uniform writer cannot be null");
}
return CombatantRenderSystem.uniforms().write(name, std140Size, expectedWritesPerFrame, writer::write);
}
public static GpuBufferSlice writeCached(String name,
int std140Size,
int expectedWritesPerFrame,
int updateEveryFrames,
boolean force,
UniformWriter writer) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Uniform name cannot be blank");
}
if (std140Size <= 0) {
throw new IllegalArgumentException("Uniform std140 size must be positive");
}
if (writer == null) {
throw new IllegalArgumentException("Uniform writer cannot be null");
}
return CombatantRenderSystem.uniforms().writeCached(
name,
std140Size,
expectedWritesPerFrame,
updateEveryFrames,
force,
writer::write
);
}
public static GpuBufferSlice current(String name) {
if (name == null || name.isBlank()) return null;
return CombatantRenderSystem.uniforms().current(name);
}
public static void invalidate(String name) {
if (name == null || name.isBlank()) return;
CombatantRenderSystem.uniforms().invalidate(name);
}
@FunctionalInterface
public interface UniformWriter {
void write(ByteBuffer buffer);
}
}

View file

@ -0,0 +1,75 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import org.jetbrains.annotations.Nullable;
import xaero.common.minimap.waypoints.Waypoint;
import xaero.hud.minimap.waypoint.WaypointColor;
import xaero.hud.minimap.waypoint.WaypointPurpose;
public enum TriangulatorXaeroMinimapCompat {
;
private static Waypoint hudWaypoint;
private static Waypoint minimapWaypoint;
private static boolean hudActive;
private static boolean minimapActive;
@Nullable
public static Waypoint getHudWaypoint() {
sync();
return hudActive ? hudWaypoint : null;
}
@Nullable
public static Waypoint getMinimapWaypoint() {
sync();
return minimapActive ? minimapWaypoint : null;
}
private static void sync() {
TriangulatorXaeroState.XaeroSnapshot snapshot = TriangulatorXaeroState.snapshot();
if (snapshot == null) {
hudActive = false;
minimapActive = false;
return;
}
TriangulatorXaeroState.SyncPoint point = TriangulatorXaeroState.toCurrentDimension(snapshot);
WaypointColor color = snapshot.ready() ? WaypointColor.GOLD : WaypointColor.RED;
hudWaypoint = syncWaypoint(hudWaypoint, point, color);
minimapWaypoint = syncWaypoint(minimapWaypoint, point, color);
hudActive = true;
minimapActive = true;
}
private static Waypoint syncWaypoint(@Nullable Waypoint waypoint,
TriangulatorXaeroState.SyncPoint point,
WaypointColor color) {
Waypoint result = waypoint;
if (result == null) {
result = new Waypoint(
point.x(),
point.y(),
point.z(),
TriangulatorXaeroState.NAME,
TriangulatorXaeroState.SYMBOL,
color,
WaypointPurpose.NORMAL
);
result.setTemporary(false);
result.setYIncluded(false);
}
result.setX(point.x());
result.setY(point.y());
result.setZ(point.z());
result.setWaypointColor(color);
result.setDisabled(false);
return result;
}
}

View file

@ -0,0 +1,87 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Method;
public enum TriangulatorXaeroState {
;
public static final String NAME = "Stronghold";
public static final String SYMBOL = "S";
public static final String SET = "combatant";
public static final int DEFAULT_Y = 64;
@Nullable
public static XaeroSnapshot snapshot() {
DraggableHudElement triangulator = DraggableHudElementRegistry.getById("triangulator");
if (triangulator == null) return null;
try {
Object raw = triangulator.getClass().getMethod("getXaeroSnapshot").invoke(triangulator);
if (raw == null) return null;
return new XaeroSnapshot(
readDouble(raw, "overworldX"),
readDouble(raw, "overworldZ"),
readBoolean(raw, "ready"),
readDouble(raw, "confidence"),
readInt(raw, "eyeCount")
);
} catch (ReflectiveOperationException | ClassCastException ignored) {
return null;
}
}
public static SyncPoint toCurrentDimension(XaeroSnapshot snapshot) {
boolean nether = isNetherView();
double factor = nether ? 0.125 : 1.0;
return new SyncPoint(
(int) Math.round(snapshot.overworldX() * factor),
DEFAULT_Y,
(int) Math.round(snapshot.overworldZ() * factor)
);
}
public static boolean isNetherView() {
Minecraft mc = Minecraft.getInstance();
return mc != null && mc.level != null && mc.level.dimension() == Level.NETHER;
}
private static double readDouble(Object target, String method) throws ReflectiveOperationException {
Object value = invoke(target, method);
if (value instanceof Number number) return number.doubleValue();
throw new ClassCastException(method);
}
private static boolean readBoolean(Object target, String method) throws ReflectiveOperationException {
Object value = invoke(target, method);
if (value instanceof Boolean bool) return bool;
throw new ClassCastException(method);
}
private static int readInt(Object target, String method) throws ReflectiveOperationException {
Object value = invoke(target, method);
if (value instanceof Number number) return number.intValue();
throw new ClassCastException(method);
}
private static Object invoke(Object target, String method) throws ReflectiveOperationException {
Method accessor = target.getClass().getMethod(method);
return accessor.invoke(target);
}
public record XaeroSnapshot(double overworldX, double overworldZ, boolean ready, double confidence, int eyeCount) {
}
public record SyncPoint(int x, int y, int z) {
}
}

View file

@ -0,0 +1,40 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import org.jetbrains.annotations.Nullable;
import xaero.common.minimap.waypoints.Waypoint;
import xaero.hud.minimap.waypoint.WaypointColor;
import xaero.hud.minimap.waypoint.WaypointPurpose;
import xaero.map.mods.SupportXaeroMinimap;
public enum TriangulatorXaeroWorldMapCompat {
;
@Nullable
public static xaero.map.mods.gui.Waypoint getWaypoint(SupportXaeroMinimap minimap) {
TriangulatorXaeroState.XaeroSnapshot snapshot = TriangulatorXaeroState.snapshot();
if (snapshot == null || minimap == null) {
return null;
}
Waypoint baseWaypoint = new Waypoint(
(int) Math.round(snapshot.overworldX()),
TriangulatorXaeroState.DEFAULT_Y,
(int) Math.round(snapshot.overworldZ()),
TriangulatorXaeroState.NAME,
TriangulatorXaeroState.SYMBOL,
snapshot.ready() ? WaypointColor.GOLD : WaypointColor.RED,
WaypointPurpose.NORMAL
);
baseWaypoint.setTemporary(false);
baseWaypoint.setYIncluded(false);
baseWaypoint.setDisabled(false);
return minimap.convertWaypoint(baseWaypoint, false, TriangulatorXaeroState.SET, minimap.getDimDiv());
}
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import org.jetbrains.annotations.Nullable;
import xaero.common.minimap.waypoints.Waypoint;
import xaero.map.mods.SupportXaeroMinimap;
import java.util.List;
/**
* Kept as a no-op compatibility bridge for older mixin code paths.
* @xwp markers are now inserted into Xaero's real waypoint sets by {@link XaeroWaypointRuntime},
* otherwise World Map/minimap hover, open and delete logic cannot see them.
*/
public enum XaeroCommandWaypointCompat {
;
public static List<Waypoint> getMinimapWaypoints() {
return List.of();
}
public static List<xaero.map.mods.gui.Waypoint> getWorldMapWaypoints(@Nullable SupportXaeroMinimap minimap) {
return List.of();
}
}

View file

@ -0,0 +1,229 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.Level;
import xaero.common.HudMod;
import xaero.common.minimap.waypoints.Waypoint;
import xaero.hud.minimap.BuiltInHudModules;
import xaero.hud.minimap.module.MinimapSession;
import xaero.hud.minimap.waypoint.WaypointColor;
import xaero.hud.minimap.waypoint.WaypointPurpose;
import xaero.hud.minimap.waypoint.set.WaypointSet;
import xaero.hud.minimap.world.MinimapWorld;
import xaero.hud.minimap.world.MinimapWorldManager;
import xaero.hud.path.XaeroPath;
import java.util.ArrayList;
import java.util.List;
final class XaeroWaypointRuntime {
private XaeroWaypointRuntime() {
}
static XaeroWaypointStore.RuntimeAddResult addFromCurrentDimension(int x,
int y,
int z,
String name,
boolean dualDefault) {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.level == null) {
return fail("No client world is loaded.");
}
MinimapSession session = currentSession();
if (session == null) {
return fail("Xaero minimap session is not ready.");
}
List<XaeroWaypointStore.Marker> added = new ArrayList<>(2);
ResourceKey<Level> currentDim = mc.level.dimension();
boolean overworld = currentDim == Level.OVERWORLD;
boolean nether = currentDim == Level.NETHER;
if (dualDefault && overworld) {
addToWorld(session, Level.OVERWORLD, x, y, z, name, "overworld", added);
addToWorld(session, Level.NETHER, XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z), name, "nether", added);
return new XaeroWaypointStore.RuntimeAddResult(true,
"Added dual Xaero marker: " + XaeroWaypointStore.format(x, y, z)
+ " / Nether " + XaeroWaypointStore.format(XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z)) + ".",
List.copyOf(added));
}
if (dualDefault && nether) {
addToWorld(session, Level.NETHER, x, y, z, name, "nether", added);
addToWorld(session, Level.OVERWORLD, x * 8, y, z * 8, name, "overworld", added);
return new XaeroWaypointStore.RuntimeAddResult(true,
"Added dual Xaero marker: Nether " + XaeroWaypointStore.format(x, y, z)
+ " / Overworld " + XaeroWaypointStore.format(x * 8, y, z * 8) + ".",
List.copyOf(added));
}
addToWorld(session, currentDim, x, y, z, name, XaeroWaypointStore.dimensionId(currentDim.identifier()), added);
return new XaeroWaypointStore.RuntimeAddResult(true,
"Added Xaero marker: " + XaeroWaypointStore.format(x, y, z) + ".",
List.copyOf(added));
}
static boolean remove(XaeroWaypointStore.Marker marker) {
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
return true;
}
set.remove(waypoint);
markChanged();
return true;
}
static boolean exists(XaeroWaypointStore.Marker marker) {
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
return false;
}
for (Waypoint existing : set.getWaypoints()) {
if (existing == waypoint) {
return true;
}
}
return false;
}
private static void addToWorld(MinimapSession session,
ResourceKey<Level> dimension,
int x,
int y,
int z,
String name,
String kind,
List<XaeroWaypointStore.Marker> out) {
MinimapWorld world = resolveWorld(session, dimension);
if (world == null) {
throw new IllegalStateException("Could not resolve Xaero world for " + dimension.identifier());
}
WaypointSet set = currentSet(world);
Waypoint waypoint = new Waypoint(
x,
y,
z,
XaeroWaypointStore.displayName(name, kind),
XaeroWaypointStore.DEFAULT_SYMBOL,
WaypointColor.GOLD,
WaypointPurpose.NORMAL,
true,
true
);
waypoint.setTemporary(true);
waypoint.setYIncluded(true);
waypoint.setDisabled(false);
set.add(waypoint);
out.add(XaeroWaypointStore.createMarker(
XaeroWaypointStore.dimensionId(dimension.identifier()),
x,
y,
z,
waypoint.getName(),
waypoint.getSymbol(),
set.getName(),
kind,
set,
waypoint
));
markChanged();
}
private static WaypointSet currentSet(MinimapWorld world) {
WaypointSet set = world.getCurrentWaypointSet();
if (set != null) {
return set;
}
String setId = world.getCurrentWaypointSetId();
if (setId == null || setId.isBlank()) {
setId = XaeroWaypointStore.SET;
world.setCurrentWaypointSetId(setId);
}
set = world.getWaypointSet(setId);
if (set == null) {
world.addWaypointSet(setId);
set = world.getWaypointSet(setId);
}
if (set == null) {
throw new IllegalStateException("Could not resolve Xaero waypoint set.");
}
return set;
}
private static MinimapWorld resolveWorld(MinimapSession session, ResourceKey<Level> dimension) {
Minecraft mc = Minecraft.getInstance();
MinimapWorldManager manager = session.getWorldManager();
if (mc != null && mc.level != null && mc.level.dimension() == dimension) {
return manager.getCurrentWorld();
}
XaeroPath rootPath = session.getWorldState().getCurrentRootContainerPath();
XaeroPath currentWorldPath = session.getWorldState().getCurrentWorldPath();
if (rootPath == null || currentWorldPath == null) {
return manager.getCurrentWorld();
}
String dimensionNode = session.getDimensionHelper().getDimensionDirectoryName(dimension);
if (dimensionNode == null || dimensionNode.isBlank()) {
return null;
}
String worldNode = null;
try {
boolean worldMap = HudMod.INSTANCE != null
&& HudMod.INSTANCE.getSupportMods() != null
&& HudMod.INSTANCE.getSupportMods().worldmap();
worldNode = session.getWorldStateUpdater().getPotentialWorldNode(dimension, worldMap);
} catch (Throwable ignored) {
// Fallback below keeps the marker in the same multiworld node as the current dimension.
}
if (worldNode == null || worldNode.isBlank()) {
worldNode = currentWorldPath.getLastNode();
}
XaeroPath worldPath = rootPath.resolve(dimensionNode).resolve(worldNode);
MinimapWorld world = manager.getWorld(worldPath);
if (world != null) {
world.setDimId(dimension);
}
return world;
}
private static MinimapSession currentSession() {
Object session = BuiltInHudModules.MINIMAP.getCurrentSession();
return session instanceof MinimapSession minimapSession ? minimapSession : null;
}
private static void markChanged() {
MinimapSession session = currentSession();
if (session != null && session.getWaypointSession() != null) {
session.getWaypointSession().setSetChangedTime(System.currentTimeMillis());
}
requestWorldMapRefresh();
}
private static void requestWorldMapRefresh() {
try {
Class<?> supportMods = Class.forName("xaero.map.mods.SupportMods");
Object support = supportMods.getField("xaeroMinimap").get(null);
if (support != null) {
support.getClass().getMethod("requestWaypointsRefresh").invoke(support);
}
} catch (Throwable ignored) {
// World Map is optional; minimap hover/list deletion works through the real Xaero set without it.
}
}
private static XaeroWaypointStore.RuntimeAddResult fail(String message) {
return new XaeroWaypointStore.RuntimeAddResult(false, message, List.of());
}
}

View file

@ -0,0 +1,249 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.Identifier;
import net.minecraft.world.level.Level;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
public enum XaeroWaypointStore {
;
public static final String SET = "combatant";
public static final String DEFAULT_NAME = "LoVisual";
public static final String DEFAULT_SYMBOL = "C";
private static final AtomicLong NEXT_ID = new AtomicLong(1L);
private static final CopyOnWriteArrayList<Marker> MARKERS = new CopyOnWriteArrayList<>();
public static AddResult addFromCurrentDimension(int x, int y, int z, String name, boolean dualDefault) {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.level == null) {
return new AddResult(false, 0, "No client world is loaded.");
}
String safeName = sanitizeName(name);
try {
RuntimeAddResult runtime = XaeroWaypointRuntime.addFromCurrentDimension(x, y, z, safeName, dualDefault);
if (!runtime.success()) {
return new AddResult(false, 0, runtime.message());
}
MARKERS.addAll(runtime.markers());
return new AddResult(true, runtime.markers().size(), runtime.message());
} catch (NoClassDefFoundError | ExceptionInInitializerError error) {
return new AddResult(false, 0, "Xaero waypoint runtime is not available.");
} catch (Throwable throwable) {
return new AddResult(false, 0, "Failed to add Xaero marker: " + throwable.getClass().getSimpleName() + ".");
}
}
public static List<Marker> currentDimensionMarkers() {
pruneMissing();
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.level == null || MARKERS.isEmpty()) return List.of();
String dim = dimensionId(mc.level.dimension().identifier());
List<Marker> out = new ArrayList<>();
for (Marker marker : MARKERS) {
if (marker.dimensionId().equals(dim)) {
out.add(marker);
}
}
return out;
}
public static List<Marker> markers() {
pruneMissing();
return List.copyOf(MARKERS);
}
public static RemoveResult remove(String selector) {
pruneMissing();
if (MARKERS.isEmpty()) {
return new RemoveResult(true, 0, "No LoVisual Xaero markers to remove.");
}
List<Marker> targets = select(selector);
if (targets.isEmpty()) {
return new RemoveResult(false, 0, "No matching LoVisual Xaero marker: " + selector + ".");
}
int removed = 0;
for (Marker marker : targets) {
if (removeMarker(marker)) {
removed++;
}
}
if (removed == 0) {
return new RemoveResult(false, 0, "No LoVisual Xaero markers were removed.");
}
return new RemoveResult(true, removed, "Removed Xaero markers: " + removed + ".");
}
public static int clear() {
return remove(null).count();
}
static Marker createMarker(String dimensionId,
int x,
int y,
int z,
String name,
String symbol,
String set,
String kind,
Object waypointSetHandle,
Object waypointHandle) {
return new Marker(
NEXT_ID.getAndIncrement(),
dimensionId,
x,
y,
z,
name,
symbol,
set,
kind,
System.currentTimeMillis(),
waypointSetHandle,
waypointHandle
);
}
private static List<Marker> select(String selector) {
String normalized = selector == null ? "" : selector.trim();
if (normalized.isEmpty()
|| "all".equalsIgnoreCase(normalized)
|| "*".equals(normalized)) {
return new ArrayList<>(MARKERS);
}
Integer index = parsePositiveInt(normalized);
if (index != null) {
List<Marker> snapshot = markers();
int zeroIndex = index - 1;
if (zeroIndex >= 0 && zeroIndex < snapshot.size()) {
return List.of(snapshot.get(zeroIndex));
}
return List.of();
}
String lower = normalized.toLowerCase(Locale.ROOT);
List<Marker> out = new ArrayList<>();
for (Marker marker : MARKERS) {
if (marker.name().toLowerCase(Locale.ROOT).contains(lower)
|| marker.kind().toLowerCase(Locale.ROOT).contains(lower)
|| marker.dimensionId().toLowerCase(Locale.ROOT).contains(lower)) {
out.add(marker);
}
}
return out;
}
private static boolean removeMarker(Marker marker) {
boolean removedFromXaero = true;
try {
removedFromXaero = XaeroWaypointRuntime.remove(marker);
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
removedFromXaero = true;
} catch (Throwable ignored) {
removedFromXaero = false;
}
boolean removedFromStore = MARKERS.remove(marker);
return removedFromStore && removedFromXaero;
}
private static void pruneMissing() {
if (MARKERS.isEmpty()) return;
try {
Iterator<Marker> iterator = MARKERS.iterator();
while (iterator.hasNext()) {
Marker marker = iterator.next();
if (!XaeroWaypointRuntime.exists(marker)) {
MARKERS.remove(marker);
}
}
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
MARKERS.clear();
} catch (Throwable ignored) {
// Keep the in-memory index if Xaero is mid-session reload or unavailable for a tick.
}
}
static int netherCoord(int overworldCoord) {
return (int) Math.round(overworldCoord / 8.0);
}
static String dimensionId(Identifier id) {
return id == null ? "" : id.toString();
}
static String sanitizeName(String name) {
if (name == null || name.isBlank()) return DEFAULT_NAME;
String trimmed = name.trim();
return trimmed.length() > 40 ? trimmed.substring(0, 40) : trimmed;
}
static String displayName(String name, String kind) {
String safeName = sanitizeName(name);
if (kind == null || kind.isBlank() || kind.contains(":")) return safeName;
return safeName + " " + kind;
}
static String format(int x, int y, int z) {
return String.format(Locale.ROOT, "%d %d %d", x, y, z);
}
private static Integer parsePositiveInt(String value) {
try {
int parsed = Integer.parseInt(value);
return parsed <= 0 ? null : parsed;
} catch (NumberFormatException ignored) {
return null;
}
}
static boolean isOverworld() {
Minecraft mc = Minecraft.getInstance();
return mc != null && mc.level != null && mc.level.dimension() == Level.OVERWORLD;
}
static boolean isNether() {
Minecraft mc = Minecraft.getInstance();
return mc != null && mc.level != null && mc.level.dimension() == Level.NETHER;
}
public record Marker(long id,
String dimensionId,
int x,
int y,
int z,
String name,
String symbol,
String set,
String kind,
long createdAtMs,
Object waypointSetHandle,
Object waypointHandle) {
}
public record AddResult(boolean success, int count, String message) {
}
public record RemoveResult(boolean success, int count, String message) {
}
static record RuntimeAddResult(boolean success, String message, List<Marker> markers) {
}
}

View file

@ -0,0 +1,21 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Event {
private boolean cancelled;
public void cancel() {
cancelled = true;
}
}

View file

@ -0,0 +1,263 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.runtime.RuntimeGate;
import dev.loki.lovisual.util.logging.DebugLog;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public final class EventBus {
private static final Subscriber[] EMPTY_SUBSCRIBERS = new Subscriber[0];
private static final Comparator<Subscriber> PRIORITY =
Comparator.comparingInt((Subscriber sub) -> sub.priority).reversed();
private final Object lock = new Object();
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> exactHandlers = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> dispatchCache = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<Object, Subscriber[]> ownerIndex = new Reference2ObjectOpenHashMap<>();
private static Subscriber[] append(Subscriber[] old, Subscriber sub) {
Subscriber[] next = Arrays.copyOf(old, old.length + 1);
next[old.length] = sub;
return next;
}
private static Subscriber[] remove(Subscriber[] old, Subscriber sub) {
int index = -1;
for (int i = 0; i < old.length; i++) {
if (old[i] == sub) {
index = i;
break;
}
}
if (index < 0) return old;
if (old.length == 1) return EMPTY_SUBSCRIBERS;
Subscriber[] next = new Subscriber[old.length - 1];
System.arraycopy(old, 0, next, 0, index);
System.arraycopy(old, index + 1, next, index, old.length - index - 1);
return next;
}
private static void sortSubscribers(Subscriber[] subscribers) {
Arrays.sort(subscribers, PRIORITY);
}
public void register(Object listener) {
if (listener instanceof Module module) {
registerOwned(module, listener);
} else {
registerOwned(null, listener);
}
}
public void registerOwned(Module gateModule, Object listener) {
if (listener == null) return;
synchronized (lock) {
if (ownerIndex.containsKey(listener)) return;
Subscriber[] subs = scan(listener, gateModule);
if (subs.length == 0) return;
ownerIndex.put(listener, subs);
for (Subscriber sub : subs) {
Subscriber[] old = exactHandlers.get(sub.eventType);
if (old == null) old = EMPTY_SUBSCRIBERS;
Subscriber[] next = append(old, sub);
sortSubscribers(next);
exactHandlers.put(sub.eventType, next);
}
dispatchCache.clear();
}
}
public void unregister(Object listener) {
if (listener == null) return;
synchronized (lock) {
Subscriber[] subs = ownerIndex.remove(listener);
if (subs == null || subs.length == 0) return;
for (Subscriber sub : subs) {
Subscriber[] old = exactHandlers.get(sub.eventType);
if (old == null || old.length == 0) continue;
Subscriber[] next = remove(old, sub);
if (next.length == 0) {
exactHandlers.remove(sub.eventType);
} else {
exactHandlers.put(sub.eventType, next);
}
}
dispatchCache.clear();
}
}
public boolean hasListeners(Class<? extends Event> eventType) {
return subscribersFor(eventType).length != 0;
}
public <T extends Event> T post(T event) {
if (event == null) return null;
if (!RuntimeGate.canRunClientLogic()) return event;
Subscriber[] subscribers = subscribersFor(event.getClass());
for (Subscriber sub : subscribers) {
Module gate = sub.gateModule;
if (gate != null && !gate.isEnabled()) continue;
try {
sub.invoker.invoke(event);
} catch (Throwable t) {
DebugLog.error("Event handler failed: %s", t, sub.describe());
}
}
return event;
}
public void clear() {
synchronized (lock) {
exactHandlers.clear();
dispatchCache.clear();
ownerIndex.clear();
}
}
public int listenerCount() {
synchronized (lock) {
return ownerIndex.size();
}
}
private Subscriber[] scan(Object listener, Module gateModule) {
List<Subscriber> out = new ArrayList<>();
Class<?> cls = listener.getClass();
for (Method method : cls.getDeclaredMethods()) {
if (!method.isAnnotationPresent(EventHandler.class)) continue;
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) continue;
if (!Event.class.isAssignableFrom(params[0])) continue;
EventHandler meta = method.getAnnotation(EventHandler.class);
method.setAccessible(true);
@SuppressWarnings("unchecked")
Class<? extends Event> eventType = (Class<? extends Event>) params[0];
EventInvoker invoker = createInvoker(listener, method);
out.add(new Subscriber(listener, gateModule, method, invoker, eventType, meta.priority()));
}
return out.toArray(Subscriber[]::new);
}
private EventInvoker createInvoker(Object listener, Method method) {
method.setAccessible(true);
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.unreflect(method).bindTo(listener);
return handle::invoke;
} catch (Throwable t) {
DebugLog.error("Failed to create MethodHandle event invoker, falling back to reflection: %s", t,
listener.getClass().getName() + "#" + method.getName());
return event -> method.invoke(listener, event);
}
}
private Subscriber[] subscribersFor(Class<?> eventType) {
if (eventType == null) return EMPTY_SUBSCRIBERS;
synchronized (lock) {
Subscriber[] cached = dispatchCache.get(eventType);
if (cached != null) return cached;
Subscriber[] built = buildFlattenedSubscribers(eventType);
dispatchCache.put(eventType, built);
return built;
}
}
private Subscriber[] buildFlattenedSubscribers(Class<?> eventType) {
int total = 0;
Class<?> type = eventType;
while (type != null && Event.class.isAssignableFrom(type)) {
Subscriber[] exact = exactHandlers.get(type);
if (exact != null) total += exact.length;
type = type.getSuperclass();
}
if (total == 0) return EMPTY_SUBSCRIBERS;
Subscriber[] out = new Subscriber[total];
int offset = 0;
type = eventType;
while (type != null && Event.class.isAssignableFrom(type)) {
Subscriber[] exact = exactHandlers.get(type);
if (exact != null && exact.length > 0) {
System.arraycopy(exact, 0, out, offset, exact.length);
offset += exact.length;
}
type = type.getSuperclass();
}
return out;
}
@FunctionalInterface
private interface EventInvoker {
void invoke(Event event) throws Throwable;
}
private static final class Subscriber {
final Object owner;
final Module gateModule;
final Method method;
final EventInvoker invoker;
final Class<? extends Event> eventType;
final int priority;
final String description;
Subscriber(Object owner,
Module gateModule,
Method method,
EventInvoker invoker,
Class<? extends Event> eventType,
int priority) {
this.owner = owner;
this.gateModule = gateModule;
this.method = method;
this.invoker = invoker;
this.eventType = eventType;
this.priority = priority;
this.description = owner.getClass().getName() + "#" + method.getName();
}
String describe() {
return description;
}
}
}

View file

@ -0,0 +1,20 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@UsedImplicitly
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventHandler {
int priority() default 0;
}

View file

@ -0,0 +1,14 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
public enum Events {
;
public static final EventBus BUS = new EventBus();
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks code that is intentionally reached through reflection, Fabric entrypoints,
* addon API calls, event dispatch, serialization, or other non-direct call paths.
*
* <p>This is a source-level documentation and IntelliJ IDEA inspection hint. It is
* not a runtime contract and should not be used for behavior checks.</p>
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE
})
public @interface UsedImplicitly {
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import dev.loki.lovisual.events.Event;
@Getter
public final class AttackEntityEvent extends Event {
private final Player player;
private final Entity target;
public AttackEntityEvent(Player player, Entity target) {
this.player = player;
this.target = target;
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on LiquidBounce
* (https://github.com/CCBlueX/LiquidBounce).
* Copyright (c) 2015-2026 CCBlueX.
*
* LiquidBounce portions are licensed under GPLv3-or-later.
* Combatant modifications are licensed under GPLv3.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.network.protocol.Packet;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.network.BlinkManager;
import dev.loki.lovisual.util.network.TransferOrigin;
/**
* Adapted from LiquidBounce's BlinkPacketEvent.
*/
public class BlinkPacketEvent extends Event {
private final Packet<?> packet;
@Getter
private final TransferOrigin origin;
@Getter
private BlinkManager.Action action = BlinkManager.Action.FLUSH;
public BlinkPacketEvent(Packet<?> packet, TransferOrigin origin) {
this.packet = packet;
this.origin = origin;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> T getPacket() {
return (T) packet;
}
public void setAction(BlinkManager.Action action) {
if (action == null || this.action == action || this.action.getPriority() >= action.getPriority()) {
return;
}
this.action = action;
}
}

View file

@ -0,0 +1,26 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import java.util.List;
public class CombatProtocolBossbarEvent extends Event {
public final List<String> names;
public final long timeMs;
public CombatProtocolBossbarEvent(List<String> names) {
this(names, System.currentTimeMillis());
}
public CombatProtocolBossbarEvent(List<String> names, long timeMs) {
this.names = names == null ? List.of() : List.copyOf(names);
this.timeMs = timeMs;
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.HitResult;
import dev.loki.lovisual.events.Event;
@Getter
public final class CrosshairTargetUpdateEvent extends Event {
private final float tickDelta;
@Setter
private HitResult hitResult;
@Setter
private Entity targetedEntity;
public CrosshairTargetUpdateEvent(float tickDelta, HitResult hitResult, Entity targetedEntity) {
this.tickDelta = tickDelta;
this.hitResult = hitResult;
this.targetedEntity = targetedEntity;
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.core.BlockPos;
import dev.loki.lovisual.events.Event;
@Getter
public class EventBreakBlock extends Event {
private final BlockPos pos;
public EventBreakBlock(BlockPos pos) {
this.pos = pos;
}
}

View file

@ -0,0 +1,27 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.state.BlockState;
import dev.loki.lovisual.events.Event;
@Getter
public class EventCollision extends Event {
private final BlockPos pos;
@Setter
private BlockState state;
public EventCollision(BlockState state, BlockPos pos) {
this.state = state;
this.pos = pos;
}
}

View file

@ -0,0 +1,15 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
public class EventPostSync extends Event {
public EventPostSync() {
}
}

View file

@ -0,0 +1,23 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
@Getter
public class EventPushOutOfBlocks extends Event {
private final double x;
private final double z;
public EventPushOutOfBlocks(double x, double z) {
this.x = x;
this.z = z;
}
}

View file

@ -0,0 +1,69 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
public class EventSync extends Event {
@Getter
private final float originalYaw;
@Getter
private final float originalPitch;
@Getter
private float yaw;
@Getter
private float pitch;
private boolean rotationOverride;
@Getter
private boolean silentRotation;
@Getter
private Runnable postAction;
public EventSync(float yaw, float pitch) {
this.originalYaw = yaw;
this.originalPitch = pitch;
this.yaw = yaw;
this.pitch = pitch;
}
public void setYaw(float yaw) {
this.yaw = yaw;
this.rotationOverride = true;
}
public void setPitch(float pitch) {
this.pitch = pitch;
this.rotationOverride = true;
}
public void setRotation(float yaw, float pitch, boolean silent) {
this.yaw = yaw;
this.pitch = pitch;
this.rotationOverride = true;
this.silentRotation = silent;
}
public boolean hasRotationOverride() {
return rotationOverride;
}
public void addPostAction(Runnable r) {
if (r == null) return;
if (postAction == null) {
postAction = r;
} else {
Runnable prev = postAction;
postAction = () -> {
prev.run();
r.run();
};
}
}
}

View file

@ -0,0 +1,32 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import net.minecraft.world.entity.LivingEntity;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.target.TargetManager;
/**
* Fired when the centralized target changes.
*/
public class EventTargetChanged extends Event {
public final LivingEntity previous;
public final TargetManager.Source previousSource;
public final LivingEntity current;
public final TargetManager.Source currentSource;
public EventTargetChanged(LivingEntity previous,
TargetManager.Source previousSource,
LivingEntity current,
TargetManager.Source currentSource) {
this.previous = previous;
this.previousSource = previousSource;
this.current = current;
this.currentSource = currentSource;
}
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Setter
@Getter
public final class FireworkEvent extends Event {
private Vec3 vector;
public FireworkEvent(Vec3 vector) {
this.vector = vector;
}
}

View file

@ -0,0 +1,16 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired at the start of each client tick.
*/
public final class GameTickEvent extends Event {
}

View file

@ -0,0 +1,94 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.SettingOwner;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.features.gui.clickgui.settings.Setting;
import dev.loki.lovisual.features.gui.clickgui.settings.SettingFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Collects setting-backed i18n keys after language resources are loaded.
*/
public final class I18nPreflightCollectEvent extends Event {
private final String reason;
private final ArrayList<Entry> entries = new ArrayList<>();
public I18nPreflightCollectEvent(String reason) {
this.reason = reason != null && !reason.isBlank() ? reason : "i18n preflight";
}
public String reason() {
return reason;
}
public I18nPreflightCollectEvent setting(Setting setting) {
return setting("settings", setting);
}
public I18nPreflightCollectEvent setting(String path, Setting setting) {
if (setting != null) {
entries.add(new Entry(normalizePath(path), setting));
}
return this;
}
public I18nPreflightCollectEvent settings(Iterable<? extends Setting> values) {
return settings("settings", values);
}
public I18nPreflightCollectEvent settings(String path, Iterable<? extends Setting> values) {
if (values == null) return this;
for (Setting setting : values) {
setting(path, setting);
}
return this;
}
public I18nPreflightCollectEvent settingDefs(SettingOwner owner, Iterable<SettingDef> defs) {
return settingDefs(owner != null ? owner.name() : "settings", owner, defs);
}
public I18nPreflightCollectEvent settingDefs(String path, SettingOwner owner, Iterable<SettingDef> defs) {
if (owner == null || defs == null) return this;
for (SettingDef def : defs) {
Setting setting = SettingFactory.fromDef(def);
if (setting == null) continue;
setting.setParent(owner);
setting(path, setting);
}
return this;
}
public List<Entry> entries() {
return Collections.unmodifiableList(entries);
}
public boolean isEmpty() {
return entries.isEmpty();
}
private static String normalizePath(String path) {
if (path == null || path.isBlank()) return "settings";
String normalized = path.trim().replace('\\', '/');
while (normalized.contains("//")) {
normalized = normalized.replace("//", "/");
}
if (normalized.startsWith("/")) normalized = normalized.substring(1);
if (normalized.endsWith("/")) normalized = normalized.substring(0, normalized.length() - 1);
return normalized.isBlank() ? "settings" : normalized;
}
public record Entry(String path, Setting setting) {
}
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.client.input.KeyEvent;
import dev.loki.lovisual.events.Event;
@Getter
public final class KeyInputEvent extends Event {
private final int action;
private final KeyEvent input;
public KeyInputEvent(int action, KeyEvent input) {
this.action = action;
this.input = input;
}
}

View file

@ -0,0 +1,27 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.KeyMapping;
import dev.loki.lovisual.events.Event;
@Getter
public final class KeybindIsPressedEvent extends Event {
private final KeyMapping keyBinding;
@Setter
private boolean pressed;
public KeybindIsPressedEvent(KeyMapping keyBinding, boolean pressed) {
this.keyBinding = keyBinding;
this.pressed = pressed;
}
}

View file

@ -0,0 +1,34 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Getter
public class LightmapEvent extends Event {
private final float originalAmbient;
@Setter
private float ambientLight;
public LightmapEvent(float ambientLight) {
this.originalAmbient = ambientLight;
this.ambientLight = ambientLight;
}
public void raiseAmbientLight(float ambientLight) {
if (ambientLight > this.ambientLight) {
this.ambientLight = ambientLight;
}
}
public boolean isModified() {
return Math.abs(ambientLight - originalAmbient) > 1.0e-4f;
}
}

View file

@ -0,0 +1,81 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.client.renderer.state.LightmapRenderState;
import net.minecraft.util.Mth;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import dev.loki.lovisual.events.Event;
public class LightmapModifyEvent extends Event {
private static final float EPSILON = 1.0e-4f;
private final LightmapRenderState state;
private final float originalBrightness;
@Getter
private boolean modified;
public LightmapModifyEvent(LightmapRenderState state) {
this.state = state;
this.originalBrightness = state != null ? state.brightness : 0.0f;
}
public LightmapRenderState state() {
return state;
}
public float originalBrightness() {
return originalBrightness;
}
public void raiseMinimumLight(float minLight) {
if (state == null) return;
float strength = Mth.clamp(minLight, 0.0f, 1.0f);
if (strength <= EPSILON) return;
state.needsUpdate = true;
// Do not emulate FullBright by forcing brightness/night vision to 1.0.
// In the 1.21+ UBO lightmap path that behaves like global exposure and blows out the scene.
float exposureFloor = 0.08f + 0.18f * strength;
state.brightness = Math.max(state.brightness, exposureFloor);
state.nightVisionEffectIntensity = Math.max(state.nightVisionEffectIntensity, 0.10f * strength);
// Lift the generated lightmap itself, but keep vanilla color response instead of whitening it.
state.skyFactor = Math.max(state.skyFactor, 0.55f + 0.35f * strength);
state.blockFactor = Math.max(state.blockFactor, 1.4f + 0.25f * strength);
// FullBright must not be attenuated by darkness/boss-world darkening.
float attenuation = 1.0f - strength;
state.darknessEffectScale *= attenuation;
state.bossOverlayWorldDarkening *= attenuation;
float colorFloor = 0.10f + 0.28f * strength;
state.blockLightTint = raiseColorFloor(state.blockLightTint, colorFloor);
state.skyLightColor = raiseColorFloor(state.skyLightColor, colorFloor);
state.ambientColor = raiseColorFloor(state.ambientColor, colorFloor);
state.nightVisionColor = raiseColorFloor(state.nightVisionColor, colorFloor);
modified = true;
}
private static Vector3fc raiseColorFloor(Vector3fc color, float floor) {
float min = Mth.clamp(floor, 0.0f, 1.0f);
if (color == null) {
return new Vector3f(min, min, min);
}
return new Vector3f(
Math.max(color.x(), min),
Math.max(color.y(), min),
Math.max(color.z(), min)
);
}
}

View file

@ -0,0 +1,45 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on LiquidBounce
* (https://github.com/CCBlueX/LiquidBounce).
* Copyright (c) 2015-2026 CCBlueX.
*
* LiquidBounce portions are licensed under GPLv3-or-later.
* Combatant modifications are licensed under GPLv3.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.player.Input;
import dev.loki.lovisual.events.Event;
@Setter
@Getter
public final class MovementInputEvent extends Event {
private boolean forward;
private boolean backward;
private boolean left;
private boolean right;
private boolean jump;
private boolean sneak;
private boolean sprint;
public MovementInputEvent(Input input) {
this.forward = input.forward();
this.backward = input.backward();
this.left = input.left();
this.right = input.right();
this.jump = input.jump();
this.sneak = input.shift();
this.sprint = input.sprint();
}
public Input toPlayerInput() {
return new Input(forward, backward, left, right, jump, sneak, sprint);
}
}

View file

@ -0,0 +1,76 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.network.protocol.Packet;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.network.TransferOrigin;
public class PacketEvent extends Event {
private final Packet<?> packet;
@Getter
private final TransferOrigin origin;
@Getter
private final boolean original;
public PacketEvent(Packet<?> packet) {
this(packet, null, true);
}
public PacketEvent(Packet<?> packet, TransferOrigin origin, boolean original) {
this.packet = packet;
this.origin = origin;
this.original = original;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> T getPacket() {
return (T) this.packet;
}
public static class Send extends PacketEvent {
public Send(Packet<?> packet) {
super(packet, TransferOrigin.OUTGOING, true);
}
public Send(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.OUTGOING, original);
}
}
public static class Receive extends PacketEvent {
public Receive(Packet<?> packet) {
super(packet, TransferOrigin.INCOMING, true);
}
public Receive(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.INCOMING, original);
}
}
public static class SendPost extends PacketEvent {
public SendPost(Packet<?> packet) {
super(packet, TransferOrigin.OUTGOING, true);
}
@SuppressWarnings("unused")
public SendPost(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.OUTGOING, original);
}
}
public static class ReceivePost extends PacketEvent {
public ReceivePost(Packet<?> packet) {
super(packet, TransferOrigin.INCOMING, true);
}
@SuppressWarnings("unused")
public ReceivePost(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.INCOMING, original);
}
}
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public final class PlayerJumpEvent extends Event {
private float yaw;
private float motion;
public PlayerJumpEvent(float yaw, float motion) {
this.yaw = yaw;
this.motion = motion;
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on, adapted from, or implemented
* with reference to Meteor Client
* (https://github.com/MeteorDevelopment/meteor-client).
* Copyright (c) Meteor Development.
*
* Licensed under the GNU General Public License v3.0.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public class PlayerMoveEvent extends Event {
private final MoverType type;
@Setter
private Vec3 movement;
public PlayerMoveEvent(MoverType type, Vec3 movement) {
this.type = type;
this.movement = movement;
}
}

View file

@ -0,0 +1,19 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PlayerSafeWalkEvent extends Event {
private boolean safeWalk;
}

View file

@ -0,0 +1,23 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public final class PlayerStepEvent extends Event {
private float height;
public PlayerStepEvent(float height) {
this.height = height;
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public final class PlayerStepSuccessEvent extends Event {
private final Vec3 adjustedVec;
public PlayerStepSuccessEvent(Vec3 adjustedVec) {
this.adjustedVec = adjustedVec;
}
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public class PlayerVelocityStrafe extends Event {
private final Vec3 movementInput;
private final float speed;
private final float yaw;
@Setter
private Vec3 velocity;
public PlayerVelocityStrafe(Vec3 movementInput, float speed, float yaw, Vec3 velocity) {
this.movementInput = movementInput;
this.speed = speed;
this.yaw = yaw;
this.velocity = velocity;
}
}

View file

@ -0,0 +1,19 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PostPlayerUpdateEvent extends Event {
private int iterations;
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired when a PvP-related chat or game message is received.
*/
public class PvpChatEvent extends Event {
public final String message;
public final Source source;
public final long timeMs;
public PvpChatEvent(String message, Source source) {
this(message, source, System.currentTimeMillis());
}
public PvpChatEvent(String message, Source source, long timeMs) {
this.message = message;
this.source = source;
this.timeMs = timeMs;
}
public enum Source {
GAME_MESSAGE,
CHAT_MESSAGE
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.events.Event;
/**
* Fired when an in-game HUD overlay message is shown (action bar).
*/
public class PvpOverlayEvent extends Event {
public final Component message;
public final boolean tinted;
public final long timeMs;
public PvpOverlayEvent(Component message, boolean tinted) {
this(message, tinted, System.currentTimeMillis());
}
public PvpOverlayEvent(Component message, boolean tinted, long timeMs) {
this.message = message;
this.tinted = tinted;
this.timeMs = timeMs;
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired when the server updates tab-list header/footer text.
*/
public class PvpTabEvent extends Event {
public final String header;
public final String footer;
public final long timeMs;
public PvpTabEvent(String header, String footer) {
this(header, footer, System.currentTimeMillis());
}
public PvpTabEvent(String header, String footer, long timeMs) {
this.header = header == null ? "" : header;
this.footer = footer == null ? "" : footer;
this.timeMs = timeMs;
}
public String combinedText() {
if (header.isBlank()) return footer;
if (footer.isBlank()) return header;
return header + "\n" + footer;
}
}

View file

@ -0,0 +1,81 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.render.engine.svg.SvgRegistry;
import dev.loki.lovisual.render.engine.text.FontInfo;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Collects render resources that are known to be needed before the first GUI/HUD draw.
* Producers should add only resources implied by current runtime state/config: enabled
* modules, enabled HUD elements, and UI surfaces that can be opened immediately.
*/
public final class RenderPrewarmCollectEvent extends Event {
private final String reason;
private final LinkedHashSet<FontInfo> fonts = new LinkedHashSet<>();
private final LinkedHashSet<Identifier> svgMsdfIcons = new LinkedHashSet<>();
public RenderPrewarmCollectEvent(String reason) {
this.reason = reason != null ? reason : "render prewarm";
}
public String reason() {
return reason;
}
public RenderPrewarmCollectEvent font(String family) {
return font(family, FontInfo.Type.Regular);
}
public RenderPrewarmCollectEvent font(String family, FontInfo.Type type) {
if (family == null || family.isBlank()) return this;
fonts.add(new FontInfo(family.trim(), type != null ? type : FontInfo.Type.Regular));
return this;
}
public RenderPrewarmCollectEvent font(@Nullable FontInfo info) {
if (info != null && info.family() != null && !info.family().isBlank()) {
fonts.add(info);
}
return this;
}
public RenderPrewarmCollectEvent svg(String nameOrPath) {
Identifier id = SvgRegistry.resolve(nameOrPath);
if (id != null) {
svgMsdfIcons.add(id);
}
return this;
}
public RenderPrewarmCollectEvent svg(@Nullable Identifier id) {
if (id != null) {
svgMsdfIcons.add(id);
}
return this;
}
public Set<FontInfo> fonts() {
return Collections.unmodifiableSet(fonts);
}
public Set<Identifier> svgMsdfIcons() {
return Collections.unmodifiableSet(svgMsdfIcons);
}
public boolean isEmpty() {
return fonts.isEmpty() && svgMsdfIcons.isEmpty();
}
}

View file

@ -0,0 +1,28 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
/**
* Rotation lifecycle event fired each tick in two phases.
*/
@Getter
public final class RotationUpdateEvent extends Event {
private final Type type;
public RotationUpdateEvent(Type type) {
this.type = type == null ? Type.PRE : type;
}
public enum Type {
PRE,
POST
}
}

View file

@ -0,0 +1,43 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
public class SprintControlEvent extends Event {
@Getter
private final float forward;
@Getter
private final float sideways;
@Getter
private final Source source;
@Setter
private boolean sprint;
public SprintControlEvent(float forward, float sideways, boolean sprint, Source source) {
this.forward = forward;
this.sideways = sideways;
this.sprint = sprint;
this.source = source;
}
public boolean isMoving() {
return forward != 0.0f || sideways != 0.0f;
}
public boolean shouldSprint() {
return sprint;
}
public enum Source {
INPUT,
MOVEMENT_TICK,
NETWORK
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
public enum AccountAuthType {
OFFLINE("offline"),
MICROSOFT("microsoft");
private final String id;
AccountAuthType(String id) {
this.id = id;
}
public String id() {
return id;
}
public static AccountAuthType byId(String raw) {
if (raw == null || raw.isBlank()) {
return OFFLINE;
}
for (AccountAuthType type : values()) {
if (type.id.equalsIgnoreCase(raw.trim()) || type.name().equalsIgnoreCase(raw.trim())) {
return type;
}
}
return OFFLINE;
}
}

View file

@ -0,0 +1,473 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import net.minecraft.resources.Identifier;
import dev.loki.lovisual.config.ConfigNameProvider;
import dev.loki.lovisual.config.ConfigSerializer;
import dev.loki.lovisual.config.JsonConfigObject;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.config.values.StringValue;
import dev.loki.lovisual.util.session.MicrosoftSessionResult;
import dev.loki.lovisual.util.session.SessionChanger;
import dev.loki.lovisual.util.session.microsoft.MicrosoftAuthService;
import dev.loki.lovisual.util.logging.DebugLog;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public final class AccountConfig implements JsonConfigObject, ConfigNameProvider {
public static final AccountConfig INSTANCE = new AccountConfig();
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
private final AccountsValue accounts = new AccountsValue("accounts");
private final StringValue activeAccountName = new StringValue("active_name", "");
private final StringValue activeAccountDate = new StringValue("active_date", "");
private final StringValue activeAccountSkin = new StringValue("active_skin", "");
private String microsoftAuthorizationRequiredName = "";
private AccountConfig() {
ConfigSerializer.load(this);
applyActiveSession();
}
public static AccountConfig get() {
return INSTANCE;
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
private static String normalizeName(String name) {
return name == null ? "" : name.trim();
}
private static String nowString() {
return LocalDateTime.now().format(DATE_FORMAT);
}
private static Identifier parseIdentifier(String raw) {
if (isBlank(raw)) {
return null;
}
try {
return Identifier.parse(raw);
} catch (Exception ignored) {
return null;
}
}
private static UUID parseUuid(String raw) {
if (isBlank(raw)) {
return null;
}
try {
return UUID.fromString(raw.trim());
} catch (Exception ignored) {
return null;
}
}
public List<AccountEntry> getAccounts() {
return accounts.get();
}
public List<AccountEntry> getSortedAccounts() {
List<AccountEntry> sorted = new ArrayList<>(accounts.get());
sorted.sort(Comparator
.comparing(AccountEntry::isPinned).reversed()
.thenComparingInt(AccountEntry::getOriginalIndex));
return sorted;
}
public AccountEntry getAccountBySortedIndex(int sortedIndex) {
List<AccountEntry> sorted = getSortedAccounts();
if (sortedIndex < 0 || sortedIndex >= sorted.size()) {
return null;
}
return sorted.get(sortedIndex);
}
public AccountEntry findByName(String name) {
String normalized = normalizeName(name);
if (normalized.isEmpty()) {
return null;
}
for (AccountEntry entry : accounts.get()) {
if (normalizeName(entry.getName()).equals(normalized)) {
return entry;
}
}
return null;
}
public AccountEntry addAccount(String name) {
return addAccount(name, nowString(), null);
}
public AccountEntry addAccount(String name, String date, Identifier skin) {
String cleanName = normalizeName(name);
if (cleanName.isEmpty()) {
return null;
}
AccountEntry existing = findByName(cleanName);
if (existing != null) {
existing.setAuthType(AccountAuthType.OFFLINE);
existing.setOnlineUuid(null);
existing.setMicrosoftRefreshToken("");
clearAuthorizationRequired(existing.getName());
if (!isBlank(date)) {
existing.setDate(date);
}
if (skin != null) {
existing.setSkin(skin);
}
save();
return existing;
}
AccountEntry entry = new AccountEntry(cleanName, isBlank(date) ? nowString() : date, skin, false, accounts.get().size());
accounts.get().add(entry);
save();
return entry;
}
public AccountEntry addMicrosoftAccount(MicrosoftSessionResult session) {
if (session == null || isBlank(session.name()) || session.uuid() == null || isBlank(session.refreshToken())) {
return null;
}
AccountEntry existing = findByName(session.name());
if (existing != null) {
existing.applyMicrosoftSession(session);
existing.setDate(nowString());
clearAuthorizationRequired(existing.getName());
save();
return existing;
}
AccountEntry entry = new AccountEntry(
session.name(),
nowString(),
null,
false,
accounts.get().size(),
AccountAuthType.MICROSOFT,
session.uuid(),
session.refreshToken()
);
accounts.get().add(entry);
clearAuthorizationRequired(entry.getName());
save();
return entry;
}
public void removeAccount(AccountEntry entry) {
if (entry == null) {
return;
}
if (!accounts.get().remove(entry)) {
return;
}
if (isActive(entry)) {
clearActiveAccount();
} else {
reindexAccounts();
save();
}
}
public void removeAccountBySortedIndex(int sortedIndex) {
removeAccount(getAccountBySortedIndex(sortedIndex));
}
public void clearAllAccounts() {
accounts.get().clear();
activeAccountName.set("");
activeAccountDate.set("");
activeAccountSkin.set("");
microsoftAuthorizationRequiredName = "";
save();
}
public void togglePin(int sortedIndex) {
AccountEntry entry = getAccountBySortedIndex(sortedIndex);
if (entry == null) {
return;
}
entry.togglePinned();
save();
}
public void setActiveAccount(AccountEntry entry) {
if (entry == null) {
clearActiveAccount();
return;
}
activeAccountName.set(normalizeName(entry.getName()));
activeAccountDate.set(entry.getDate() == null ? "" : entry.getDate());
Identifier skin = entry.getSkin();
activeAccountSkin.set(skin == null ? "" : skin.toString());
applySession(entry);
save();
}
public void setActiveAccount(String name, String date, Identifier skin) {
String cleanName = normalizeName(name);
if (cleanName.isEmpty()) {
clearActiveAccount();
return;
}
AccountEntry entry = findByName(cleanName);
if (entry == null) {
entry = addAccount(cleanName, date, skin);
} else {
if (!isBlank(date)) {
entry.setDate(date);
}
if (skin != null) {
entry.setSkin(skin);
}
}
setActiveAccount(entry);
}
public void clearActiveAccount() {
activeAccountName.set("");
activeAccountDate.set("");
activeAccountSkin.set("");
reindexAccounts();
save();
}
public String getActiveAccountName() {
return activeAccountName.get();
}
public String getActiveAccountDate() {
return activeAccountDate.get();
}
public Identifier getActiveAccountSkin() {
return parseIdentifier(activeAccountSkin.get());
}
public boolean isMicrosoftAuthorizationRequired() {
return getMicrosoftAuthorizationRequiredAccount() != null;
}
public AccountEntry getMicrosoftAuthorizationRequiredAccount() {
if (isBlank(microsoftAuthorizationRequiredName)) {
return null;
}
AccountEntry entry = findByName(microsoftAuthorizationRequiredName);
return entry != null && entry.isMicrosoft() ? entry : null;
}
public void clearMicrosoftAuthorizationRequired() {
microsoftAuthorizationRequiredName = "";
}
public void save() {
reindexAccounts();
ConfigSerializer.requestSave(this);
}
@Override
public String getConfigName() {
return "accounts";
}
@Override
public List<ConfigValue<?>> getConfigValues() {
List<ConfigValue<?>> values = new ArrayList<>();
values.add(accounts);
values.add(activeAccountName);
values.add(activeAccountDate);
values.add(activeAccountSkin);
return values;
}
private void applyActiveSession() {
if (isBlank(activeAccountName.get())) {
return;
}
AccountEntry entry = findByName(activeAccountName.get());
if (entry != null) {
applySession(entry);
} else {
SessionChanger.changeUsername(activeAccountName.get());
}
}
private void applySession(AccountEntry entry) {
if (entry == null) {
return;
}
if (!entry.isMicrosoft()) {
clearAuthorizationRequired(entry.getName());
SessionChanger.changeUsername(entry.getName())
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to apply offline account session: " + entry.getName(), t);
return null;
});
return;
}
String refreshToken = entry.getMicrosoftRefreshToken();
if (isBlank(refreshToken)) {
if (SessionChanger.canUseOriginalLauncherSession(entry.getName(), entry.getOnlineUuid())) {
clearAuthorizationRequired(entry.getName());
SessionChanger.restoreOriginalLauncherSession(false)
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to restore launcher Microsoft session: " + entry.getName(), t);
markAuthorizationRequired(entry);
return null;
});
return;
}
markAuthorizationRequired(entry);
DebugLog.warnOnce("alt-microsoft-token-empty-" + entry.getName(), "[AccountConfig] Microsoft account requires authorization: %s", entry.getName());
return;
}
clearAuthorizationRequired(entry.getName());
MicrosoftAuthService.loginWithRefreshToken(refreshToken)
.thenCompose(session -> {
entry.applyMicrosoftSession(session);
activeAccountName.set(session.name());
activeAccountDate.set(entry.getDate() == null ? "" : entry.getDate());
save();
return SessionChanger.changeSession(session.toLoginData());
})
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to apply Microsoft account session: " + entry.getName(), t);
markAuthorizationRequired(entry);
return null;
});
}
private void markAuthorizationRequired(AccountEntry entry) {
microsoftAuthorizationRequiredName = entry == null ? "" : normalizeName(entry.getName());
}
private void clearAuthorizationRequired(String name) {
if (normalizeName(name).equalsIgnoreCase(normalizeName(microsoftAuthorizationRequiredName))) {
microsoftAuthorizationRequiredName = "";
}
}
private boolean isActive(AccountEntry entry) {
if (entry == null) {
return false;
}
return normalizeName(entry.getName()).equals(normalizeName(activeAccountName.get()));
}
private void reindexAccounts() {
List<AccountEntry> list = accounts.get();
for (int i = 0; i < list.size(); i++) {
list.get(i).setOriginalIndex(i);
}
}
private static final class AccountsValue extends ConfigValue<List<AccountEntry>> {
private AccountsValue(String name) {
super(name, new ArrayList<>());
}
private static String stringValue(Object value) {
if (value == null) {
return "";
}
return String.valueOf(value).trim();
}
private static boolean boolValue(Object value) {
if (value instanceof Boolean bool) {
return bool;
}
if (value instanceof String string) {
return Boolean.parseBoolean(string);
}
return false;
}
private static int intValue(Object value, int fallback) {
if (value instanceof Number number) {
return Math.max(0, number.intValue());
}
if (value instanceof String string) {
try {
return Math.max(0, Integer.parseInt(string.trim()));
} catch (NumberFormatException ignored) {
return fallback;
}
}
return fallback;
}
@Override
public Object toJson() {
List<Object> out = new ArrayList<>();
for (AccountEntry entry : value) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("name", entry.getName());
row.put("date", entry.getDate());
row.put("skin", entry.getSkin() == null ? "" : entry.getSkin().toString());
row.put("pinned", entry.isPinned());
row.put("originalIndex", entry.getOriginalIndex());
row.put("authType", entry.getAuthType().id());
row.put("onlineUuid", entry.getOnlineUuid() == null ? "" : entry.getOnlineUuid().toString());
row.put("microsoftRefreshToken", "");
out.add(row);
}
return out;
}
@Override
public void fromJson(Object json) {
List<AccountEntry> loaded = new ArrayList<>();
if (json instanceof Iterable<?> iterable) {
int fallbackIndex = 0;
for (Object item : iterable) {
if (!(item instanceof Map<?, ?> row)) {
continue;
}
String name = stringValue(row.get("name"));
if (name.isBlank()) {
continue;
}
String date = stringValue(row.get("date"));
Identifier skin = parseIdentifier(stringValue(row.get("skin")));
boolean pinned = boolValue(row.get("pinned"));
int originalIndex = intValue(row.get("originalIndex"), fallbackIndex);
AccountAuthType authType = AccountAuthType.byId(stringValue(row.get("authType")));
UUID onlineUuid = parseUuid(stringValue(row.get("onlineUuid")));
loaded.add(new AccountEntry(name, date, skin, pinned, originalIndex, authType, onlineUuid, ""));
fallbackIndex++;
}
}
loaded.sort(Comparator.comparingInt(AccountEntry::getOriginalIndex));
value = loaded;
}
}
}

View file

@ -0,0 +1,91 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import dev.loki.lovisual.util.session.MicrosoftSessionResult;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.resources.Identifier;
import java.util.UUID;
@Getter
public final class AccountEntry {
private String name;
private String date;
@Setter
private Identifier skin;
@Setter
private boolean pinned;
private int originalIndex;
private AccountAuthType authType;
@Setter
private UUID onlineUuid;
private String microsoftRefreshToken;
public AccountEntry(String name, String date, Identifier skin, boolean pinned, int originalIndex) {
this(name, date, skin, pinned, originalIndex, AccountAuthType.OFFLINE, null, "");
}
public AccountEntry(String name,
String date,
Identifier skin,
boolean pinned,
int originalIndex,
AccountAuthType authType,
UUID onlineUuid,
String microsoftRefreshToken) {
this.name = name == null ? "" : name;
this.date = date == null ? "" : date;
this.skin = skin;
this.pinned = pinned;
this.originalIndex = Math.max(0, originalIndex);
this.authType = authType == null ? AccountAuthType.OFFLINE : authType;
this.onlineUuid = onlineUuid;
this.microsoftRefreshToken = microsoftRefreshToken == null ? "" : microsoftRefreshToken;
}
public void setName(String name) {
this.name = name == null ? "" : name;
}
public void setDate(String date) {
this.date = date == null ? "" : date;
}
public void togglePinned() {
pinned = !pinned;
}
public void setOriginalIndex(int originalIndex) {
this.originalIndex = Math.max(0, originalIndex);
}
public void setAuthType(AccountAuthType authType) {
this.authType = authType == null ? AccountAuthType.OFFLINE : authType;
}
public boolean isMicrosoft() {
return authType == AccountAuthType.MICROSOFT;
}
public void setMicrosoftRefreshToken(String microsoftRefreshToken) {
this.microsoftRefreshToken = microsoftRefreshToken == null ? "" : microsoftRefreshToken;
}
public void applyMicrosoftSession(MicrosoftSessionResult session) {
if (session == null) {
return;
}
this.authType = AccountAuthType.MICROSOFT;
this.name = session.name();
this.onlineUuid = session.uuid();
this.microsoftRefreshToken = session.refreshToken();
}
}

View file

@ -0,0 +1,183 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.player.PlayerSkin;
import dev.loki.lovisual.util.player.PlayerSkinResolver;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public enum SkinManager {
;
private static final Map<String, Identifier> CACHE = new ConcurrentHashMap<>();
private static final Map<String, Boolean> LOADING = new ConcurrentHashMap<>();
private static final Executor EXECUTOR = Executors.newFixedThreadPool(3, runnable -> {
Thread thread = new Thread(runnable, "LoVisual-AltSkinLoader");
thread.setDaemon(true);
return thread;
});
public static Identifier getSkin(String playerName) {
String key = normalizeKey(playerName);
if (key.isEmpty()) {
return defaultSkin(playerName);
}
Identifier cached = CACHE.get(key);
if (cached != null) {
return cached;
}
if (LOADING.putIfAbsent(key, Boolean.TRUE) == null) {
CompletableFuture.runAsync(() -> loadSkin(playerName, key), EXECUTOR);
}
return defaultSkin(playerName);
}
public static void removeSkin(String playerName) {
String key = normalizeKey(playerName);
if (key.isEmpty()) {
return;
}
CACHE.remove(key);
LOADING.remove(key);
}
public static void reloadSkin(String playerName) {
removeSkin(playerName);
getSkin(playerName);
}
public static void clearCache() {
CACHE.clear();
LOADING.clear();
}
private static void loadSkin(String playerName, String key) {
try {
UUID uuid = fetchUuid(playerName);
if (uuid == null) {
return;
}
Minecraft client = Minecraft.getInstance();
if (client == null || client.getSkinManager() == null) {
return;
}
GameProfile profile = new GameProfile(uuid, playerName);
Supplier<PlayerSkin> supplier = client.getSkinManager().createLookup(profile, false);
if (supplier == null) {
return;
}
PlayerSkin textures = supplier.get();
Identifier skin = PlayerSkinResolver.resolveAssetId(textures == null ? null : textures.body());
if (skin != null) {
CACHE.put(key, skin);
}
} catch (Throwable ignored) {
} finally {
LOADING.remove(key);
}
}
private static UUID fetchUuid(String playerName) {
String cleanName = normalizeName(playerName);
if (cleanName.isEmpty()) {
return null;
}
try {
HttpURLConnection connection = (HttpURLConnection) URI
.create("https://api.mojang.com/users/profiles/minecraft/" + cleanName)
.toURL()
.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "LoVisual");
if (connection.getResponseCode() != 200) {
connection.disconnect();
return null;
}
try (InputStreamReader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
if (!json.has("id")) {
return null;
}
return parseUuid(json.get("id").getAsString());
} finally {
connection.disconnect();
}
} catch (Throwable ignored) {
return null;
}
}
private static UUID parseUuid(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String value = raw.trim();
if (value.length() == 32) {
value = value.substring(0, 8) + "-" + value.substring(8, 12) + "-" + value.substring(12, 16)
+ "-" + value.substring(16, 20) + "-" + value.substring(20);
}
try {
return UUID.fromString(value);
} catch (IllegalArgumentException ignored) {
return null;
}
}
private static Identifier defaultSkin(String playerName) {
String cleanName = normalizeName(playerName);
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + cleanName).getBytes(StandardCharsets.UTF_8));
GameProfile profile = new GameProfile(uuid, cleanName);
PlayerSkin textures = DefaultPlayerSkin.get(profile);
Identifier resolved = PlayerSkinResolver.resolveAssetId(textures == null ? null : textures.body());
if (resolved != null) {
return resolved;
}
return Identifier.fromNamespaceAndPath("minecraft", "textures/entity/player/wide/steve.png");
}
private static String normalizeKey(String playerName) {
String cleanName = normalizeName(playerName);
return cleanName.isEmpty() ? "" : cleanName.toLowerCase();
}
private static String normalizeName(String playerName) {
return playerName == null ? "" : playerName.trim();
}
}

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