diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..740324b1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +[*] +root = true +charset = utf-8 +end_of_line = crlf +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.gitignore b/.gitignore index 663293b0..b23279da 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,14 @@ +[Bb]uild/ +.vs/ +.vscode/ +*.zip +*.timestamp +deploy-*.ps1 + shaders/target_folder.txt tools/dxc_analysis_tools/dndxc.settings.xml + +Plugin/dist/Data/* +Plugin/dist/ASI/* +Plugin/dist/SFSE/* +Plugin/dist/*.exp diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..d25bdedf --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "extern/DKUtil"] + path = extern/DKUtil + url = https://github.com/gottyduke/DKUtil.git +[submodule "extern/SFSE"] + path = extern/SFSE + url = https://github.com/ianpatt/sfse.git diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..a5eae152 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + +The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/EXCEPTIONS b/EXCEPTIONS new file mode 100644 index 00000000..9ee58756 --- /dev/null +++ b/EXCEPTIONS @@ -0,0 +1,15 @@ +This Program is intended to be used with and modify existing code (the "Modded Code") and to build a robust modding community with open source principles. The purpose of this exception is to address issues when an open source modding community interacts with potentially proprietary code. In addition, the modding community often uses libraries (the "Modding Libraries") under licenses that may be incompatible with the GPL ("Modding Library Licenses"). + +=== + +Modding Exception + +In addition, as a special exception, the authors gives You the additional right to link the code of this Program with the existing code that this Program is intended to be used with or modify and to distribute linked combinations including the two, subject to the limitations in this paragraph. Modded Code permitted under this exception may link to the code of this Program without causing the Modded Code and portion of the combined work corresponding to the Modded Code to be covered by the GNU General Public License. You must obey the GNU General Public License in all respects for all of the Program code and other code used in conjunction with the Program except the Modded Code covered by this exception. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to provide this exception without modification, you must delete this exception statement from your version and license this file solely under the GPL without exception. + +=== + +GPL-3.0 Linking Exception (with Corresponding Source) + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it with Modding Libraries (or a modified version thereof), containing parts covered by the terms of Modding Library Licenses, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of Modding Libraries used as well as that of the covered work. diff --git a/Plugin/!update.ps1 b/Plugin/!update.ps1 new file mode 100644 index 00000000..1cbb5dfb --- /dev/null +++ b/Plugin/!update.ps1 @@ -0,0 +1,263 @@ +#Requires -Version 5 + +# args +param ( + [Parameter(Mandatory)][ValidateSet('SOURCEGEN', 'DISTRIBUTE')][string]$Mode = 'SOURCEGEN', + [string]$Version, + [string]$Path, + [string]$Payload +) + + +$ErrorActionPreference = "Stop" + +$Folder = $PSScriptRoot | Split-Path -Leaf +$SourceExt = @('.asm', '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx', 'inc', '.inl', '.ixx') +$ConfigExt = @('.ini', '.json', '.toml', '.xml') +$DocsExt = @('.md') + +function Normalize-Path { + param ( + [string]$in + ) + + $out = $in -replace '\\', '/' + while ($out.Contains('//')) { + $out = $out -replace '//', '/' + } + return $out +} + +function Resolve-Files { + param ( + [Parameter(ValueFromPipeline)][string]$parent = $PSScriptRoot, + [string[]]$range = @('include', 'src', 'test') + ) + + process { + Push-Location $PSScriptRoot + $_generated = [System.Collections.ArrayList]::new() + + try { + foreach ($directory in $range) { + if (!$env:RebuildInvoke) { + Write-Host "`t[$parent/$directory]" + } + + Get-ChildItem "$parent/$directory" -Recurse -File -ErrorAction SilentlyContinue | Where-Object { + ($_.Extension -in ($SourceExt + $DocsExt)) -and + ($_.Name -notmatch 'Plugin.h|Version.h') + } | Resolve-Path -Relative | ForEach-Object { + if (!$env:RebuildInvoke) { + Write-Host "`t`t<$_>" + } + $_generated.Add("`n`t`"$(Normalize-Path $_.Substring(2))`"") | Out-Null + } + } + + Get-ChildItem "$parent/dist" -Exclude "rules" | Get-ChildItem -File -Recurse -ErrorAction SilentlyContinue | Where-Object { + ($_.Extension -in ($ConfigExt + $DocsExt)) -and + ($_.Name -notmatch 'cmake|vcpkg') + } | Resolve-Path -Relative | ForEach-Object { + if (!$env:RebuildInvoke) { + Write-Host "`t`t<$_>" + } + $_generated.Add("`n`t`"$(Normalize-Path $_.Substring(2))`"") | Out-Null + } + } + finally { + Pop-Location + } + + return $_generated + } +} + + +Write-Host "`n`t<$Folder> [$Mode]" + + +# @@SOURCEGEN +if ($Mode.ToUpper() -eq 'SOURCEGEN') { + Write-Host "`tGenerating CMake sourcelist..." + Remove-Item "$Path/sourcelist.cmake" -Force -Confirm:$false -ErrorAction Ignore + + $generated = 'set(SOURCES' + $generated += $PSScriptRoot | Resolve-Files + if ($Path) { + $generated += $Path | Resolve-Files + } + $generated += "`n)" + [IO.File]::WriteAllText("$Path/sourcelist.cmake", $generated) +} + +$RuleVarTbl = @{ + config = 'debug'; + cmake_output = Normalize-Path ($Path + '/'); + dist = Normalize-Path "$PSScriptRoot/dist/"; + project_name = $Payload; + project_version = $Version; +} +$RuleCmds = @() + +function Resolve-RuleVar { + param ( + [string]$Path + ) + + $Path = $Path.Trim(' ') + $any = [regex]::Matches($Path, '\{.*?\}').Value + $Resolved = $Path + + # env: + foreach ($unset in $any) { + $inner = $unset.Trim('{', '}') + if ($inner.StartsWith('env:')) { + $Resolved = $Resolved -replace $unset, [System.Environment]::GetEnvironmentVariable($inner.TrimStart('env:')) + } + else { + $Resolved = if ($script:RuleVarTbl.Contains($inner)) { + $Resolved -replace $unset, $script:RuleVarTbl[$inner] + } + else { + $Resolved -replace $unset, $inner + } + } + } + + return Normalize-Path $Resolved.Trim('{', '}') +} + +function Resolve-Rules { + param ( + [Object]$Deployee + ) + + switch ($Deployee.action) { + "base" { + $script:RuleVarTbl[($Deployee.params[0].Trim('{', '}'))] = Resolve-RuleVar $Deployee.params[1] + #"setting $($Deployee.params[0]) to $(Resolve-RuleVar $Deployee.params[1])" + break + } + "copy" { + $source = $(Resolve-RuleVar $Deployee.params[0]) + $destination = $(Resolve-RuleVar $Deployee.params[1]) + $dest_path = $destination.Substring(0, $destination.LastIndexOf('/') + 1) + $script:RuleCmds += "New-Item `'$dest_path`' -ItemType Directory -Force -ErrorAction:SilentlyContinue" + $script:RuleCmds += "Copy-Item `'$source`' `'$destination`' -Force -Recurse -ErrorAction:SilentlyContinue" + break + } + "copy_if" { + $source = $(Resolve-RuleVar $Deployee.params[0]) + $destination = $(Resolve-RuleVar $Deployee.params[1]) + $dest_path = $destination.Substring(0, $destination.LastIndexOf('/') + 1) + $script:RuleCmds += "if (Test-Path `'$source`') {" + $script:RuleCmds += "New-Item `'$dest_path`' -ItemType Directory -Force -ErrorAction:SilentlyContinue" + $script:RuleCmds += "Copy-Item `'$source`' `'$destination`' -Force -Recurse -ErrorAction:SilentlyContinue }" + break + } + "package" { + $source_tree = @() + foreach ($source in $Deployee.params[0..($Deployee.params.Length - 2)]) { + $source_tree += , "`'$(Resolve-RuleVar $source)`'" + } + $script:RuleCmds += "Compress-Archive -Path $($source_tree -join ',') -DestinationPath `'$(Resolve-RuleVar $Deployee.params[-1])`' -Force -ErrorAction:SilentlyContinue" + break + } + "remove" { + foreach ($to_remove in $Deployee.params) { + $script:RuleCmds += "Remove-Item `'$(Resolve-RuleVar $to_remove)`' -Force -Recurse -ErrorAction:SilentlyContinue" + } + break + } + "script" { + foreach ($raw_script in $Deployee.params) { + $script:RuleCmds += $raw_script + } + break + } + default { + break + } + } +} + + +# @@DISTRIBUTE +if ($Mode.ToUpper() -eq 'DISTRIBUTE') { + if ($Version.ToUpper() -eq '-1') { + # update script to every project + Get-ChildItem "$PSScriptRoot/$Path" -Directory -Recurse | Where-Object { + $_.Name -notin @('vcpkg', 'build', '.git', '.vs') -and + (Test-Path "$_/CMakeLists.txt" -PathType Leaf) -and + (Test-Path "$_/vcpkg.json" -PathType Leaf) + } | ForEach-Object { + Write-Host "`tUpdated <$_>" + Robocopy.exe "$PSScriptRoot" "$_" '!Update.ps1' /MT /NJS /NFL /NDL /NJH | Out-Null + } + exit + } + + $Path = Normalize-Path $Path + $RuleVarTbl.config = $Path.Split('/')[-1].ToLower() + + $rules = Get-ChildItem "$($RuleVarTbl.dist)/rules" -File *.json + $rule_timestamp = @( "!update : $((Get-Item $MyInvocation.MyCommand.Path).LastWriteTime.Ticks)" ) + + # generate timestamp & distribution step + foreach ($rule in $rules) { + $rule_timestamp += , "$($rule.BaseName) : $($rule.LastWriteTime.Ticks)" + } + + $regenerate = $true + $timestamp = "$($RuleVarTbl.dist)/rules/$($RuleVarTbl.project_version).timestamp" + Write-Host "`tChecking deploy rules..." + + if (Test-Path "$($RuleVarTbl.dist)/deploy.ps1") { + $rule_timestamp += , "deployer : $((Get-Item "$($RuleVarTbl.dist)/deploy.ps1").LastWriteTime.Ticks)" + } + + if (Test-Path $timestamp) { + $old_timestamp = [IO.File]::ReadAllText($timestamp) + + if ($old_timestamp -eq ($rule_timestamp | Out-String)) { + $regenerate = $false + Write-Host "`t...No changes" + } + else { + Write-Host "`t...Pending changes" + } + } + + # parse all rules + if ($regenerate) { + Write-Host "`tRegenerating deploy rules..." + + foreach ($rule in $rules) { + $deployer = [IO.File]::ReadAllText($rule.FullName) | ConvertFrom-Json + + foreach ($deployee in $deployer) { + if (("config" -in $deployee.PSObject.Properties.Name) -and ($deployee.config -ne $RuleVarTbl.config)) { + continue + } + else { + Resolve-Rules $deployee + } + } + } + + $RuleCmds | Out-File "$($RuleVarTbl.dist)/deploy-$($RuleVarTbl.config.ToLower()).ps1" utf8 + + $rule_timestamp[-1] = "deployer : $((Get-Item "$($RuleVarTbl.dist)/deploy-$($RuleVarTbl.config.ToLower()).ps1").LastWriteTime.Ticks)" + Remove-Item "$($RuleVarTbl.dist)/rules/*.timestamp" -Force -ErrorAction:SilentlyContinue | Out-Null + $rule_timestamp | Out-File $timestamp utf8 + + Write-Host "`t...Ok" + } + + # deploy + Write-Host "`tExecuting deploy rules..." + & "$($RuleVarTbl.dist)/deploy-$($RuleVarTbl.config.ToLower()).ps1" + + Write-Host "`t...Ok" +} diff --git a/Plugin/.clang-format b/Plugin/.clang-format new file mode 100644 index 00000000..e7031d45 --- /dev/null +++ b/Plugin/.clang-format @@ -0,0 +1,97 @@ +--- +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignConsecutiveAssignments: false +AlignConsecutiveBitFields: false +AlignConsecutiveDeclarations: true +AlignConsecutiveMacros: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: After +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeTernaryOperators: false +BreakConstructorInitializers: AfterColon +BreakInheritanceList: AfterColon +BreakStringLiterals: true +ColumnLimit: 0 +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +FixNamespaceComments: false +IncludeBlocks: Preserve +IndentCaseBlocks: true +IndentCaseLabels: false +IndentExternBlock: Indent +IndentGotoLabels: false +IndentPPDirectives: AfterHash +IndentWidth: 4 +IndentWrappedFunctionNames: true +KeepEmptyLinesAtTheStartOfBlocks: false +Language: Cpp +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +PointerAlignment: Left +ReflowComments: false +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Latest +TabWidth: 4 +UseTab: AlignWithSpaces +LineEnding: CRLF +PackConstructorInitializers: BinPack diff --git a/Plugin/CMakeLists.txt b/Plugin/CMakeLists.txt new file mode 100644 index 00000000..1a5c6b98 --- /dev/null +++ b/Plugin/CMakeLists.txt @@ -0,0 +1,144 @@ +cmake_minimum_required(VERSION 3.21) + +# info +project( + Luma + VERSION 0.3.0 + LANGUAGES CXX +) + +# boiler +include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/common.cmake) + +# in-place configuration +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Plugin.h.in + ${CMAKE_CURRENT_BINARY_DIR}/include/Plugin.h + @ONLY +) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/version.rc.in + ${CMAKE_CURRENT_BINARY_DIR}/version.rc + @ONLY +) + +# source files +execute_process(COMMAND powershell -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/!update.ps1" "SOURCEGEN" "${PROJECT_VERSION}" "${CMAKE_CURRENT_BINARY_DIR}") +include(${CMAKE_CURRENT_BINARY_DIR}/sourcelist.cmake) +source_group( + TREE ${CMAKE_CURRENT_SOURCE_DIR} + FILES ${SOURCES} +) + +source_group( + TREE ${CMAKE_CURRENT_BINARY_DIR} + FILES ${CMAKE_CURRENT_BINARY_DIR}/include/Plugin.h +) + +# dependencies +find_package(spdlog CONFIG REQUIRED) +find_dependency_path(DKUtil include/DKUtil/Logger.hpp) +find_dependency_path(SFSE sfse/sfse.cpp) + +# +target_compile_options( + sfse + PRIVATE + /WX- +) +target_compile_options( + sfse_common + PRIVATE + /WX- +) + +# cmake target +# runtime +add_library( + ${PROJECT_NAME} + SHARED + ${SOURCES} + ${CMAKE_CURRENT_BINARY_DIR}/include/Plugin.h + ${CMAKE_CURRENT_BINARY_DIR}/version.rc + .clang-format + vcpkg.json +) + +# include dir +target_include_directories( + ${PROJECT_NAME} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/src +) + +# linkage +target_link_libraries( + ${PROJECT_NAME} + PRIVATE + DKUtil::DKUtil + sfse::sfse_common + spdlog::spdlog +) + +# compiler def +if (MSVC) + add_compile_definitions(_UNICODE) + + target_compile_options( + ${PROJECT_NAME} + PRIVATE + /MP + /await + /W0 + /WX + /permissive- + /utf-8 + /Zc:alignedNew + /Zc:auto + /Zc:__cplusplus + /Zc:externC + /Zc:externConstexpr + /Zc:forScope + /Zc:hiddenFriend + /Zc:implicitNoexcept + /Zc:lambda + /Zc:noexceptTypes + /Zc:preprocessor + /Zc:referenceBinding + /Zc:rvalueCast + /Zc:sizedDealloc + /Zc:strictStrings + /Zc:ternary + /Zc:threadSafeInit + /Zc:trigraphs + /Zc:wchar_t + /wd4200 # nonstandard extension used : zero-sized array in struct/union + /FI${CMAKE_BINARY_DIR}/CMakeFiles/${PROJECT_NAME}.dir/$/cmake_pch.hxx + ) +endif() + +# PCH +target_precompile_headers( + ${PROJECT_NAME} + PRIVATE + src/PCH.h +) + +set_property( + TARGET + ${PROJECT_NAME} + PROPERTY VS_USER_PROPS + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/build_stl_modules.props" +) + +# update deployments +add_custom_command( + TARGET + ${PROJECT_NAME} + POST_BUILD + COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File + "${CMAKE_CURRENT_SOURCE_DIR}/!update.ps1" "DISTRIBUTE" "${PROJECT_VERSION}" "${CMAKE_CURRENT_BINARY_DIR}/$(ConfigurationName)" "${PROJECT_NAME}" +) diff --git a/Plugin/CMakePresets.json b/Plugin/CMakePresets.json new file mode 100644 index 00000000..eb9bcffe --- /dev/null +++ b/Plugin/CMakePresets.json @@ -0,0 +1,230 @@ +{ + "version": 6, + "cmakeMinimumRequired": { + "major": 3, + "minor": 26, + "patch": 0 + }, + "configurePresets": [ + { + "name": "common", + "hidden": true, + "cacheVariables": { + "CMAKE_CXX_FLAGS": "$env{PROJECT_PLATFORM_FLAGS} $env{PROJECT_TEXT_FLAGS} $env{PROJECT_COMPILER_FLAGS} $penv{CXXFLAGS}", + "SFSE_SUPPORT_XBYAK": "ON" + }, + "vendor": { + "microsoft.com/VisualStudioSettings/CMake/1.0": { + "intelliSenseMode": "windows-msvc-x64", + "enableMicrosoftCodeAnalysis": true, + "enableClangTidyCodeAnalysis": true + } + } + }, + { + "name": "packaging-vcpkg", + "hidden": true, + "cacheVariables": { + "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake", + "VCPKG_HOST_TRIPLET": "x64-windows-static-md", + "VCPKG_TARGET_TRIPLET": "x64-windows-static-md" + } + }, + { + "name": "buildtype-debug", + "hidden": true, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "buildtype-release", + "hidden": true, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + }, + { + "name": "x64", + "hidden": true, + "architecture": "x64", + "cacheVariables": { + "CMAKE_MSVC_RUNTIME_LIBRARY": "MultiThreaded$<$:Debug>DLL" + } + }, + { + "name": "generator-msvc", + "hidden": true, + "inherits": "x64", + "generator": "Visual Studio 17 2022" + }, + { + "name": "generator-ninja", + "hidden": true, + "generator": "Ninja" + }, + { + "name": "compiler-msvc", + "hidden": true, + "environment": { + "PROJECT_COMPILER_FLAGS": "/cgthreads8 /diagnostics:caret /fp:contract /fp:except- /guard:cf- /permissive- /Zc:__cplusplus /Zc:lambda /Zc:preprocessor /Zc:referenceBinding /Zc:rvalueCast /Zc:templateScope /Zc:ternary /Zc:preprocessor /EHsc /MP /W4 /external:anglebrackets /external:W0", + "PROJECT_COMPILER": "msvc" + } + }, + { + "name": "compiler-clang", + "hidden": true, + "cacheVariables": { + "CMAKE_C_COMPILER": "clang", + "CMAKE_CXX_COMPILER": "clang++" + }, + "environment": { + "PROJECT_COMPILER": "clang", + "PROJECT_COMPILER_FLAGS": "-Wno-overloaded-virtual -Wno-delete-non-abstract-non-virtual-dtor -Wno-inconsistent-missing-override -Wno-reinterpret-base-class" + }, + "vendor": { + "microsoft.com/VisualStudioSettings/CMake/1.0": { + "intelliSenseMode": "windows-clang-x64" + } + } + }, + { + "name": "compiler-clang-cl", + "hidden": true, + "inherits": "compiler-clang", + "cacheVariables": { + "CMAKE_C_COMPILER": "clang-cl", + "CMAKE_CXX_COMPILER": "clang-cl" + }, + "environment": { + "CC": "clang-cl", + "CXX": "clang-cl", + "PROJECT_COMPILER_FLAGS": "/permissive- /EHsc /W4 -Wno-overloaded-virtual -Wno-delete-non-abstract-non-virtual-dtor -Wno-inconsistent-missing-override -Wno-reinterpret-base-class -D__cpp_consteval" + } + }, + { + "name": "build-debug-msvc-msvc", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-debug", + "generator-msvc", + "compiler-msvc" + ] + }, + { + "name": "build-debug-msvc-ninja", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-debug", + "generator-ninja", + "compiler-msvc" + ] + }, + { + "name": "build-debug-clang-cl-msvc", + "toolset": "ClangCL", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-debug", + "generator-msvc", + "compiler-clang-cl" + ] + }, + { + "name": "build-debug-clang-cl-ninja", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-debug", + "generator-ninja", + "compiler-clang-cl" + ] + }, + { + "name": "build-release-msvc-msvc", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-release", + "generator-msvc", + "compiler-msvc" + ] + }, + { + "name": "build-release-msvc-ninja", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-release", + "generator-ninja", + "compiler-msvc" + ] + }, + { + "name": "build-release-clang-cl-msvc", + "toolset": "ClangCL", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-release", + "generator-msvc", + "compiler-clang-cl" + ] + }, + { + "name": "build-release-clang-cl-ninja", + "inherits": [ + "common", + "packaging-vcpkg", + "buildtype-release", + "generator-ninja", + "compiler-clang-cl" + ] + } + ], + "buildPresets": [ + { + "name": "debug-msvc-ninja", + "configurePreset": "build-debug-msvc-ninja", + "displayName": "1. (Debug) MSVC - Ninja" + }, + { + "name": "release-msvc-ninja", + "configurePreset": "build-release-msvc-ninja", + "displayName": "2. (Release) MSVC - Ninja" + }, + { + "name": "debug-msvc-msvc", + "configurePreset": "build-debug-msvc-msvc", + "displayName": "3. (Debug) MSVC - MSVC" + }, + { + "name": "release-msvc-msvc", + "configurePreset": "build-release-msvc-msvc", + "displayName": "4. (Release) MSVC - MSVC" + }, + { + "name": "debug-clang-cl-ninja", + "configurePreset": "build-debug-clang-cl-ninja", + "displayName": "5. (Debug) Clang - Ninja" + }, + { + "name": "release-clang-cl-ninja", + "configurePreset": "build-release-clang-cl-ninja", + "displayName": "6. (Release) Clang - Ninja" + }, + { + "name": "debug-clang-cl-msvc", + "configurePreset": "build-debug-clang-cl-msvc", + "displayName": "7. (Debug) Clang - MSVC" + }, + { + "name": "release-clang-cl-msvc", + "configurePreset": "build-release-clang-cl-msvc", + "displayName": "8. (Release) Clang - MSVC" + } + ] +} \ No newline at end of file diff --git a/Plugin/cmake/Plugin.h.in b/Plugin/cmake/Plugin.h.in new file mode 100644 index 00000000..c0de7ad0 --- /dev/null +++ b/Plugin/cmake/Plugin.h.in @@ -0,0 +1,12 @@ +#pragma once + + +namespace Plugin +{ + inline constexpr auto NAME = "@PROJECT_NAME@"sv; + inline constexpr auto AUTHOR = "@PluginAuthor@"sv; + inline constexpr auto Version = + @PROJECT_VERSION_MAJOR@u * 10000 + + @PROJECT_VERSION_MINOR@u * 100 + + @PROJECT_VERSION_PATCH@u; +} diff --git a/Plugin/cmake/build_stl_modules.props b/Plugin/cmake/build_stl_modules.props new file mode 100644 index 00000000..a8184de9 --- /dev/null +++ b/Plugin/cmake/build_stl_modules.props @@ -0,0 +1,8 @@ + + + + + false + + + \ No newline at end of file diff --git a/Plugin/cmake/common.cmake b/Plugin/cmake/common.cmake new file mode 100644 index 00000000..22ece508 --- /dev/null +++ b/Plugin/cmake/common.cmake @@ -0,0 +1,44 @@ +# dependency macros +macro(find_dependency_path DEPENDENCY FILE) + # searches extern for dependencies and if not checks the environment variable + if(NOT ${DEPENDENCY} STREQUAL "") + # Check extern + message( + STATUS + "Searching for ${DEPENDENCY} using file ${FILE}" + ) + find_path("${DEPENDENCY}Path" + ${FILE} + PATHS "${CMAKE_CURRENT_SOURCE_DIR}/../extern/${DEPENDENCY}") + + if("${${DEPENDENCY}Path}" STREQUAL "${DEPENDENCY}Path-NOTFOUND") + # Check path + message( + STATUS + "Getting environment for ${DEPENDENCY}Path: $ENV{${DEPENDENCY}Path}" + ) + set("${DEPENDENCY}Path" "$ENV{${DEPENDENCY}Path}") + endif() + + message( + STATUS + "Found ${DEPENDENCY} in ${${DEPENDENCY}Path}; adding" + ) + add_subdirectory("${${DEPENDENCY}Path}" ${DEPENDENCY}) + endif() +endmacro() + + +# standards & flags +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON) +set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_DEBUG OFF) +set_property(GLOBAL PROPERTY USE_FOLDERS ON) +set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE FILEPATH "") + + +# out-of-source builds only +if(${PROJECT_SOURCE_DIR} STREQUAL ${PROJECT_BINARY_DIR}) + message(FATAL_ERROR "In-source builds are not allowed.") +endif() diff --git a/Plugin/cmake/version.rc.in b/Plugin/cmake/version.rc.in new file mode 100644 index 00000000..82de531b --- /dev/null +++ b/Plugin/cmake/version.rc.in @@ -0,0 +1,31 @@ +#include + +1 VERSIONINFO + FILEVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, 0 + PRODUCTVERSION @PROJECT_VERSION_MAJOR@, @PROJECT_VERSION_MINOR@, @PROJECT_VERSION_PATCH@, 0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "@PROJECT_NAME@" + VALUE "FileVersion", "@PROJECT_VERSION@.0" + VALUE "InternalName", "@PROJECT_NAME@" + VALUE "ProductName", "@PROJECT_NAME@" + VALUE "ProductVersion", "@PROJECT_VERSION@.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END diff --git a/Plugin/dist/Luma.toml b/Plugin/dist/Luma.toml new file mode 100644 index 00000000..2bd80726 --- /dev/null +++ b/Plugin/dist/Luma.toml @@ -0,0 +1,42 @@ +[Dev] +ForceSDROnHDR = false +DevSetting01 = 0.0 +DevSetting02 = 0.0 +DevSetting03 = 0.0 +DevSetting04 = 0.0 +DevSetting05 = 0.0 + +[HDR] +Contrast = 50.0 +GamePaperWhite = 200 +PeakBrightness = 1000 +PeakBrightnessAutoDetected = false +ExtendGamut = 50.0 +Saturation = 50.0 +UIPaperWhite = 200 + +[Main] +ColorGradingStrength = 100.0 +DisplayMode = 0 +FilmGrainType = 1 +FilmGrainCap = 24.0 +GammaCorrectionStrength = 100.0 +LUTCorrectionStrength = 100.0 +PostSharpen = true +SecondaryBrightness = 50.0 +VanillaMenuLUTs = true + +[RenderTargets] +RenderTargetsToUpgrade = [ + 'ImageSpaceBuffer', + 'ScaleformCompositeBuffer', + 'SF_ColorBuffer', + 'HDRImagespaceBuffer', + 'ImageSpaceHalfResBuffer', + 'ImageProcessColorTarget', + 'ImageSpaceBufferB10G11R11', + 'ImageSpaceBufferE5B9G9R9', + 'TAA_idTech7HistoryColorTarget', + 'EnvBRDF', + 'ImageSpaceBufferR10G10B10A2' +] \ No newline at end of file diff --git a/Plugin/dist/ReadMe.txt b/Plugin/dist/ReadMe.txt new file mode 100644 index 00000000..7ab93de0 --- /dev/null +++ b/Plugin/dist/ReadMe.txt @@ -0,0 +1,40 @@ +This mod was created by 5 (HDR passionate) developers (Ersh, Pumbo (Filoppi / Filippo T.), Lilium, Nukem and ShortFuse), whom all took on different roles to achieve a large refactor of the game post processing phase. +The main thing the mod does is adding Native HDR support to the game, which is not the same as the one seen on Xbox, this version changes the game tonemapper and color correction phase to give a much more HDR look, while also trying to retaining the look and feel of the vanilla game. This was achieved by replacing the game shaders. +This mod also improves the look of the game in SDR, so benefits are not restricted to HDR users. +This is a follow up to https://www.nexusmods.com/starfield/mods/588, which just increased the quality of the game buffers to 10bit+, leaving more room for AutoHDR to work. +Join our discord here: https://discord.gg/DNGfMZgH3f + +List of features: +-Native HDR (scRGB and HDR10) +-Increased buffers accuracy in SDR and HDR, which reduced banding all around (SDR is now 10bit instead of 8bit) +-Normalized LUTs, the grey/flat look is mostly gone, but the color tint is still there (this mod includes a runtime version of https://www.nexusmods.com/starfield/mods/2407) +-Fixed bink fullscreen videos playing back with the wrong colors (BT.601 instead of BT.709) +-Improved the sharpening passes +-Improved film grain to be more realistic and nice to look at (e.g. rebalancing the grain size and strength on white/black colors) +-Fixed the game using very wrong gamma formulas +-Customization settings for you to personalize the game visuals + +How to use: +Drop the content of the mod into the game root folder, or install it with a mod manager in the game root folder. +The game needs to be started through the SFSE loader on Steam and ASI loader on Microsoft Store (Game Pass). +You can configure the mod from the game graphics setting menu. It also hooks to ReShade if you have installed, you will see the settings menu as a small ReShade widget. +There's also a config file in the dll folders, delete it to reset settings. +To uninstall, clear all the files (they are unique to the mod). + +Compatibility: +This mod should work with any other mod, including DLSS Super Resolution and DLSS Frame Generation (scRGB is NOT supported by FG). +You can also use customized LUTs mods, but if you do, make sure to disable "LUTs Correction" in the mods settings, or they will be corrected twice. +Our suggestion is to use the LUT correction that is built in with the mod, as our LUTs correction code extracts HDR detail when normalizing them, something that could not be otherwise achieved. +Additionally this mod should be compatible with any story content and new location, whether official added by Bethesda as DLCs, or unofficial mods. +You do NOT need any other HDR related mod, like AutoHDR, or "HUD for HDR" (which dimmed the UI for AutoHDR). + +Issues and limitations: +-The UI blends in slightly differently in HDR, usually it's not noticeable +-scRGB HDR doesn't work with DLSS Frame Generation (ping Nvidia about that) +-You can not take screenshots directly from Starfield in photo mode + +Comparison with other "HDR" methods: +-Starfield Xbox HDR: Starfield on Xbox uses an integrated for of AutoHDR, the output image in HDR is extracted from an SDR one, thus its visual quality is still bottlenecked by that. +-Windows 11 AutoHDR: Windows 11 can apply a post process AutoHDR filter, but this is still limited by 8bits output (causing banding), interprets games as gamma sRGB instead of 2.2, and doesn't go anywhere beyond 1000 nits. Additionally, it makes the game UI too bright. +-SpecialK HDR Retrofit: It can upgrade all buffers to 16bit but the game tonemapping remains SDR, and highlights gets mushed together and clipped. +-Pumbo's Advanced Auto HDR + DXVK: Same problems as SpecialK HDR. \ No newline at end of file diff --git a/Plugin/dist/SFShaderInjector.asi b/Plugin/dist/SFShaderInjector.asi new file mode 100644 index 00000000..d67a7209 Binary files /dev/null and b/Plugin/dist/SFShaderInjector.asi differ diff --git a/Plugin/dist/SFShaderInjector.dll b/Plugin/dist/SFShaderInjector.dll new file mode 100644 index 00000000..cc1c0d1f Binary files /dev/null and b/Plugin/dist/SFShaderInjector.dll differ diff --git a/Plugin/dist/rules/!base.json b/Plugin/dist/rules/!base.json new file mode 100644 index 00000000..dafe05d4 --- /dev/null +++ b/Plugin/dist/rules/!base.json @@ -0,0 +1,16 @@ +[ + { + "action": "base", + "params": [ + "{target_base}", + "{env:SFPath}\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "copy", + "params": [ + "{cmake_output}\\*", + "{dist}\\" + ] + } +] \ No newline at end of file diff --git a/Plugin/dist/rules/bin_copy.json b/Plugin/dist/rules/bin_copy.json new file mode 100644 index 00000000..a78daf1e --- /dev/null +++ b/Plugin/dist/rules/bin_copy.json @@ -0,0 +1,16 @@ +[ + { + "action": "copy", + "params": [ + "{dist}\\*.dll", + "{target_base}" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.pdb", + "{target_base}" + ] + } +] \ No newline at end of file diff --git a/Plugin/dist/rules/config_copy.json b/Plugin/dist/rules/config_copy.json new file mode 100644 index 00000000..16e0de00 --- /dev/null +++ b/Plugin/dist/rules/config_copy.json @@ -0,0 +1,23 @@ +[ + { + "action": "copy_if", + "params": [ + "{dist}\\*.ini", + "{target_base}" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.toml", + "{target_base}" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.json", + "{target_base}" + ] + } +] \ No newline at end of file diff --git a/Plugin/dist/rules/publish_asI_package.json b/Plugin/dist/rules/publish_asI_package.json new file mode 100644 index 00000000..ca70328d --- /dev/null +++ b/Plugin/dist/rules/publish_asI_package.json @@ -0,0 +1,75 @@ +[ + { + "action": "copy", + "params": [ + "{dist}\\{project_name}.dll", + "{dist}\\ASI\\{project_name}.asi" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\SFShaderInjector.asi", + "{dist}\\ASI\\SFShaderInjector.asi" + ] + }, + { + "action": "copy", + "params": [ + "{dist}\\Data\\", + "{dist}\\ASI\\" + ] + }, + { + "action": "copy_if", + "config": "RelWithDebInfo", + "params": [ + "{dist}\\*.pdb", + "{dist}\\ASI\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.txt", + "{dist}\\ASI\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.ini", + "{dist}\\ASI\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.toml", + "{dist}\\ASI\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.json", + "{dist}\\ASI\\" + ] + }, + { + "action": "package", + "config": "Release", + "params": [ + "{dist}\\ASI\\*", + "{dist}\\{project_name}-v{project_version}-ASI.zip" + ] + }, + { + "action": "package", + "config": "RelWithDebInfo", + "params": [ + "{dist}\\ASI\\*", + "{dist}\\{project_name}-v{project_version}-ASI.zip" + ] + } +] \ No newline at end of file diff --git a/Plugin/dist/rules/publish_sfse_package.json b/Plugin/dist/rules/publish_sfse_package.json new file mode 100644 index 00000000..3d90c8be --- /dev/null +++ b/Plugin/dist/rules/publish_sfse_package.json @@ -0,0 +1,68 @@ +[ + { + "action": "copy", + "params": [ + "{dist}\\*.dll", + "{dist}\\SFSE\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "copy", + "params": [ + "{dist}\\Data\\", + "{dist}\\SFSE\\" + ] + }, + { + "action": "copy_if", + "config": "RelWithDebInfo", + "params": [ + "{dist}\\*.pdb", + "{dist}\\SFSE\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.txt", + "{dist}\\SFSE\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.ini", + "{dist}\\SFSE\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.toml", + "{dist}\\SFSE\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "copy_if", + "params": [ + "{dist}\\*.json", + "{dist}\\SFSE\\Data\\SFSE\\Plugins\\" + ] + }, + { + "action": "package", + "config": "Release", + "params": [ + "{dist}\\SFSE\\*", + "{dist}\\{project_name}-v{project_version}-SFSE.zip" + ] + }, + { + "action": "package", + "config": "RelWithDebInfo", + "params": [ + "{dist}\\SFSE\\*", + "{dist}\\{project_name}-v{project_version}-SFSE.zip" + ] + } +] \ No newline at end of file diff --git a/Plugin/include/SFSE/Stub.h b/Plugin/include/SFSE/Stub.h new file mode 100644 index 00000000..d80e54b7 --- /dev/null +++ b/Plugin/include/SFSE/Stub.h @@ -0,0 +1,277 @@ +#pragma once + +#include "DKUtil/Hook.hpp" +#include "sfse/PluginAPI.h" +#include "sfse_common/sfse_version.h" + +// interface +namespace SFSE +{ + namespace detail + { + inline static SFSEInterface* load_storage = nullptr; + inline static SFSEMessagingInterface* messaging_storage = nullptr; + inline static SFSETrampolineInterface* trampoline_storage = nullptr; + } // namespace detail + + class LoadInterface : public dku::model::Singleton + { + public: + enum + { + kVersion = 1, + }; + + enum : std::uint32_t + { + kInvalid = 0, + kMessaging, + kTrampoline, + + kTotal, + }; + + [[nodiscard]] constexpr auto RuntimeVersion() const { return GetProxy()->runtimeVersion; } + [[nodiscard]] constexpr auto SFSEVersion() const { return GetProxy()->sfseVersion; } + [[nodiscard]] constexpr auto GetPluginHandle() const { return handle; }; + [[nodiscard]] constexpr const auto* GetPluginInfo(const char* a_name) const { return GetProxy()->GetPluginInfo(a_name); } + template + [[nodiscard]] constexpr T* QueryInterface(std::uint32_t a_id) const + { + return std::bit_cast(GetProxy()->QueryInterface(a_id)); + }; + + PluginHandle handle = static_cast(-1); + + protected: + constexpr const SFSEInterface* const GetProxy() const + { + return detail::load_storage; + } + }; + + class MessagingInterface : public dku::model::Singleton + { + public: + enum + { + kVersion = 1, + }; + + struct Message + { + const char* sender; + std::uint32_t type; + std::uint32_t dataLen; + void* data; + }; + using EventCallback = std::add_pointer_t; + + enum : std::uint32_t + { + kPostLoad, // sent to registered plugins once all plugins have been loaded (no data) + kPostPostLoad, // sent right after kPostPostLoad to facilitate the correct dispatching/registering of messages/listeners + }; + + constexpr bool Dispatch(std::uint32_t a_messageType, void* a_data, std::uint32_t a_dataLength, std::string_view a_receiver) const + { + auto success = GetProxy()->Dispatch(LoadInterface::GetSingleton()->GetPluginHandle(), a_messageType, a_data, a_dataLength, a_receiver.data()); + if (!success) { + FATAL( + "failed to dispatch message!\nexpected receiver : {}\n" + "message {{\ntype : {}\nlength : {}}}", + a_receiver, a_messageType, a_dataLength); + } + + return success; + } + + constexpr bool RegisterListener(std::string_view a_sender, EventCallback a_callback) const + { + auto success = GetProxy()->RegisterListener(LoadInterface::GetSingleton()->GetPluginHandle(), a_sender.data(), std::bit_cast(a_callback)); + if (!success) { + FATAL("failed to register messaging listener!\nexpected sender : {}\nmessage handler : {}.{:X}", + a_sender, Plugin::NAME, AsAddress(a_callback)); + } + + return success; + } + + constexpr bool RegisterListener(EventCallback a_callback) const + { + return RegisterListener("SFSE"sv, a_callback); + } + + protected: + constexpr const SFSEMessagingInterface* const GetProxy() const + { + return detail::messaging_storage; + } + }; + + class TrampolineInterface : public dku::model::Singleton + { + public: + enum + { + kVersion = 1, + }; + + [[nodiscard]] constexpr void* AllocateFromBranchPool(std::size_t a_size) const + { + return GetProxy()->AllocateFromBranchPool(LoadInterface::GetSingleton()->GetPluginHandle(), a_size); + } + + [[nodiscard]] constexpr void* AllocateFromLocalPool(std::size_t a_size) const + { + return GetProxy()->AllocateFromLocalPool(LoadInterface::GetSingleton()->GetPluginHandle(), a_size); + } + + protected: + constexpr const SFSETrampolineInterface* const GetProxy() const + { + return detail::trampoline_storage; + } + }; +} // namespace SFSE + +// stubs +namespace SFSE +{ + inline void Init(SFSEInterface* a_intfc) noexcept + { + if (!a_intfc) { + FATAL("SFSEInterface is null"sv); + } + + auto* storage = SFSE::LoadInterface::GetSingleton(); + + detail::load_storage = std::launder(a_intfc); + detail::messaging_storage = std::launder(storage->QueryInterface(LoadInterface::kMessaging)); + detail::trampoline_storage = std::launder(storage->QueryInterface(LoadInterface::kTrampoline)); + + storage->handle = detail::load_storage->GetPluginHandle(); + } + + [[nodiscard]] inline constexpr const auto* GetLoadInterface() noexcept { return SFSE::LoadInterface::GetSingleton(); } + [[nodiscard]] inline constexpr const auto* GetMessagingInterface() noexcept + { + return MessagingInterface::GetSingleton(); + } + [[nodiscard]] inline constexpr const auto* GetTrampolineInterface() noexcept + { + return TrampolineInterface::GetSingleton(); + } + + [[nodiscard]] inline auto& GetTrampoline() noexcept { return DKUtil::Hook::Trampoline::GetTrampoline(); } + + // offer SFSE reserve pool first, otherwise use local trampoline + void* AllocTrampoline(std::size_t a_size, bool a_useSFSEReserve = true) + { + auto& trampoline = GetTrampoline(); + + if (auto intfc = GetTrampolineInterface(); intfc && a_useSFSEReserve) { + auto* mem = intfc->AllocateFromBranchPool(a_size); + if (mem) { + trampoline.set_trampoline(mem, a_size); + return mem; + } else { + WARN( + "requesting allocation from SFSE branch pool failed\n" + "falling back to local trampoline"); + } + } + + auto* mem = trampoline.PageAlloc(a_size); + if (mem) { + return mem; + } else { + FATAL( + "failed to allocate any memory from either branch pool or local trampoline\n" + "this is fatal!\nSize : {}", + a_size); + std::unreachable(); + } + } +} // namespace SFSE + +// versiondata +namespace SFSE +{ + struct PluginVersionData + { + public: + enum + { + kVersion = 1, + }; + + // describe how you find your addresses + enum class AddressIndependence : std::uint32_t + { + kNone = 0, + // signature matching only + kSignatureScanning = 1 << 0, + // Address Library v1 (https://www.nexusmods.com/starfield/mods/3256) + kAddressLibrary = 1 << 1, + }; + + // describe your structure compatibility + enum class StructureIndependence : std::uint32_t + { + kNone = 0, + // doesn't use any game structures + kNoStructs = 1 << 0, + // works with the structure layout the game shipped with + kInitialLayout = 1 << 1, + // additional bits will be added here when breaking changes happen + }; + + constexpr void PluginVersion(std::uint32_t a_version) noexcept { pluginVersion = a_version; } + constexpr void PluginName(std::string_view a_plugin) noexcept { SetCharBuffer(a_plugin, std::span{ pluginName }); } + constexpr void AuthorName(std::string_view a_name) noexcept { SetCharBuffer(a_name, std::span{ author }); } + constexpr void UsesSigScanning(bool a_value) noexcept { addressIndependence.set(AddressIndependence::kSignatureScanning); } + constexpr void UsesAddressLibrary(bool a_value) noexcept { addressIndependence.set(AddressIndependence::kAddressLibrary); } + constexpr void HasNoStructUse(bool a_value) noexcept { structureCompatibility.set(StructureIndependence::kNoStructs); } + constexpr void IsLayoutDependent(bool a_value) noexcept { structureCompatibility.set(StructureIndependence::kInitialLayout); } + constexpr void CompatibleVersions(std::initializer_list a_versions) noexcept + { + // must be zero-terminated + assert(a_versions.size() < std::size(compatibleVersions) - 1); + std::ranges::copy(a_versions, compatibleVersions); + } + constexpr void MinimumRequiredXSEVersion(std::uint32_t a_version) noexcept { xseMinimum = a_version; } + + const std::uint32_t dataVersion{ kVersion }; // shipped with xse + std::uint32_t pluginVersion = 0; // version number of your plugin + char pluginName[256] = {}; // null-terminated ASCII plugin name (please make this recognizable to users) + char author[256] = {}; // null-terminated ASCII plugin author name + dku::enumeration addressIndependence{ AddressIndependence::kNone }; // describe how you find your addressese using the kAddressIndependence_ enums + dku::enumeration structureCompatibility{ StructureIndependence::kNone }; // describe how you handle structure layout using the kStructureIndependence_ enums + std::uint32_t compatibleVersions[16] = {}; // list of compatible versions + std::uint32_t xseMinimum = 0; // minimum version of the script extender required + const std::uint32_t reservedNonBreaking = 0; // set to 0 + const std::uint32_t reservedBreaking = 0; // set to 0 + + private: + static constexpr void SetCharBuffer( + std::string_view a_src, + std::span a_dst) noexcept + { + assert(a_src.size() < a_dst.size()); + std::ranges::fill(a_dst, '\0'); + std::ranges::copy(a_src, a_dst.begin()); + } + }; + static_assert(offsetof(PluginVersionData, dataVersion) == 0x000); + static_assert(offsetof(PluginVersionData, pluginVersion) == 0x004); + static_assert(offsetof(PluginVersionData, pluginName) == 0x008); + static_assert(offsetof(PluginVersionData, author) == 0x108); + static_assert(offsetof(PluginVersionData, addressIndependence) == 0x208); + static_assert(offsetof(PluginVersionData, structureCompatibility) == 0x20C); + static_assert(offsetof(PluginVersionData, compatibleVersions) == 0x210); + static_assert(offsetof(PluginVersionData, xseMinimum) == 0x250); + static_assert(offsetof(PluginVersionData, reservedNonBreaking) == 0x254); + static_assert(offsetof(PluginVersionData, reservedBreaking) == 0x258); + static_assert(sizeof(PluginVersionData) == 0x25C); +} // namespace SFSE diff --git a/Plugin/include/imconfig.h b/Plugin/include/imconfig.h new file mode 100644 index 00000000..876cf32f --- /dev/null +++ b/Plugin/include/imconfig.h @@ -0,0 +1,122 @@ +//----------------------------------------------------------------------------- +// COMPILE-TIME OPTIONS FOR DEAR IMGUI +// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. +// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. +//----------------------------------------------------------------------------- +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) +// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. +//----------------------------------------------------------------------------- +// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp +// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. +// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. +// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. +//----------------------------------------------------------------------------- + +#pragma once + +//---- Define assertion handler. Defaults to calling assert(). +// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) +//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() +// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. +//#define IMGUI_API __declspec( dllexport ) +//#define IMGUI_API __declspec( dllimport ) + +//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS +//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions. + +//---- Disable all of Dear ImGui or don't implement standard windows/tools. +// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. +//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. +//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. +//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowStackToolWindow() will be empty (this was called IMGUI_DISABLE_METRICS_WINDOW before 1.88). + +//---- Don't implement some functions to reduce linkage requirements. +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) +//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) +//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). +//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. +//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) +//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. +//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). +//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available + +//---- Include imgui_user.h at the end of imgui.h as a convenience +//#define IMGUI_INCLUDE_IMGUI_USER_H + +//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) +//#define IMGUI_USE_WCHAR32 + +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if enabled +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION + +//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. +//#define IMGUI_USE_STB_SPRINTF + +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). +// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. +//#define IMGUI_ENABLE_FREETYPE + +//---- Use stb_truetype to build and rasterize the font atlas (default) +// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. +//#define IMGUI_ENABLE_STB_TRUETYPE + +//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. +// This will be inlined as part of ImVec2 and ImVec4 class declarations. +/* +#define IM_VEC2_CLASS_EXTRA \ + constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ +//---- ...Or use Dear ImGui's own very basic math operators. +//#define IMGUI_DEFINE_MATH_OPERATORS + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +//#define ImDrawIdx unsigned int + +//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) +//struct ImDrawList; +//struct ImDrawCmd; +//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +//#define ImDrawCallback MyImDrawCallback + +//---- Debug Tools: Macro to break in Debugger +// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) +//#define IM_DEBUG_BREAK IM_ASSERT(0) +//#define IM_DEBUG_BREAK __debugbreak() + +//---- Debug Tools: Enable slower asserts +//#define IMGUI_DEBUG_PARANOID + +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +/* +namespace ImGui +{ + void MyFunction(const char* name, const MyMatrix44& v); +} +*/ diff --git a/Plugin/include/imgui.h b/Plugin/include/imgui.h new file mode 100644 index 00000000..07cd9560 --- /dev/null +++ b/Plugin/include/imgui.h @@ -0,0 +1,3459 @@ +// dear imgui, v1.89.7 +// (headers) + +// Help: +// - Read FAQ at http://dearimgui.com/faq +// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// Read imgui.cpp for details, links and comments. + +// Resources: +// - FAQ http://dearimgui.com/faq +// - Homepage https://github.com/ocornut/imgui +// - Releases & changelog https://github.com/ocornut/imgui/releases +// - Gallery https://github.com/ocornut/imgui/issues/6478 (please post your screenshots/video there!) +// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Issues & support https://github.com/ocornut/imgui/issues + +// Getting Started? +// - Read https://github.com/ocornut/imgui/wiki/Getting-Started +// - For first-time users having issues compiling/linking/running/loading fonts: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. + +// Library Version +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') +#define IMGUI_VERSION "1.89.7" +#define IMGUI_VERSION_NUM 18971 +#define IMGUI_HAS_TABLE +#define IMGUI_HAS_VIEWPORT // Viewport WIP branch +#define IMGUI_HAS_DOCK // Docking WIP branch + +/* + +Index of this file: +// [SECTION] Header mess +// [SECTION] Forward declarations and basic types +// [SECTION] Dear ImGui end-user API functions +// [SECTION] Flags & Enumerations +// [SECTION] Helpers: Memory allocations macros, ImVector<> +// [SECTION] ImGuiStyle +// [SECTION] ImGuiIO +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) +// [SECTION] Platform Dependent Interfaces (ImGuiPlatformIO, ImGuiPlatformMonitor, ImGuiPlatformImeData) +// [SECTION] Obsolete functions and types + +*/ + +#pragma once + +// Configuration file with compile-time options +// (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system') +#ifdef IMGUI_USER_CONFIG +#include IMGUI_USER_CONFIG +#endif +#include "imconfig.h" + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +// Includes +#include // FLT_MIN, FLT_MAX +#include // va_list, va_start, va_end +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) +// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API) +#ifndef IMGUI_API +#define IMGUI_API +#endif +#ifndef IMGUI_IMPL_API +#define IMGUI_IMPL_API IMGUI_API +#endif + +// Helper Macros +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h +#endif +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11 +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) + +// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. +#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) +#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) +#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif + +// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) +#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID) +#define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) +#define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) +#else +#define IM_MSVC_RUNTIME_CHECKS_OFF +#define IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Warnings +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#if __has_warning("-Wzero-as-null-pointer-constant") +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations and basic types +//----------------------------------------------------------------------------- + +// Forward declarations +struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) +struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. +struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) +struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader +struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) +struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) +struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) +struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame +struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiPlatformIO; // Multi-viewport support: interface for Platform/Renderer backends + viewports to render +struct ImGuiPlatformMonitor; // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors +struct ImGuiPlatformImeData; // Platform IME data for io.SetPlatformImeDataFn() function. +struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) +struct ImGuiStorage; // Helper for key->value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table +struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) +struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") +struct ImGuiViewport; // A Platform Window (always 1 unless multi-viewport are enabled. One per platform window to output to). In the future may represent Platform Monitor +struct ImGuiWindowClass; // Window class (rare/advanced uses: provide hints to the platform backend via altered viewport flags and parent/child info) + +// Enumerations +// - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +enum ImGuiKey : int; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) +enum ImGuiMouseSource : int; // -> enum ImGuiMouseSource // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen) +typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions +typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type +typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction +typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) +typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor shape +typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending) +typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() + +// Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build +typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. +typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags +typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDockNodeFlags; // -> enum ImGuiDockNodeFlags_ // Flags: for DockSpace() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() +typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() +typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() +typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for storage only for now: an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() +typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() +typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() +typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() +typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() + +// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] +// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. +#ifndef ImTextureID +typedef void* ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +#endif + +// ImDrawIdx: vertex index. [Compile-time configurable type] +// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). +// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) +#endif + +// Scalar data types +typedef unsigned int ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string) +typedef signed char ImS8; // 8-bit signed integer +typedef unsigned char ImU8; // 8-bit unsigned integer +typedef signed short ImS16; // 16-bit signed integer +typedef unsigned short ImU16; // 16-bit unsigned integer +typedef signed int ImS32; // 32-bit signed integer == int +typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) +typedef signed long long ImS64; // 64-bit signed integer +typedef unsigned long long ImU64; // 64-bit unsigned integer + +// Character types +// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) +typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. +typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. +#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] +typedef ImWchar32 ImWchar; +#else +typedef ImWchar16 ImWchar; +#endif + +// Callback and functions types +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() +typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() +typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() + +// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] +// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec2 +{ + float x, y; + constexpr ImVec2() : x(0.0f), y(0.0f) { } + constexpr ImVec2(float _x, float _y) : x(_x), y(_y) { } + float& operator[] (size_t idx) { IM_ASSERT(idx == 0 || idx == 1); return ((float*)(void*)(char*)this)[idx]; } // We very rarely use this [] operator, so the assert overhead is fine. + float operator[] (size_t idx) const { IM_ASSERT(idx == 0 || idx == 1); return ((const float*)(const void*)(const char*)this)[idx]; } +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. +#endif +}; + +// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] +struct ImVec4 +{ + float x, y, z, w; + constexpr ImVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { } + constexpr ImVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. +#endif +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] Dear ImGui end-user API functions +// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Context creation and access + // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. + IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Main + IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame! + IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. + + // Demo, Debug, Information + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. + IMGUI_API void ShowDebugLogWindow(bool* p_open = NULL); // create Debug Log window. display a simplified log of important dear imgui events. + IMGUI_API void ShowStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) + + // Styles + IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) + IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font + IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style + + // Windows + // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. + // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, + // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). + // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting + // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + // - Note that the bottom of window stack always contains a window called "Debug". + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API void End(); + + // Child Windows + // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. + // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). + // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. + // Always call a matching EndChild() for each BeginChild() call, regardless of its return value. + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API void EndChild(); + + // Windows Utilities + // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. + IMGUI_API bool IsWindowAppearing(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives + IMGUI_API float GetWindowDpiScale(); // get DPI scale currently associated to the current window's viewport. + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) + IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) + IMGUI_API ImGuiViewport*GetWindowViewport(); // get viewport currently associated to the current window. + + // Window manipulation + // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() + IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. + IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. + + // Content region + // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful. + // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion) + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min for the full window (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max for the full window (roughly (0,0)+Size-Scroll) where Size can be overridden with SetNextWindowContentSize(), in window coordinates + + // Windows Scrolling + // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). + // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). + IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y + IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushTabStop(bool tab_stop); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopTabStop(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). + IMGUI_API void PopItemWidth(); + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. + IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + + // Style read access + // - Use the ShowStyleEditor() function to interactively see/edit the colors. + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. + + // Cursor / Layout + // - By "cursor" we mean the current output position. + // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. + // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: + // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() + // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. + IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. + IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. + IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in a horizontal-layout context. + IMGUI_API void Spacing(); // add vertical spacing. + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position) + IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc. + IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList:: + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system. + IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.) + IMGUI_API void SetCursorPosY(float local_y); // + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates (useful to work with ImDrawList API). generally top-left == GetMainViewport()->Pos == (0,0) in single viewport mode, and bottom-right == GetMainViewport()->Pos+Size == io.DisplaySize in single-viewport mode. + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute coordinates + IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) + IMGUI_API float GetTextLineHeight(); // ~ FontSize + IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) + IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 + IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) + + // ID stack/scopes + // Read the FAQ (docs/FAQ.md or http://dearimgui.com/faq) for more details about how ID are handled in dear imgui. + // - Those questions are answered and impacted by understanding of the ID stack system: + // - "Q: Why is my widget not reacting when I click on it?" + // - "Q: How can I have widgets with an empty label?" + // - "Q: How can I have multiple widgets with the same label?" + // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely + // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. + // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. + // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, + // whereas "str_id" denote a string that is only used as an ID and not normally displayed. + IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). + IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). + IMGUI_API void PopID(); // pop from the ID stack. + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets: Text + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. + IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text + IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void SeparatorText(const char* label); // currently: formatted text with an horizontal line + + // Widgets: Main + // - Most widgets return true when the value has been changed or when pressed/selected + // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); + IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + + // Widgets: Images + // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0)); + IMGUI_API bool ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + + // Widgets: Combo Box (Dropdown) + // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. + // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. + IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! + IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" + IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); + + // Widgets: Drag Sliders + // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that a 'float v[X]' function argument is the same as 'float* v', + // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. + // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders + // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Input with Keyboard + // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. + // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. + IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. + + // Widgets: Trees + // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. + IMGUI_API bool TreeNode(const char* label); + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const void* ptr_id); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. + IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. + + // Widgets: Selectables + // - A selectable highlights when hovered, and can display another color when selected. + // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + + // Widgets: List Boxes + // - This is essentially a thin wrapper to using BeginChild/EndChild with some stylistic changes. + // - The BeginListBox()/EndListBox() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() or any items. + // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. + // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth + // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items + IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region + IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + + // Widgets: Data Plotting + // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + + // Widgets: Value() Helpers. + // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + + // Widgets: Menus + // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. + // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. + // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. + // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). + IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. + IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Tooltips + // - Tooltips are windows following the mouse. They do not take focus away. + // - A tooltip window can contain items of any types. SetTooltip() is a shortcut for the 'if (BeginTooltip()) { Text(...); EndTooltip(); }' idiom. + IMGUI_API bool BeginTooltip(); // begin/append a tooltip window. + IMGUI_API void EndTooltip(); // only call EndTooltip() if BeginTooltip()/BeginItemTooltip() returns true! + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip. Often used after a ImGui::IsItemHovered() check. Override any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Tooltips: helpers for showing a tooltip when hovering an item + // - BeginItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_Tooltip) && BeginTooltip())' idiom. + // - SetItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_Tooltip)) { SetTooltip(...); }' idiom. + // - Where 'ImGuiHoveredFlags_Tooltip' itself is a shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on active input type. For mouse it defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. + IMGUI_API bool BeginItemTooltip(); // begin/append a tooltip window if preceding item was hovered. + IMGUI_API void SetItemTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip if preceeding item was hovered. override any previous call to SetTooltip(). + IMGUI_API void SetItemTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Popups, Modals + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + + // Popups: begin/end functions + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + + // Popups: open/close functions + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. + // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks + IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + + // Popups: open+begin combined functions helpers + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - They are convenient to easily create context menus, hence the name. + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). + + // Popups: query functions + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. + + // Tables + // - Full-featured replacement for old Columns API. + // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. + // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. + // The typical call flow is: + // - 1. Call BeginTable(), early out if returning false. + // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. + // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. + // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. + // - 5. Populate contents: + // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. + // - If you are using tables as a sort of grid, where every column is holding the same type of contents, + // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). + // TableNextColumn() will automatically wrap-around into the next row if needed. + // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! + // - Summary of possible call flow: + // -------------------------------------------------------------------------------------------------------- + // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! + // -------------------------------------------------------------------------------------------------------- + // - 5. Call EndTable() + IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! + IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. + IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. + IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. + + // Tables: Headers & Columns declaration + // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. + // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. + // Headers are required to perform: reordering, sorting, and opening the context menu. + // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. + // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in + // some advanced use cases (e.g. adding custom widgets in header row). + // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0); + IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) + + // Tables: Sorting & Miscellaneous functions + // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. + // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have + // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, + // else you may wastefully sort your data every frame! + // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. + IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) + IMGUI_API int TableGetColumnIndex(); // return current column index. + IMGUI_API int TableGetRowIndex(); // return current row index. + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. + IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. + + // Legacy Columns API (prefer using Tables!) + // - You can also use SameLine(pos_x) to mimic simplified columns. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); + + // Tab Bars, Tabs + // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. + IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar + IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! + IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. + IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + + // Docking + // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. + // Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking! + // - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking/undocking. + // - Drag from window menu button (upper-left button) to undock an entire node (all windows). + // - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to _enable_ docking/undocking. + // About dockspaces: + // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. + // - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport. + // This is often used with ImGuiDockNodeFlags_PassthruCentralNode. + // - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame! + // - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. + // e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. + IMGUI_API ImGuiID DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API ImGuiID DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id + IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (control docking compatibility + provide hints to platform backend via custom viewport flags and platform parent/child relationship) + IMGUI_API ImGuiID GetWindowDockID(); + IMGUI_API bool IsWindowDocked(); // is current window docked into another window? + + // Logging/Capture + // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) + IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) + IMGUI_API void LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Drag and Drop + // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). + // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) + // - An item can be both drag source and drop target. + IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. + IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! + IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! + IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type. + + // Disabling [BETA API] + // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) + // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) + // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. + IMGUI_API void BeginDisabled(bool disabled = true); + IMGUI_API void EndDisabled(); + + // Clipping + // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Focus, Activation + // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item" + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. + + // Overlapping mode + IMGUI_API void SetNextItemAllowOverlap(); // allow next item to be overlapped by a subsequent item. Useful with invisible buttons, selectable, treenode covering an area where subsequent items may need to be added. Note that both Selectable() and TreeNode() have dedicated flags doing this. + + // Item/Widgets Utilities and Query Functions + // - Most of the functions are referring to the previous Item that has been submitted. + // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. + IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. + IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) + IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? + IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. + IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) + IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). + IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. + IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). + IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). + IMGUI_API bool IsAnyItemHovered(); // is any item hovered? + IMGUI_API bool IsAnyItemActive(); // is any item active? + IMGUI_API bool IsAnyItemFocused(); // is any item focused? + IMGUI_API ImGuiID GetItemID(); // get ID of last item (~~ often same ImGui::GetID(label) beforehand) + IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectSize(); // get size of last item + + // Viewports + // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. + // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. + // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. + IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. + + // Background/Foreground Draw Lists + IMGUI_API ImDrawList* GetBackgroundDrawList(); // get background draw list for the viewport associated to the current window. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(); // get foreground draw list for the viewport associated to the current window. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. + IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). + IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) + + // Text Utilities + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + + // Color Utilities + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs Utilities: Keyboard/Mouse/Gamepad + // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). + // - before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. About use of those legacy ImGuiKey values: + // - without IMGUI_DISABLE_OBSOLETE_KEYIO (legacy support): you can still use your legacy native/user indices (< 512) according to how your backend/engine stored them in io.KeysDown[], but need to cast them to ImGuiKey. + // - with IMGUI_DISABLE_OBSOLETE_KEYIO (this is the way forward): any use of ImGuiKey will assert with key < 512. GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined). + IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. + IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? + IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate + IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared. + IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. + + // Inputs Utilities: Mouse specific + // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. + // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. + // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') + IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? + IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. + IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) + IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available + IMGUI_API bool IsAnyMouseDown(); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) + IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + + // Clipboard Utilities + // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Settings/.Ini Utilities + // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). + // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. + // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). + IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. + + // Debug Utilities + IMGUI_API void DebugTextEncoding(const char* text); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. + + // Memory Allocators + // - Those functions are not reliant on the current context. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. + IMGUI_API void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL); + IMGUI_API void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + + // (Optional) Platform/OS interface for multi-viewport support + // Read comments around the ImGuiPlatformIO structure for more details. + // Note: You may use GetWindowViewport() to get the current viewport of the current window. + IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // platform/renderer functions, for backend to setup + viewports list. + IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport. + IMGUI_API void RenderPlatformWindowsDefault(void* platform_render_arg = NULL, void* renderer_render_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs. + IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from backend Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext(). + IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID id); // this is a helper for backends. + IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.) + +} // namespace ImGui + +//----------------------------------------------------------------------------- +// [SECTION] Flags & Enumerations +//----------------------------------------------------------------------------- + +// Flags for ImGui::Begin() +// (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) +enum ImGuiWindowFlags_ +{ + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiWindowFlags_NoDocking = 1 << 21, // Disable docking of this window + + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + + // [Internal] + ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] On child window: allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. + ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() + ImGuiWindowFlags_DockNodeHost = 1 << 29, // Don't use! For internal use by Begin()/NewFrame() +}; + +// Flags for ImGui::InputText() +// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) +enum ImGuiInputTextFlags_ +{ + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function. + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysOverwrite = 1 << 13, // Overwrite mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). + ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) + ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) + ImGuiInputTextFlags_EscapeClearsAll = 1 << 20, // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + + // Obsolete names + //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). + ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default. + ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area). + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 +#endif +}; + +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat +// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. +// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. +// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter +// and want to use another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag explicitly. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this doesn't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too + ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text + ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 +#endif +}; + +// Flags for ImGui::BeginCombo() +enum ImGuiComboFlags_ +{ + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default + ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) + ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible + ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible + ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button + ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, +}; + +// Flags for ImGui::BeginTabBar() +enum ImGuiTabBarFlags_ +{ + ImGuiTabBarFlags_None = 0, + ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) + ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab + ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, +}; + +// Flags for ImGui::BeginTabItem() +enum ImGuiTabItemFlags_ +{ + ImGuiTabItemFlags_None = 0, + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab + ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) + ImGuiTabItemFlags_Trailing = 1 << 7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) +}; + +// Flags for ImGui::BeginTable() +// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The DEFAULT sizing policies are: +// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. +// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. +// - When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. +// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +// - Stretch Columns will share the remaining width according to their respective weight. +// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +// - When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed +// - Columns sizing policy allowed: Fixed/Auto mostly. +// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +// - Read on documentation at the top of imgui_tables.cpp for details. +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. + ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). + // Decorations + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + // Sizing Policy (read above for defaults) + ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. + ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. + ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + // Sizing Extra Options + ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + // Clipping + ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + // Padding + ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. + ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + // Sorting + ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + + // [Internal] Combinations and masks + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, +}; + +// Flags for ImGui::TableSetupColumn() +enum ImGuiTableColumnFlags_ +{ + // Input configuration flags + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. + ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. + ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. + ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit label for this column. Convenient for some small columns. Name will still appear in context menu. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). + ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + + // Output status flags, read-only via TableGetColumnFlags() + ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. + ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs + ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse + + // [Internal] Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) +}; + +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) +}; + +// Flags for ImGui::IsWindowFocused() +enum ImGuiFocusedFlags_ +{ + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, // Return true if any children of the window is focused + ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, +}; + +// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() +// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. +enum ImGuiHoveredFlags_ +{ + ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + ImGuiHoveredFlags_AllowWhenOverlappedByItem = 1 << 8, // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. + ImGuiHoveredFlags_AllowWhenOverlappedByWindow = 1 << 9, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 10, // IsItemHovered() only: Return true even if the item is disabled + ImGuiHoveredFlags_NoNavOverride = 1 << 11, // IsItemHovered() only: Disable using gamepad/keyboard navigation state when active, always query mouse + ImGuiHoveredFlags_AllowWhenOverlapped = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow, + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, + + // Tooltips mode + // - typically used in IsItemHovered() + SetTooltip() sequence. + // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. + // e.g. 'TooltipHoveredFlagsForMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. + // - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often. + // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. + ImGuiHoveredFlags_ForTooltip = 1 << 11, // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. + + // (Advanced) Mouse Hovering delays. + // - generally you can use ImGuiHoveredFlags_ForTooltip to use application-standardized flags. + // - use those if you need specific overrides. + ImGuiHoveredFlags_Stationary = 1 << 12, // Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. + ImGuiHoveredFlags_DelayNone = 1 << 13, // IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. + ImGuiHoveredFlags_DelayShort = 1 << 14, // IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + ImGuiHoveredFlags_DelayNormal = 1 << 15, // IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + ImGuiHoveredFlags_NoSharedDelay = 1 << 16, // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) +}; + +// Flags for ImGui::DockSpace(), shared/inherited by child nodes. +// (Some flags can be applied to individual nodes directly) +// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. +enum ImGuiDockNodeFlags_ +{ + ImGuiDockNodeFlags_None = 0, + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6, // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. +}; + +// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() +enum ImGuiDragDropFlags_ +{ + ImGuiDragDropFlags_None = 0, + // BeginDragDropSource() flags + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + // AcceptDragDropPayload() flags + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. +}; + +// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. +#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. + +// A primary data type +enum ImGuiDataType_ +{ + ImGuiDataType_S8, // signed char / char (with sensible compilers) + ImGuiDataType_U8, // unsigned char + ImGuiDataType_S16, // short + ImGuiDataType_U16, // unsigned short + ImGuiDataType_S32, // int + ImGuiDataType_U32, // unsigned int + ImGuiDataType_S64, // long long / __int64 + ImGuiDataType_U64, // unsigned long long / unsigned __int64 + ImGuiDataType_Float, // float + ImGuiDataType_Double, // double + ImGuiDataType_COUNT +}; + +// A cardinal direction +enum ImGuiDir_ +{ + ImGuiDir_None = -1, + ImGuiDir_Left = 0, + ImGuiDir_Right = 1, + ImGuiDir_Up = 2, + ImGuiDir_Down = 3, + ImGuiDir_COUNT +}; + +// A sorting direction +enum ImGuiSortDirection_ +{ + ImGuiSortDirection_None = 0, + ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. + ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. +}; + +// A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values. +// All our named keys are >= 512. Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87). +// Since >= 1.89 we increased typing (went from int to enum), some legacy code may need a cast to ImGuiKey. +// Read details about the 1.87 and 1.89 transition : https://github.com/ocornut/imgui/issues/4921 +// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter(). +enum ImGuiKey : int +{ + // Keyboard + ImGuiKey_None = 0, + ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Insert, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Space, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, + ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, + ImGuiKey_Menu, + ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, + ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, + ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, + ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, + ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, + ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, + ImGuiKey_Apostrophe, // ' + ImGuiKey_Comma, // , + ImGuiKey_Minus, // - + ImGuiKey_Period, // . + ImGuiKey_Slash, // / + ImGuiKey_Semicolon, // ; + ImGuiKey_Equal, // = + ImGuiKey_LeftBracket, // [ + ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) + ImGuiKey_RightBracket, // ] + ImGuiKey_GraveAccent, // ` + ImGuiKey_CapsLock, + ImGuiKey_ScrollLock, + ImGuiKey_NumLock, + ImGuiKey_PrintScreen, + ImGuiKey_Pause, + ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, + ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, + ImGuiKey_KeypadDecimal, + ImGuiKey_KeypadDivide, + ImGuiKey_KeypadMultiply, + ImGuiKey_KeypadSubtract, + ImGuiKey_KeypadAdd, + ImGuiKey_KeypadEnter, + ImGuiKey_KeypadEqual, + + // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION + // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) + ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) + ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) + ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) + ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit + ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard + ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak + ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode) + ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode) + ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog] + ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog] + ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS) + ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS) + ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadRStickLeft, // [Analog] + ImGuiKey_GamepadRStickRight, // [Analog] + ImGuiKey_GamepadRStickUp, // [Analog] + ImGuiKey_GamepadRStickDown, // [Analog] + + // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) + // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. + ImGuiKey_MouseLeft, ImGuiKey_MouseRight, ImGuiKey_MouseMiddle, ImGuiKey_MouseX1, ImGuiKey_MouseX2, ImGuiKey_MouseWheelX, ImGuiKey_MouseWheelY, + + // [Internal] Reserved for mod storage + ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, + ImGuiKey_COUNT, + + // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) + // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing + // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those + // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). + // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. + // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and + // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... + ImGuiMod_None = 0, + ImGuiMod_Ctrl = 1 << 12, // Ctrl + ImGuiMod_Shift = 1 << 13, // Shift + ImGuiMod_Alt = 1 << 14, // Option/Menu + ImGuiMod_Super = 1 << 15, // Cmd/Super/Windows + ImGuiMod_Shortcut = 1 << 11, // Alias for Ctrl (non-macOS) _or_ Super (macOS). + ImGuiMod_Mask_ = 0xF800, // 5-bits + + // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array. + // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE) + // If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. + ImGuiKey_NamedKey_BEGIN = 512, + ImGuiKey_NamedKey_END = ImGuiKey_COUNT, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys + ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index. +#else + ImGuiKey_KeysData_SIZE = ImGuiKey_COUNT, // Size of KeysData[]: hold legacy 0..512 keycodes + named keys + ImGuiKey_KeysData_OFFSET = 0, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index. +#endif + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 + ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 +#endif +}; + +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO +// OBSOLETED in 1.88 (from July 2022): ImGuiNavInput and io.NavInputs[]. +// Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as IMGUI_DISABLE_OBSOLETE_KEYIO is not set. +// Custom backends: feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. +enum ImGuiNavInput +{ + ImGuiNavInput_Activate, ImGuiNavInput_Cancel, ImGuiNavInput_Input, ImGuiNavInput_Menu, ImGuiNavInput_DpadLeft, ImGuiNavInput_DpadRight, ImGuiNavInput_DpadUp, ImGuiNavInput_DpadDown, + ImGuiNavInput_LStickLeft, ImGuiNavInput_LStickRight, ImGuiNavInput_LStickUp, ImGuiNavInput_LStickDown, ImGuiNavInput_FocusPrev, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakSlow, ImGuiNavInput_TweakFast, + ImGuiNavInput_COUNT, +}; +#endif + +// Configuration flags stored in io.ConfigFlags. Set by user/application. +enum ImGuiConfigFlags_ +{ + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate. + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. + ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + + // [BETA] Docking + ImGuiConfigFlags_DockingEnable = 1 << 6, // Docking enable flags. + + // [BETA] Viewports + // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. + ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends) + ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application. + ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress. + + // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21, // Application is using a touch screen instead of a mouse. +}; + +// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. +enum ImGuiBackendFlags_ +{ + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + + // [BETA] Viewports + ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Backend Platform supports multiple viewports. + ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, // Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags_NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + ImGuiBackendFlags_RendererHasViewports = 1 << 12, // Backend Renderer supports multiple viewports. +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgActive, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_Tab, // TabItem in a TabBar + ImGuiCol_TabHovered, + ImGuiCol_TabActive, + ImGuiCol_TabUnfocused, + ImGuiCol_TabUnfocusedActive, + ImGuiCol_DockingPreview, // Preview overlay color when about to docking something + ImGuiCol_DockingEmptyBg, // Background color for empty node (e.g. CentralNode with no window docked into it) + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) + ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) + ImGuiCol_TableRowBg, // Table row background (even rows) + ImGuiCol_TableRowBgAlt, // Table row background (odd rows) + ImGuiCol_TextSelectedBg, + ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target + ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item + ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active + ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +// During initialization or between frames, feel free to just poke into ImGuiStyle directly. +// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign + ImGuiStyleVar_ChildRounding, // float ChildRounding + ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize + ImGuiStyleVar_PopupRounding, // float PopupRounding + ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_CellPadding, // ImVec2 CellPadding + ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize + ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_TabRounding, // float TabRounding + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign + ImGuiStyleVar_SeparatorTextBorderSize,// float SeparatorTextBorderSize + ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign + ImGuiStyleVar_SeparatorTextPadding,// ImVec2 SeparatorTextPadding + ImGuiStyleVar_COUNT +}; + +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + + // [Internal] + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft, +}; + +// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() +enum ImGuiColorEditFlags_ +{ + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. + ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + + // User Options (right-click on widget to change some of them). + ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. + ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). + ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " + ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " + ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. + ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. + + // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to + // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. + ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + + // [Internal] Masks + ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, + + // Obsolete names + //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] +}; + +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigDragClickToInputText) +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + + // Obsolete names + //ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79] +}; + +// Identify a mouse button. +// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. +enum ImGuiMouseButton_ +{ + ImGuiMouseButton_Left = 0, + ImGuiMouseButton_Right = 1, + ImGuiMouseButton_Middle = 2, + ImGuiMouseButton_COUNT = 5 +}; + +// Enumeration for GetMouseCursor() +// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) + ImGuiMouseCursor_ResizeNS, // When hovering over a horizontal border + ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column + ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. + ImGuiMouseCursor_COUNT +}; + +// Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. +// Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() +// But that "Mouse" data can come from different source which occasionally may be useful for application to know about. +// You can submit a change of pointer type using io.AddMouseSourceEvent(). +enum ImGuiMouseSource : int +{ + ImGuiMouseSource_Mouse = 0, // Input is coming from an actual mouse. + ImGuiMouseSource_TouchScreen, // Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). + ImGuiMouseSource_Pen, // Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). + ImGuiMouseSource_COUNT +}; + +// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions +// Represent a condition. +// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. +enum ImGuiCond_ +{ + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable), same as _None + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) + ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) + ImGuiCond_Appearing = 1 << 3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers: Memory allocations macros, ImVector<> +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + +//----------------------------------------------------------------------------- +// ImVector<> +// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). +//----------------------------------------------------------------------------- +// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. +// - We use std-like naming convention here, which is a little unusual for this codebase. +// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. +// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, +// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. +//----------------------------------------------------------------------------- + +IM_MSVC_RUNTIME_CHECKS_OFF +template +struct ImVector +{ + int Size; + int Capacity; + T* Data; + + // Provide standard typedefs but we don't use them ourselves. + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + // Constructors, destructor + inline ImVector() { Size = Capacity = 0; Data = NULL; } + inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } + inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything + + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything + inline void clear_delete() { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); } // Important: never called automatically! always explicit. + inline void clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); } // Important: never called automatically! always explicit. + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int size_in_bytes() const { return Size * (int)sizeof(T); } + inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } + inline int capacity() const { return Capacity; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return Data + Size; } + inline const T* end() const { return Data + Size; } + inline T& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } + inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } + inline void reserve_discard(int new_capacity) { if (new_capacity <= Capacity) return; if (Data) IM_FREE(Data); Data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); Capacity = new_capacity; } + + // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. + inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } + inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; } + inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; } + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStyle +//----------------------------------------------------------------------------- +// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). +// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, +// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. +//----------------------------------------------------------------------------- + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in Dear ImGui. + float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + ImVec2 WindowPadding; // Padding within a window. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. + float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. + float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) + float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 CellPadding; // Padding within a table cell + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. + float ScrollbarRounding; // Radius of grab corners for scrollbar. + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthForCloseButton; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + float SeparatorTextBorderSize; // Thickkness of border in SeparatorText() + ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). + ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + ImVec4 Colors[ImGuiCol_COUNT]; + + // Behaviors + // (It is possible to modify those fields mid-frame if specific behavior need it, unlike e.g. configuration fields in ImGuiIO) + float HoverStationaryDelay; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. + float HoverDelayShort; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay. + float HoverDelayNormal; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). " + ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. + + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiIO +//----------------------------------------------------------------------------- +// Communicate most settings and inputs/outputs to Dear ImGui using this structure. +// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +//----------------------------------------------------------------------------- + +// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. +struct ImGuiKeyData +{ + bool Down; // True for if key is down + float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) + float DownDurationPrev; // Last frame duration the key has been down + float AnalogValue; // 0.0f..1.0f for gamepad values +}; + +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Configuration // Default value + //------------------------------------------------------------------ + + ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. + ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ImVec2 DisplaySize; // // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. + float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. + const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + void* UserData; // = NULL // Store your own data. + + ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. + + // Docking options (when ImGuiConfigFlags_DockingEnable is set) + bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + + // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) + bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. + bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. + bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). + bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. + + // Miscellaneous options + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. + bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). + bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). + bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. + bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) + bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. + + // Inputs Behaviors + // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. + float KeyRepeatDelay; // = 0.275f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. + + //------------------------------------------------------------------ + // Debug options + //------------------------------------------------------------------ + + // Tools to test correct Begin/End and BeginChild/EndChild behaviors. + // Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX() + // This is inconsistent with other BeginXXX functions and create confusion for many users. + // We expect to update the API eventually. In the meanwhile we provide tools to facilitate checking user-code behavior. + bool ConfigDebugBeginReturnValueOnce;// = false // First-time calls to Begin()/BeginChild() will return false. NEEDS TO BE SET AT APPLICATION BOOT TIME if you don't want to miss windows. + bool ConfigDebugBeginReturnValueLoop;// = false // Some calls to Begin()/BeginChild() will return false. Will cycle through window depths then repeat. Suggested use: add "io.ConfigDebugBeginReturnValue = io.KeyShift" in your main loop then occasionally press SHIFT. Windows should be flickering while running. + + // Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data. + // Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. + // Consider using e.g. Win32's IsDebuggerPresent() as an additional filter (or see ImOsIsDebuggerPresent() in imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version). + bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys() in input processing. + + // Option to audit .ini data + bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) + + //------------------------------------------------------------------ + // Platform Functions + // (the imgui_impl_xxxx backend files are setting those up for you) + //------------------------------------------------------------------ + + // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. + const char* BackendPlatformName; // = NULL + const char* BackendRendererName; // = NULL + void* BackendPlatformUserData; // = NULL // User data for platform backend + void* BackendRendererUserData; // = NULL // User data for renderer backend + void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend + + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + void* ImeWindowHandle; // = NULL // [Obsolete] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. +#else + void* _UnusedPadding; // Unused field to keep data structure the same size. +#endif + + //------------------------------------------------------------------ + // Input - Call before calling NewFrame() + //------------------------------------------------------------------ + + // Input Functions + IMGUI_API void AddKeyEvent(ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) + IMGUI_API void AddKeyAnalogEvent(ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. + IMGUI_API void AddMousePosEvent(float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) + IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change + IMGUI_API void AddMouseWheelEvent(float wheel_x, float wheel_y); // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left. + IMGUI_API void AddMouseSourceEvent(ImGuiMouseSource source); // Queue a mouse source change (Mouse/TouchScreen/Pen) + IMGUI_API void AddMouseViewportEvent(ImGuiID id); // Queue a mouse hovered viewport. Requires backend to set ImGuiBackendFlags_HasMouseHoveredViewport to call this (for multi-viewport support). + IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) + IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input + IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate + IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue a new characters input from a UTF-8 string + + IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. + IMGUI_API void SetAppAcceptingEvents(bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. + IMGUI_API void ClearInputCharacters(); // [Internal] Clear the text input buffer manually + IMGUI_API void ClearInputKeys(); // [Internal] Release all keys + + //------------------------------------------------------------------ + // Output - Updated by NewFrame() or EndFrame()/Render() + // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is + // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). + bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. + bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! + bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. + bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events). + float Framerate; // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsRenderWindows; // Number of visible windows + int MetricsActiveWindows; // Number of active windows + int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts. + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. + + // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. + // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). + // Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. + bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. + float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. +#endif + + //------------------------------------------------------------------ + // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). + + // Main Input State + // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. + float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. + ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). + ImGuiID MouseHoveredViewport; // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag is much better (few backends can handle that). Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows). + bool KeyCtrl; // Keyboard modifier down: Control + bool KeyShift; // Keyboard modifier down: Shift + bool KeyAlt; // Keyboard modifier down: Alt + bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows + + // Other state maintained from data above + IO function calls + ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. DOES NOT CONTAINS ImGuiMod_Shortcut which is pretranslated). Read-only, updated by NewFrame() + ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this. + bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. + ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) + ImVec2 MouseClickedPos[5]; // Position at time of clicking + double MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) + ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. + bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. + bool AppFocusLost; // Only modify via AddFocusEvent() + bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents() + ImS8 BackendUsingLegacyKeyArrays; // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[] + bool BackendUsingLegacyNavInputArray; // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly + ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() + ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc data structures +//----------------------------------------------------------------------------- + +// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. +// The callback function should return 0 by default. +// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration +// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB +// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows +// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. +struct ImGuiInputTextCallbackData +{ + ImGuiContext* Ctx; // Parent UI context + ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + + // Arguments for the different callback events + // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. + // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! + int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] + int CursorPos; // // Read-write // [Completion,History,Always] + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) + int SelectionEnd; // // Read-write // [Completion,History,Always] + + // Helper functions for text manipulation. + // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. + IMGUI_API ImGuiInputTextCallbackData(); + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>). + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +// Important: the content of this class is still highly WIP and likely to change and be refactored +// before we stabilize Docking features. Please be mindful if using this. +// Provide hints: +// - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +// - To the platform backend for OS level parent/child relationships of viewport. +// - To the docking system for various options and filtering. +struct ImGuiWindowClass +{ + ImGuiID ClassId; // User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ImGuiID ParentViewportId; // Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiTabItemFlags TabItemFlagsOverrideSet; // [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags_Leading or ImGuiTabItemFlags_Trailing. + ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? + + ImGuiWindowClass() { memset(this, 0, sizeof(*this)); ParentViewportId = (ImGuiID)-1; DockingAllowUnclassed = true; } +}; + +// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() +struct ImGuiPayload +{ + // Members + void* Data; // Data (copied and owned by dear imgui) + int DataSize; // Data size + + // [Internal] + ImGuiID SourceId; // Source item id + ImGuiID SourceParentId; // Source parent id (if available) + int DataFrameCount; // Data timestamp + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) + bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) + bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. + + ImGuiPayload() { Clear(); } + void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } + bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsPreview() const { return Preview; } + bool IsDelivery() const { return Delivery; } +}; + +// Sorting specification for one column of a table (sizeof == 12 bytes) +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImS16 ColumnIndex; // Index of the column + ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) + + ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + + ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +//----------------------------------------------------------------------------- + +// Helper: Unicode defines +#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. +#endif + +// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame. +// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } + + // [Internal] + struct ImGuiTextRange + { + const char* b; + const char* e; + + ImGuiTextRange() { b = e = NULL; } + ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; +}; + +// Helper: Growable text buffer for logging/accumulating text +// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') +struct ImGuiTextBuffer +{ + ImVector Buf; + IMGUI_API static char EmptyString[1]; + + ImGuiTextBuffer() { } + inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } + const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size ? Buf.Size - 1 : 0; } + bool empty() const { return Buf.Size <= 1; } + void clear() { Buf.clear(); } + void reserve(int capacity) { Buf.reserve(capacity); } + const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } + IMGUI_API void append(const char* str, const char* str_end = NULL); + IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); + IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +}; + +// Helper: Key->Value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1) +// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + // [Internal] + struct ImGuiStoragePair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + ImGuiStoragePair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + ImGuiStoragePair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + ImGuiStoragePair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + void Clear() { Data.clear(); } + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); + + // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. + IMGUI_API void BuildSortByKey(); +}; + +// Helper: Manually clip large list of items. +// If you have lots evenly spaced items and you have random access to the list, you can perform coarse +// clipping based on visibility to only submit items that are in view. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally +// fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily +// scale using lists with tens of thousands of items without a problem) +// Usage: +// ImGuiListClipper clipper; +// clipper.Begin(1000); // We have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// Generally what happens is: +// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. +// - User code submit that one element. +// - Clipper can measure the height of the first element +// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. +// - User code submit visible elements. +// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. +struct ImGuiListClipper +{ + ImGuiContext* Ctx; // Parent UI context + int DisplayStart; // First item to display, updated by each call to Step() + int DisplayEnd; // End of items to display (exclusive) + int ItemsCount; // [Internal] Number of items + float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it + float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + void* TempData; // [Internal] Internal data + + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step) + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). + IMGUI_API ImGuiListClipper(); + IMGUI_API ~ImGuiListClipper(); + IMGUI_API void Begin(int items_count, float items_height = -1.0f); + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + + // Call IncludeRangeByIndices() *BEFORE* first call to Step() if you need a range of items to not be clipped, regardless of their visibility. + // (Due to alignment / padding of certain items it is possible that an extra item may be included on either end of the display range). + IMGUI_API void IncludeRangeByIndices(int item_begin, int item_end); // item_end is exclusive e.g. use (42, 42+1) to make item 42 never clipped. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeRangeByIndices(item_begin, item_end); } // [renamed in 1.89.6] + //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] +#endif +}; + +// Helpers: ImVec2/ImVec4 operators +// - It is important that we are keeping those disabled by default so they don't leak in user space. +// - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) +// - You can use '#define IMGUI_DEFINE_MATH_OPERATORS' to import our operators, provided as a courtesy. +#ifdef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED +IM_MSVC_RUNTIME_CHECKS_OFF +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Helpers macros to generate 32-bit encoded colors +// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. +#ifndef IM_COL32_R_SHIFT +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) +#endif + +// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +// you can poke into the draw list for that! Draw callback may be useful for example to: +// A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. +#ifndef ImDrawCallback +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +#endif + +// Special Draw callback value to request renderer backend to reset the graphics/render state. +// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. +// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. +// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) + +// Typically, 1 command = 1 GPU draw call (unless command is a callback) +// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Backends made for <1.71. will typically ignore the VtxOffset fields. +// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +struct ImDrawCmd +{ + ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. + unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // The draw callback code can access this. + + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed + + // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) + inline ImTextureID GetTexID() const { return TextureId; } +}; + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared at the time you'd want to set your type up. +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// [Internal] For use by ImDrawList +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; +}; + +// [Internal] For use by ImDrawListSplitter +struct ImDrawChannel +{ + ImVector _CmdBuffer; + ImVector _IdxBuffer; +}; + + +// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. +// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. +struct ImDrawListSplitter +{ + int _Current; // Current channel number (0) + int _Count; // Number of active channels (1+) + ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) + + inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } + inline ~ImDrawListSplitter() { ClearFreeMemory(); } + inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame + IMGUI_API void ClearFreeMemory(); + IMGUI_API void Split(ImDrawList* draw_list, int count); + IMGUI_API void Merge(ImDrawList* draw_list); + IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); +}; + +// Flags for ImDrawList functions +// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) +enum ImDrawFlags_ +{ + ImDrawFlags_None = 0, + ImDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. + ImDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. + ImDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, +}; + +// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. +}; + +// Draw command list +// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, +// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to +// access the current window draw list and draw custom primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). +// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!) +// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + + // [Internal, used while building lists] + unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) + const char* _OwnerName; // Pointer to owner window's name for debugging + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + + // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) + ImDrawList(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; } + + ~ImDrawList() { _ClearFreeMemory(); } + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(ImTextureID texture_id); + IMGUI_API void PopTextureID(); + inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } + inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } + + // Primitives + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. + // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. + // In future versions we will use textures to provide cheaper and higher-quality circles. + // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); + IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) + + // Image primitives + // - Read FAQ to understand what ImTextureID is. + // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. + // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + inline void PathClear() { _Path.Size = 0; } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; } + IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); + IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points) + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + + // Advanced: Channels + // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) + // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place! + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. + // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. + inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } + inline void ChannelsMerge() { _Splitter.Merge(this); } + inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } + + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + + // Obsolete names + //inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + + // [Internal helpers] + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _TryMergeDrawCmds(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedVtxOffset(); + IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; + IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); + IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); +}; + +// All draw data to render a Dear ImGui frame +// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + int CmdListsCount; // Number of ImDrawList* to render + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here. + ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) + ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). + + // Functions + ImDrawData() { Clear(); } + void Clear() { memset(this, 0, sizeof(*this)); } // The ImDrawList are owned by ImGuiContext! + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +//----------------------------------------------------------------------------- +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) +//----------------------------------------------------------------------------- + +struct ImFontConfig +{ + void* FontData; // // TTF/OTF data + int FontDataSize; // // TTF/OTF data size + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + int FontNo; // 0 // Index of font within TTF/OTF file + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal so you can reduce this to 2 to save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. + const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. + ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + + // [Internal] + char Name[40]; // Name (strictly to ease debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +// Hold rendering data for one glyph. +// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) +struct ImFontGlyph +{ + unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) + unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. + unsigned int Codepoint : 30; // 0x0000..0x10FFFF + float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) + float X0, Y0, X1, Y1; // Glyph corners + float U0, V0, U1, V1; // Texture coordinates +}; + +// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). +// This is essentially a tightly packed of vector of 64k booleans = 8KB storage. +struct ImFontGlyphRangesBuilder +{ + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + + ImFontGlyphRangesBuilder() { Clear(); } + inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges +}; + +// See ImFontAtlas::AddCustomRectXXX functions. +struct ImFontAtlasCustomRect +{ + unsigned short Width, Height; // Input // Desired rectangle dimension + unsigned short X, Y; // Output // Packed position in Atlas + unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) + float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset + ImFont* Font; // Input // For custom font glyphs only: target font + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +}; + +// Flags for ImFontAtlas build +enum ImFontAtlasFlags_ +{ + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). +}; + +// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +// - One or more fonts. +// - Custom graphics data needed to render the shapes needed by Dear ImGui. +// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). +// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. +// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. +// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. +// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// Common pitfalls: +// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the +// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. +// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. +// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, +// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. +// - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future! +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). + IMGUI_API void Clear(); // Clear all input and output. + + // Build atlas, retrieve pixel data. + // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // The pitch is always = Width * BytesPerPixels (1 or 4) + // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... + void SetTexID(ImTextureID id) { TexID = id; } + + //------------------------------------------- + // Glyph Ranges + //------------------------------------------- + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. + // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. + // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters + + //------------------------------------------- + // [BETA] Custom Rectangles/Glyphs API + //------------------------------------------- + + // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. + // - After calling Build(), you can query the rectangle position and render your pixels. + // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of prefered texture format. + // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), + // so you can render e.g. custom colorful icons and use them as regular glyphs. + // - Read docs/FONTS.md for more details about using colorful icons. + // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. + IMGUI_API int AddCustomRectRegular(int width, int height); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } + + // [Internal] + IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + + //------------------------------------------- + // Members + //------------------------------------------- + + ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + + // [Internal] + // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. + bool TexReady; // Set when texture was built matching current font input + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. + ImVector ConfigData; // Configuration data + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + + // [Internal] Font builder + const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). + unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. + + // [Internal] Packing data + int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors + int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines + + // [Obsolete] + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + // Members: Hot ~20/24 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). + float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX + float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) + + // Members: Hot ~28/40 bytes (for CalcTextSize + render loop) + ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // // All glyphs. + const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + + // Members: Cold ~32/40 bytes + ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into + const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData + short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImWchar FallbackChar; // 2 // out // = FFFD/'?' // Character used if a glyph isn't found. + ImWchar EllipsisChar; // 2 // out // = '...'/'.'// Character used for ellipsis rendering. + short EllipsisCharCount; // 1 // out // 1 or 3 + float EllipsisWidth; // 4 // out // Width + float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 + bool DirtyLookupTables; // 1 // out // + float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; + IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // [Internal] Don't use! + IMGUI_API void BuildLookupTable(); + IMGUI_API void ClearOutputData(); + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void SetGlyphVisible(ImWchar c, bool visible); + IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Viewports +//----------------------------------------------------------------------------- + +// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. +enum ImGuiViewportFlags_ +{ + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) + ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Was created/managed by the user application? (rather than our backend) + ImGuiViewportFlags_NoDecoration = 1 << 3, // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips) + ImGuiViewportFlags_NoTaskBarIcon = 1 << 4, // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags_ViewportsNoTaskBarIcon is set) + ImGuiViewportFlags_NoFocusOnAppearing = 1 << 5, // Platform Window: Don't take focus when created. + ImGuiViewportFlags_NoFocusOnClick = 1 << 6, // Platform Window: Don't take focus when clicked on. + ImGuiViewportFlags_NoInputs = 1 << 7, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + ImGuiViewportFlags_NoRendererClear = 1 << 8, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + ImGuiViewportFlags_NoAutoMerge = 1 << 9, // Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + ImGuiViewportFlags_TopMost = 1 << 10, // Platform Window: Display on top (for tooltips only). + ImGuiViewportFlags_CanHostOtherWindows = 1 << 11, // Viewport can host multiple imgui windows (secondary viewports are associated to a single window). // FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". + + // Output status flags (from Platform) + ImGuiViewportFlags_IsMinimized = 1 << 12, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + ImGuiViewportFlags_IsFocused = 1 << 13, // Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) +}; + +// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +// - With multi-viewport enabled, we extend this concept to have multiple active viewports. +// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +// - About Main Area vs Work Area: +// - Main Area = entire viewport. +// - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +// - Windows are generally trying to stay within the Work Area of their host viewport. +struct ImGuiViewport +{ + ImGuiID ID; // Unique identifier for the viewport + ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ + ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + float DpiScale; // 1.0f = 96 DPI = No extra scale. + ImGuiID ParentViewportId; // (Advanced) 0: no parent. Instruct the platform backend to setup a parent/child relationship between platform windows. + ImDrawData* DrawData; // The ImDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame(). + + // Platform/Backend Dependent Data + // Our design separate the Renderer and Platform backends to facilitate combining default backends with each others. + // When our create your own backend for a custom engine, it is possible that both Renderer and Platform will be handled + // by the same system and you may not need to use all the UserData/Handle fields. + // The library never uses those fields, they are merely storage to facilitate backend implementation. + void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function. + void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function. + void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GLFWWindow*, SDL_Window*) + void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms), when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*) + bool PlatformWindowCreated; // Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. + bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) + bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) + bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) + + ImGuiViewport() { memset(this, 0, sizeof(*this)); } + ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } + + // Helpers + ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } + ImVec2 GetWorkCenter() const { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Platform Dependent Interfaces (for e.g. multi-viewport support) +//----------------------------------------------------------------------------- +// [BETA] (Optional) This is completely optional, for advanced users! +// If you are new to Dear ImGui and trying to integrate it into your engine, you can probably ignore this for now. +// +// This feature allows you to seamlessly drag Dear ImGui windows outside of your application viewport. +// This is achieved by creating new Platform/OS windows on the fly, and rendering into them. +// Dear ImGui manages the viewport structures, and the backend create and maintain one Platform/OS window for each of those viewports. +// +// See Glossary https://github.com/ocornut/imgui/wiki/Glossary for details about some of the terminology. +// See Thread https://github.com/ocornut/imgui/issues/1542 for gifs, news and questions about this evolving feature. +// +// About the coordinates system: +// - When multi-viewports are enabled, all Dear ImGui coordinates become absolute coordinates (same as OS coordinates!) +// - So e.g. ImGui::SetNextWindowPos(ImVec2(0,0)) will position a window relative to your primary monitor! +// - If you want to position windows relative to your main application viewport, use ImGui::GetMainViewport()->Pos as a base position. +// +// Steps to use multi-viewports in your application, when using a default backend from the examples/ folder: +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: The backend initialization will setup all necessary ImGuiPlatformIO's functions and update monitors info every frame. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// Steps to use multi-viewports in your application, when using a custom backend: +// - Important: THIS IS NOT EASY TO DO and comes with many subtleties not described here! +// It's also an experimental feature, so some of the requirements may evolve. +// Consider using default backends if you can. Either way, carefully follow and refer to examples/ backends for details. +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: Hook ImGuiPlatformIO's Platform_* and Renderer_* callbacks (see below). +// Set 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports' and 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports'. +// Update ImGuiPlatformIO's Monitors list every frame. +// Update MousePos every frame, in absolute coordinates. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// You may skip calling RenderPlatformWindowsDefault() if its API is not convenient for your needs. Read comments below. +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// About ImGui::RenderPlatformWindowsDefault(): +// - This function is a mostly a _helper_ for the common-most cases, and to facilitate using default backends. +// - You can check its simple source code to understand what it does. +// It basically iterates secondary viewports and call 4 functions that are setup in ImGuiPlatformIO, if available: +// Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers() +// Those functions pointers exists only for the benefit of RenderPlatformWindowsDefault(). +// - If you have very specific rendering needs (e.g. flipping multiple swap-chain simultaneously, unusual sync/threading issues, etc.), +// you may be tempted to ignore RenderPlatformWindowsDefault() and write customized code to perform your renderingg. +// You may decide to setup the platform_io's *RenderWindow and *SwapBuffers pointers and call your functions through those pointers, +// or you may decide to never setup those pointers and call your code directly. They are a convenience, not an obligatory interface. +//----------------------------------------------------------------------------- + +// (Optional) Access via ImGui::GetPlatformIO() +struct ImGuiPlatformIO +{ + //------------------------------------------------------------------ + // Input - Backend interface/functions + Monitor List + //------------------------------------------------------------------ + + // (Optional) Platform functions (e.g. Win32, GLFW, SDL2) + // For reference, the second column shows which function are generally calling the Platform Functions: + // N = ImGui::NewFrame() ~ beginning of the dear imgui frame: read info from platform/OS windows (latest size/position) + // F = ImGui::Begin(), ImGui::EndFrame() ~ during the dear imgui frame + // U = ImGui::UpdatePlatformWindows() ~ after the dear imgui frame: create and update all platform/OS windows + // R = ImGui::RenderPlatformWindowsDefault() ~ render + // D = ImGui::DestroyPlatformWindows() ~ shutdown + // The general idea is that NewFrame() we will read the current Platform/OS state, and UpdatePlatformWindows() will write to it. + // + // The functions are designed so we can mix and match 2 imgui_impl_xxxx files, one for the Platform (~window/input handling), one for Renderer. + // Custom engine backends will often provide both Platform and Renderer interfaces and so may not need to use all functions. + // Platform functions are typically called before their Renderer counterpart, apart from Destroy which are called the other way. + + // Platform function --------------------------------------------------- Called by ----- + void (*Platform_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create a new platform window for the given viewport + void (*Platform_DestroyWindow)(ImGuiViewport* vp); // N . U . D // + void (*Platform_ShowWindow)(ImGuiViewport* vp); // . . U . . // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them before showing the window + void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos); // . . U . . // Set platform window position (given the upper-left corner of client area) + ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . // + void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.) + ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size + void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus + bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . // + bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily + void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* str); // . . U . . // Set platform window title (given an UTF-8 string) + void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); // . . U . . // (Optional) Setup global transparency (not per-pixel transparency) + void (*Platform_UpdateWindow)(ImGuiViewport* vp); // . . U . . // (Optional) Called by UpdatePlatformWindows(). Optional hook to allow the platform backend from doing general book-keeping every frame. + void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Main rendering (platform side! This is often unused, or just setting a "current" context for OpenGL bindings). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers (platform side! This is often unused!). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI. + void (*Platform_OnChangedViewport)(ImGuiViewport* vp); // . F . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. + int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); // (Optional) For a Vulkan Renderer to call into Platform code (since the surface creation needs to tie them both). + + // (Optional) Renderer functions (e.g. DirectX, OpenGL, Vulkan) + void (*Renderer_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create swap chain, frame buffers etc. (called after Platform_CreateWindow) + void (*Renderer_DestroyWindow)(ImGuiViewport* vp); // N . U . D // Destroy swap chain, frame buffers etc. (called before Platform_DestroyWindow) + void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Resize swap chain, frame buffers etc. (called after Platform_SetWindowSize) + void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Clear framebuffer, setup render target, then render the viewport->DrawData. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + + // (Optional) Monitor list + // - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + // - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. + ImVector Monitors; + + //------------------------------------------------------------------ + // Output - List of viewports to render into platform windows + //------------------------------------------------------------------ + + // Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + // (in the future we will attempt to organize this feature to remove the need for a "main viewport") + ImVector Viewports; // Main viewports, followed by all secondary viewports. + ImGuiPlatformIO() { memset(this, 0, sizeof(*this)); } // Zero clear +}; + +// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. +struct ImGuiPlatformMonitor +{ + ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) + ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. + float DpiScale; // 1.0f = 96 DPI + void* PlatformHandle; // Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) + ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; } +}; + +// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function. +struct ImGuiPlatformImeData +{ + bool WantVisible; // A widget wants the IME to be visible + ImVec2 InputPos; // Position of the input cursor + float InputLineHeight; // Line height + + ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete functions and types +// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) +// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. +//----------------------------------------------------------------------------- + +namespace ImGui +{ +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into legacy native key index. == io.KeyMap[key] +#else + static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END && "ImGuiKey and native_index was merged together and native_index is disabled by IMGUI_DISABLE_OBSOLETE_KEYIO. Please switch to ImGuiKey."); return key; } +#endif +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +namespace ImGui +{ + // OBSOLETED in 1.89.7 (from June 2023) + IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. + // OBSOLETED in 1.89.4 (from March 2023) + static inline void PushAllowKeyboardFocus(bool tab_stop) { PushTabStop(tab_stop); } + static inline void PopAllowKeyboardFocus() { PopTabStop(); } + // OBSOLETED in 1.89 (from August 2022) + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Use new ImageButton() signature (explicit item id, regular FramePadding) + // OBSOLETED in 1.88 (from May 2022) + static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. + static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. + // OBSOLETED in 1.86 (from November 2021) + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Calculate coarse clipping for large list of evenly sized items. Prefer using ImGuiListClipper. + // OBSOLETED in 1.85 (from August 2021) + static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } + + // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.81 (from February 2021) + //static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } + //static inline bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1) { float height = GetTextLineHeightWithSpacing() * ((height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f) + GetStyle().FramePadding.y * 2.0f; return BeginListBox(label, ImVec2(0.0f, height)); } // Helper to calculate size from items_count and height_in_items + //static inline void ListBoxFooter() { EndListBox(); } + //-- OBSOLETED in 1.79 (from August 2020) + //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! + //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. + //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //-- OBSOLETED in 1.77 and before + //static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.77 (from June 2020) + //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) + //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) + //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) + //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) + //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) + //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) + //-- OBSOLETED in 1.60 and before + //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) + //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) + //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //IMGUI_API bool Begin(char* name, bool* p_open, ImVec2 size_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags=0); // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017): Equivalent of using SetNextWindowSize(size, ImGuiCond_FirstUseEver) and SetNextWindowBgAlpha(). + //static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void SetNextWindowPosCenter(ImGuiCond c=0) { SetNextWindowPos(GetMainViewport()->GetCenter(), c, ImVec2(0.5f,0.5f)); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017): This was misleading and partly broken. You probably want to use the io.WantCaptureMouse flag instead. + //static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //-- OBSOLETED in 1.50 and before + //static inline bool CollapsingHeader(char* label, const char* str_id, bool framed = true, bool default_open = false) { return CollapsingHeader(label, (default_open ? (1 << 5) : 0)); } // OBSOLETED in 1.49 + //static inline ImFont*GetWindowFont() { return GetFont(); } // OBSOLETED in 1.48 + //static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETED in 1.48 + //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 +} + +// OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() +typedef ImDrawFlags ImDrawCornerFlags; +enum ImDrawCornerFlags_ +{ + ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit + ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). + ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. + ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. + ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. + ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 + ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, + ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, + ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, + ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, +}; + +// RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) +// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. +typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", but you may store only mods in there. +enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; +//typedef ImGuiKeyChord ImGuiKeyModFlags; // == int +//enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; + +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) +#if defined(IMGUI_DISABLE_METRICS_WINDOW) && !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) +#define IMGUI_DISABLE_DEBUG_TOOLS +#endif +#if defined(IMGUI_DISABLE_METRICS_WINDOW) && defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) +#error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/Plugin/include/reshade/reshade.hpp b/Plugin/include/reshade/reshade.hpp new file mode 100644 index 00000000..0b1b85c9 --- /dev/null +++ b/Plugin/include/reshade/reshade.hpp @@ -0,0 +1,346 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include "reshade_events.hpp" +#include "reshade_overlay.hpp" +#include +#include + +// Current version of the ReShade API +#define RESHADE_API_VERSION 8 + +// Optionally import ReShade API functions when 'RESHADE_API_LIBRARY' is defined instead of using header-only mode +#if defined(RESHADE_API_LIBRARY) || defined(RESHADE_API_LIBRARY_EXPORT) + +#ifdef RESHADE_API_LIBRARY_EXPORT + #define RESHADE_API_LIBRARY_DECLSPEC extern "C" __declspec(dllexport) +#else + #define RESHADE_API_LIBRARY_DECLSPEC extern "C" __declspec(dllimport) +#endif + +RESHADE_API_LIBRARY_DECLSPEC void ReShadeLogMessage(HMODULE module, int level, const char *message); + +RESHADE_API_LIBRARY_DECLSPEC void ReShadeGetBasePath(char *path, size_t *path_size); + +RESHADE_API_LIBRARY_DECLSPEC bool ReShadeGetConfigValue(HMODULE module, reshade::api::effect_runtime *runtime, const char *section, const char *key, char *value, size_t *value_size); +RESHADE_API_LIBRARY_DECLSPEC void ReShadeSetConfigValue(HMODULE module, reshade::api::effect_runtime *runtime, const char *section, const char *key, const char *value); + +RESHADE_API_LIBRARY_DECLSPEC bool ReShadeRegisterAddon(HMODULE module, uint32_t api_version); +RESHADE_API_LIBRARY_DECLSPEC void ReShadeUnregisterAddon(HMODULE module); + +RESHADE_API_LIBRARY_DECLSPEC void ReShadeRegisterEvent(reshade::addon_event ev, void *callback); +RESHADE_API_LIBRARY_DECLSPEC void ReShadeUnregisterEvent(reshade::addon_event ev, void *callback); + +RESHADE_API_LIBRARY_DECLSPEC void ReShadeRegisterOverlay(const char *title, void(*callback)(reshade::api::effect_runtime *runtime)); +RESHADE_API_LIBRARY_DECLSPEC void ReShadeUnregisterOverlay(const char *title, void(*callback)(reshade::api::effect_runtime *runtime)); + +#else + +// Use the kernel32 variant of module enumeration functions so it can be safely called from 'DllMain' +extern "C" BOOL WINAPI K32EnumProcessModules(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded); + +namespace reshade { namespace internal +{ + /// + /// Gets the handle to the ReShade module. + /// + inline HMODULE get_reshade_module_handle(HMODULE reshade_module = nullptr) + { + static HMODULE handle = reshade_module; + if (handle == nullptr) + { + HMODULE modules[1024]; DWORD num = 0; + if (K32EnumProcessModules(GetCurrentProcess(), modules, sizeof(modules), &num)) + { + if (num > sizeof(modules)) + num = sizeof(modules); + + for (DWORD i = 0; i < num / sizeof(HMODULE); ++i) + { + if (GetProcAddress(modules[i], "ReShadeRegisterAddon") && + GetProcAddress(modules[i], "ReShadeUnregisterAddon")) + { + handle = modules[i]; + break; + } + } + } + } + return handle; + } + + /// + /// Gets the handle to the current add-on module. + /// + inline HMODULE get_current_module_handle(HMODULE addon_module = nullptr) + { + static HMODULE handle = addon_module; + return handle; + } +} } + +#endif + +namespace reshade +{ + /// + /// Available log severity levels. + /// + enum class log_level + { + error = 1, + warning = 2, + info = 3, + debug = 4 + }; + + /// + /// Writes a message to ReShade's log. + /// + /// Severity level. + /// A null-terminated message string. + inline void log_message(log_level level, const char *message) + { +#if defined(RESHADE_API_LIBRARY) || defined(RESHADE_API_LIBRARY_EXPORT) + ReShadeLogMessage(nullptr, static_cast(level), message); +#else + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeLogMessage")); + func(internal::get_current_module_handle(), static_cast(level), message); +#endif + } + + /// + /// Gets the file path ReShade uses to resolve relative paths. + /// + /// Pointer to a string buffer that is filled with the file path to the preset, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + inline void get_reshade_base_path(char *path, size_t *path_size) + { +#if defined(RESHADE_API_LIBRARY) || defined(RESHADE_API_LIBRARY_EXPORT) + ReShadeGetBasePath(path, path_size); +#else + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeGetBasePath")); + func(path, path_size); +#endif + } + + /// + /// Gets a value from one of ReShade's config files. + /// + /// Optional effect runtime to use the config file from, or to use the global config file. + /// Name of the config section. + /// Name of the config value. + /// Pointer to a string buffer that is filled with the config value, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + /// if the specified config value exists, otherwise. + inline bool get_config_value(api::effect_runtime *runtime, const char *section, const char *key, char *value, size_t *value_size) + { +#if defined(RESHADE_API_LIBRARY) || defined(RESHADE_API_LIBRARY_EXPORT) + return ReShadeGetConfigValue(nullptr, runtime, section, key, value, value_size); +#else + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeGetConfigValue")); + return func(internal::get_current_module_handle(), runtime, section, key, value, value_size); +#endif + } +#if _HAS_CXX17 + template + inline bool get_config_value(api::effect_runtime *runtime, const char *section, const char *key, T &value) + { + char value_string[32]; size_t value_length = sizeof(value_string) - 1; + if (!get_config_value(runtime, section, key, value_string, &value_length)) + return false; + return std::from_chars(value_string, value_string + value_length, value).ec == std::errc {}; + } + template <> + inline bool get_config_value(api::effect_runtime *runtime, const char *section, const char *key, bool &value) + { + int value_int = 0; + if (!get_config_value(runtime, section, key, value_int)) + return false; + value = (value_int != 0); + return true; + } +#endif + + /// + /// Sets and saves a value in one of ReShade's config files. + /// + /// Optional effect runtime to use the config file from, or to use the global config file. + /// Name of the config section. + /// Name of the config value. + /// Config value to set. + inline void set_config_value(api::effect_runtime *runtime, const char *section, const char *key, const char *value) + { +#if defined(RESHADE_API_LIBRARY) || defined(RESHADE_API_LIBRARY_EXPORT) + ReShadeSetConfigValue(nullptr, runtime, section, key, value); +#else + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeSetConfigValue")); + func(internal::get_current_module_handle(), runtime, section, key, value); +#endif + } +#if _HAS_CXX17 + template + inline void set_config_value(api::effect_runtime *runtime, const char *section, const char *key, const T &value) + { + char value_string[32] = ""; + std::to_chars(value_string, value_string + sizeof(value_string) - 1, value); + set_config_value(runtime, section, key, static_cast(value_string)); + } + template <> + inline void set_config_value(api::effect_runtime *runtime, const char *section, const char *key, const bool &value) + { + set_config_value(runtime, section, key, value ? 1 : 0); + } +#endif + + /// + /// Registers this module as an add-on with ReShade. + /// Call this in 'AddonInit' or 'DllMain' during process attach, before any of the other API functions! + /// + /// Handle of the current module. + /// Handle of the ReShade module in the process, or to find it automatically. + inline bool register_addon(HMODULE addon_module, [[maybe_unused]] HMODULE reshade_module = nullptr) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON) + return ReShadeRegisterAddon(addon_module, RESHADE_API_VERSION); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + addon_module = internal::get_current_module_handle(addon_module); + reshade_module = internal::get_reshade_module_handle(reshade_module); + + if (reshade_module == nullptr) + return false; + + const auto func = reinterpret_cast( + GetProcAddress(reshade_module, "ReShadeRegisterAddon")); + // Check that the ReShade module supports the used API + if (func == nullptr || !func(addon_module, RESHADE_API_VERSION)) + return false; + +#if defined(IMGUI_VERSION_NUM) + const auto imgui_func = reinterpret_cast( + GetProcAddress(reshade_module, "ReShadeGetImGuiFunctionTable")); + // Check that the ReShade module was built with Dear ImGui support and supports the used version + if (imgui_func == nullptr || !(imgui_function_table_instance() = imgui_func(IMGUI_VERSION_NUM))) + return false; +#endif + + return true; +#else + UNREFERENCED_PARAMETER(addon_module); + UNREFERENCED_PARAMETER(reshade_module); + return false; +#endif + } + /// + /// Unregisters this module. + /// Call this in 'AddonUninit' or 'DllMain' during process detach, after any of the other API functions. + /// + /// Handle of the current module. + /// Handle of the ReShade module in the process, or to find it automatically. + inline void unregister_addon(HMODULE addon_module, [[maybe_unused]] HMODULE reshade_module = nullptr) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON) + ReShadeUnregisterAddon(addon_module); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + addon_module = internal::get_current_module_handle(addon_module); + reshade_module = internal::get_reshade_module_handle(reshade_module); + + if (reshade_module == nullptr) + return; + + const auto func = reinterpret_cast( + GetProcAddress(reshade_module, "ReShadeUnregisterAddon")); + if (func != nullptr) + func(addon_module); +#else + UNREFERENCED_PARAMETER(addon_module); + UNREFERENCED_PARAMETER(reshade_module); +#endif + } + + /// + /// Registers a callback for the specified event (via template) with ReShade. + /// The callback function is then called whenever the application performs a task associated with this event (see also the enumeration). + /// + /// Pointer to the callback function. + template + inline void register_event(typename reshade::addon_event_traits::decl callback) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON) + ReShadeRegisterEvent(ev, static_cast(callback)); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeRegisterEvent")); + if (func != nullptr) + func(ev, static_cast(callback)); +#else + UNREFERENCED_PARAMETER(callback); +#endif + } + /// + /// Unregisters a callback for the specified event (via template) that was previously registered via . + /// + /// Pointer to the callback function. + template + inline void unregister_event(typename reshade::addon_event_traits::decl callback) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON) + ReShadeUnregisterEvent(ev, static_cast(callback)); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeUnregisterEvent")); + if (func != nullptr) + func(ev, static_cast(callback)); +#else + UNREFERENCED_PARAMETER(callback); +#endif + } + + /// + /// Registers an overlay with ReShade. + /// The callback function is then called when the overlay is visible and allows adding Dear ImGui widgets for user interaction. + /// + /// Null-terminated title string, or to register a settings overlay for this add-on. + /// Pointer to the callback function. + inline void register_overlay(const char *title, void(*callback)(reshade::api::effect_runtime *runtime)) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON && RESHADE_GUI) + ReShadeRegisterOverlay(title, callback); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeRegisterOverlay")); + if (func != nullptr) + func(title, callback); +#else + UNREFERENCED_PARAMETER(title); + UNREFERENCED_PARAMETER(callback); +#endif + } + /// + /// Unregisters an overlay that was previously registered via . + /// + /// Null-terminated title string. + /// Pointer to the callback function. + inline void unregister_overlay(const char *title, void(*callback)(reshade::api::effect_runtime *runtime)) + { +#if defined(RESHADE_API_LIBRARY) || (defined(RESHADE_API_LIBRARY_EXPORT) && RESHADE_ADDON && RESHADE_GUI) + ReShadeUnregisterOverlay(title, callback); +#elif !defined(RESHADE_API_LIBRARY_EXPORT) + static const auto func = reinterpret_cast( + GetProcAddress(internal::get_reshade_module_handle(), "ReShadeUnregisterOverlay")); + if (func != nullptr) + func(title, callback); +#else + UNREFERENCED_PARAMETER(title); + UNREFERENCED_PARAMETER(callback); +#endif + } +} diff --git a/Plugin/include/reshade/reshade_api.hpp b/Plugin/include/reshade/reshade_api.hpp new file mode 100644 index 00000000..4691bd4d --- /dev/null +++ b/Plugin/include/reshade/reshade_api.hpp @@ -0,0 +1,726 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include "reshade_api_device.hpp" + +namespace reshade { namespace api +{ + /// + /// An opaque handle to a technique in an effect. + /// + /// + /// This handle is only valid until effects are next reloaded again (). + /// + RESHADE_DEFINE_HANDLE(effect_technique); + /// + /// An opaque handle to a texture variable in an effect. + /// + /// + /// This handle is only valid until effects are next reloaded again (). + /// + RESHADE_DEFINE_HANDLE(effect_texture_variable); + /// + /// An opaque handle to a uniform variable in an effect. + /// + /// + /// This handle is only valid until effects are next reloaded again (). + /// + RESHADE_DEFINE_HANDLE(effect_uniform_variable); + + /// + /// A ReShade effect runtime, used to control effects. + /// A separate runtime is instantiated for every swap chain. + /// + struct __declspec(novtable) effect_runtime : public swapchain + { + /// + /// Gets the main graphics command queue associated with this effect runtime. + /// This may potentially be different from the presentation queue and should be used to execute graphics commands on. + /// + virtual command_queue *get_command_queue() = 0; + + /// + /// Applies post-processing effects to the specified render targets and prevents the usual rendering of effects before swap chain presentation of the current frame. + /// This can be used to force ReShade to render effects at a certain point during the frame to e.g. avoid effects being applied to user interface elements of the application. + /// + /// + /// The resource the render target views point to has to be in the state. + /// This call may modify current state on the command list (pipeline, render targets, descriptor tables, ...), so it may be necessary for an add-on to backup and restore state around it if the application does not bind all state again afterwards already. + /// Calling this with set to zero will cause nothing to be rendered, but uniform variables to still be updated. + /// + /// Command list to add effect rendering commands to. + /// Render target view to use for passes that write to the back buffer with SRGBWriteEnabled state set to . + /// Render target view to use for passes that write to the back buffer with SRGBWriteEnabled state set to , or zero in which case the view from is used. + virtual void render_effects(command_list *cmd_list, resource_view rtv, resource_view rtv_srgb = { 0 }) = 0; + + /// + /// Captures a screenshot of the current back buffer resource and returns its image data in 32 bits-per-pixel RGBA format. + /// + /// Pointer to an array of width * height * 4 bytes the image data is written to. + virtual bool capture_screenshot(uint8_t *pixels) = 0; + + /// + /// Gets the current buffer dimensions of the swap chain. + /// + virtual void get_screenshot_width_and_height(uint32_t *out_width, uint32_t *out_height) const = 0; + + /// + /// Gets the current status of the specified key. + /// + /// The virtual key code to check. + /// if the key is currently pressed down, otherwise. + virtual bool is_key_down(uint32_t keycode) const = 0; + /// + /// Gets whether the specified key was pressed this frame. + /// + /// The virtual key code to check. + /// if the key was pressed this frame, otherwise. + virtual bool is_key_pressed(uint32_t keycode) const = 0; + /// + /// Gets whether the specified key was released this frame. + /// + /// The virtual key code to check. + /// if the key was released this frame, otherwise. + virtual bool is_key_released(uint32_t keycode) const = 0; + /// + /// Gets the current status of the specified mouse button. + /// + /// The mouse button index to check (0 = left, 1 = middle, 2 = right). + /// if the mouse button is currently pressed down, otherwise. + virtual bool is_mouse_button_down(uint32_t button) const = 0; + /// + /// Gets whether the specified mouse button was pressed this frame. + /// + /// The mouse button index to check (0 = left, 1 = middle, 2 = right). + /// if the mouse button was pressed this frame, otherwise. + virtual bool is_mouse_button_pressed(uint32_t button) const = 0; + /// + /// Gets whether the specified mouse button was released this frame. + /// + /// The mouse button index to check (0 = left, 1 = middle, 2 = right). + /// if the mouse button was released this frame, otherwise. + virtual bool is_mouse_button_released(uint32_t button) const = 0; + + /// + /// Gets the current absolute position of the mouse cursor in screen coordinates. + /// + /// Pointer to a variable that is set to the X coordinate of the current cursor position. + /// Pointer to a variable that is set to the Y coordinate of the current cursor position. + /// Optional pointer to a variable that is set to the mouse wheel delta since the last frame. + virtual void get_mouse_cursor_position(uint32_t *out_x, uint32_t *out_y, int16_t *out_wheel_delta = nullptr) const = 0; + + /// + /// Enumerates all uniform variables of loaded effects and calls the specified function with a handle for each one. + /// + /// File name of the effect file to enumerate uniform variables from, or to enumerate those of all loaded effects. + /// Function to call for every uniform variable. + /// Optional pointer passed to the callback function. + virtual void enumerate_uniform_variables(const char *effect_name, void(*callback)(effect_runtime *runtime, effect_uniform_variable variable, void *user_data), void *user_data) = 0; + /// + /// Enumerates all uniform variables of loaded effects and calls the specified callback function with a handle for each one. + /// + /// File name of the effect file to enumerate uniform variables from, or to enumerate those of all loaded effects. + /// Function to call for every uniform variable. + template + inline void enumerate_uniform_variables(const char *effect_name, F lambda) + { + enumerate_uniform_variables(effect_name, [](effect_runtime *runtime, effect_uniform_variable variable, void *user_data) { static_cast(user_data)->operator()(runtime, variable); }, &lambda); + } + + /// + /// Finds a specific uniform variable in the loaded effects and returns a handle to it. + /// + /// File name of the effect file the variable is declared in, or to search in all loaded effects. + /// Name of the uniform variable declaration to find. + /// Opaque handle to the uniform variable, or zero in case it was not found. + virtual effect_uniform_variable find_uniform_variable(const char *effect_name, const char *variable_name) const = 0; + + /// + /// Gets information about the data type of a uniform . + /// + /// Opaque handle to the uniform variable. + /// Optional pointer to a variable that is set to the base type of the uniform variable (, , or ). + /// Optional pointer to a variable that is set to the number of vector rows of the uniform variable type. + /// Optional pointer to a variable that is set to the number of matrix column of the uniform variable type. + /// Optional pointer to a variable that is set to the number of array elements of the uniform variable type. + virtual void get_uniform_variable_type(effect_uniform_variable variable, format *out_base_type, uint32_t *out_rows = nullptr, uint32_t *out_columns = nullptr, uint32_t *out_array_length = nullptr) const = 0; + + /// + /// Gets the name of a uniform . + /// + /// Opaque handle to the uniform variable. + /// Pointer to a string buffer that is filled with the name of the uniform variable, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_uniform_variable_name(effect_uniform_variable variable, char *name, size_t *name_size) const = 0; + template + inline void get_uniform_variable_name(effect_uniform_variable variable, char(&name)[SIZE]) const + { + size_t name_size = SIZE; + get_uniform_variable_name(variable, name, &name_size); + } + + /// + /// Gets the value from an annotation attached to the specified uniform as boolean values. + /// + /// Opaque handle to the uniform variable. + /// Name of the annotation. + /// Pointer to an array of booleans that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_bool_from_uniform_variable(effect_uniform_variable variable, const char *name, bool *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified uniform as floating-point values. + /// + /// Opaque handle to the uniform variable. + /// Name of the annotation. + /// Pointer to an array of floating-points that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_float_from_uniform_variable(effect_uniform_variable variable, const char *name, float *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified uniform as signed integer values. + /// + /// Opaque handle to the uniform variable. + /// Name of the annotation. + /// Pointer to an array of signed integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_int_from_uniform_variable(effect_uniform_variable variable, const char *name, int32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified uniform as unsigned integer values. + /// + /// Opaque handle to the uniform variable. + /// Name of the annotation. + /// Pointer to an array of unsigned integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_uint_from_uniform_variable(effect_uniform_variable variable, const char *name, uint32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from a string annotation attached to the specified uniform . + /// + /// Opaque handle to the uniform variable. + /// Name of the annotation. + /// Pointer to a string buffer that is filled with the value of the annotation, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual bool get_annotation_string_from_uniform_variable(effect_uniform_variable variable, const char *name, char *value, size_t *value_size) const = 0; + template + inline bool get_annotation_string_from_uniform_variable(effect_uniform_variable variable, const char *name, char(&value)[SIZE]) const + { + size_t value_size = SIZE; + return get_annotation_string_from_uniform_variable(variable, name, value, &value_size); + } + + /// + /// Gets the value of the specified uniform as boolean values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of booleans that is filled with the values of this uniform variable. + /// Number of values to read. + /// Array offset to start reading values from when this uniform variable is an array variable. + virtual void get_uniform_value_bool(effect_uniform_variable variable, bool *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value of the specified uniform as floating-point values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of floating-points that is filled with the values of this uniform variable. + /// Number of values to read. + /// Array offset to start reading values from when this uniform variable is an array variable. + virtual void get_uniform_value_float(effect_uniform_variable variable, float *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value of the specified uniform as signed integer values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of signed integers that is filled with the values of this uniform variable. + /// Number of values to read. + /// Array offset to start reading values from when this uniform variable is an array variable. + virtual void get_uniform_value_int(effect_uniform_variable variable, int32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value of the specified uniform as unsigned integer values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of unsigned integers that is filled with the values of this uniform variable. + /// Number of values to read. + /// Array offset to start reading values from when this uniform variable is an array variable. + virtual void get_uniform_value_uint(effect_uniform_variable variable, uint32_t *values, size_t count, size_t array_index = 0) const = 0; + + /// + /// Sets the value of the specified uniform as boolean values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of booleans that are used to update this uniform variable. + /// Number of values to write. + /// Array offset to start writing values to when this uniform variable is an array variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + virtual void set_uniform_value_bool(effect_uniform_variable variable, const bool *values, size_t count, size_t array_index = 0) = 0; + /// + /// Sets the value of the specified uniform as a vector of boolean values. + /// + /// Opaque handle to the uniform variable. + /// Value of the first component in the vector that is used to update this uniform variable. + /// Optional value of the second component in the vector that is used to update this uniform variable. + /// Optional value of the third component in the vector that is used to update this uniform variable. + /// Optional value of the fourth component in the vector that is used to update this uniform variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + inline void set_uniform_value_bool(effect_uniform_variable variable, bool x, bool y = bool(0), bool z = bool(0), bool w = bool(0)) + { + const bool values[4] = { x, y, z, w }; + set_uniform_value_bool(variable, values, 4); + } + /// + /// Sets the value of the specified uniform as floating-point values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of floating-points that are used to update this uniform variable. + /// Number of values to write. + /// Array offset to start writing values to when this uniform variable is an array variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + virtual void set_uniform_value_float(effect_uniform_variable variable, const float *values, size_t count, size_t array_index = 0) = 0; + /// + /// Sets the value of the specified uniform as a vector of floating-point values. + /// + /// Opaque handle to the uniform variable. + /// Value of the first component in the vector that is used to update this uniform variable. + /// Optional value of the second component in the vector that is used to update this uniform variable. + /// Optional value of the third component in the vector that is used to update this uniform variable. + /// Optional value of the fourth component in the vector that is used to update this uniform variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + inline void set_uniform_value_float(effect_uniform_variable variable, float x, float y = float(0), float z = float(0), float w = float(0)) + { + const float values[4] = { x, y, z, w }; + set_uniform_value_float(variable, values, 4); + } + /// + /// Sets the value of the specified uniform as signed integer values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of signed integers that are used to update this uniform variable. + /// Number of values to write. + /// Array offset to start writing values to when this uniform variable is an array variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + virtual void set_uniform_value_int(effect_uniform_variable variable, const int32_t *values, size_t count, size_t array_index = 0) = 0; + /// + /// Sets the value of the specified uniform as a vector of signed integer values. + /// + /// Opaque handle to the uniform variable. + /// Value of the first component in the vector that is used to update this uniform variable. + /// Optional value of the second component in the vector that is used to update this uniform variable. + /// Optional value of the third component in the vector that is used to update this uniform variable. + /// Optional value of the fourth component in the vector that is used to update this uniform variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + inline void set_uniform_value_int(effect_uniform_variable variable, int32_t x, int32_t y = int32_t(0), int32_t z = int32_t(0), int32_t w = int32_t(0)) + { + const int32_t values[4] = { x, y, z, w }; + set_uniform_value_int(variable, values, 4); + } + /// + /// Sets the value of the specified uniform as unsigned integer values. + /// + /// Opaque handle to the uniform variable. + /// Pointer to an array of unsigned integers that are used to update this uniform variable. + /// Number of values to write. + /// Array offset to start writing values to when this uniform variable is an array variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + virtual void set_uniform_value_uint(effect_uniform_variable variable, const uint32_t *values, size_t count, size_t array_index = 0) = 0; + /// + /// Sets the value of the specified uniform as a vector of unsigned integer values. + /// + /// Opaque handle to the uniform variable. + /// Value of the first component in the vector that is used to update this uniform variable. + /// Optional value of the second component in the vector that is used to update this uniform variable. + /// Optional value of the third component in the vector that is used to update this uniform variable. + /// Optional value of the fourth component in the vector that is used to update this uniform variable. + /// Setting the uniform value won't result in a save of the current preset. To make sure the current preset with the changed value + /// is saved to disk, call + inline void set_uniform_value_uint(effect_uniform_variable variable, uint32_t x, uint32_t y = uint32_t(0), uint32_t z = uint32_t(0), uint32_t w = uint32_t(0)) + { + const uint32_t values[4] = { x, y, z, w }; + set_uniform_value_uint(variable, values, 4); + } + + /// + /// Enumerates all texture variables of loaded effects and calls the specified function with a handle for each one. + /// + /// File name of the effect file to enumerate texture variables from, or to enumerate those of all loaded effects. + /// Function to call for every texture variable. + /// Optional pointer passed to the callback function. + virtual void enumerate_texture_variables(const char *effect_name, void(*callback)(effect_runtime *runtime, effect_texture_variable variable, void *user_data), void *user_data) = 0; + /// + /// Enumerates all texture variables of loaded effects and calls the specified callback function with a handle for each one. + /// + /// File name of the effect file to enumerate texture variables from, or to enumerate those of all loaded effects. + /// Function to call for every texture variable. + template + inline void enumerate_texture_variables(const char *effect_name, F lambda) + { + enumerate_texture_variables(effect_name, [](effect_runtime *runtime, effect_texture_variable variable, void *user_data) { static_cast(user_data)->operator()(runtime, variable); }, &lambda); + } + + /// + /// Finds a specific texture variable in the loaded effects and returns a handle to it. + /// + /// File name of the effect file the variable is declared in, or to search in all loaded effects. + /// Name of the texture variable declaration to find. + /// Opaque handle to the texture variable, or zero in case it was not found. + virtual effect_texture_variable find_texture_variable(const char *effect_name, const char *variable_name) const = 0; + + /// + /// Gets the name of a texture . + /// + /// Opaque handle to the texture variable. + /// Pointer to a string buffer that is filled with the name of the texture variable, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_texture_variable_name(effect_texture_variable variable, char *name, size_t *name_size) const = 0; + template + inline void get_texture_variable_name(effect_texture_variable variable, char(&name)[SIZE]) const + { + size_t name_size = SIZE; + get_texture_variable_name(variable, name, &name_size); + } + + /// + /// Gets the value from an annotation attached to the specified texture as boolean values. + /// + /// Opaque handle to the texture variable. + /// Name of the annotation. + /// Pointer to an array of booleans that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_bool_from_texture_variable(effect_texture_variable variable, const char *name, bool *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified texture as floating-point values. + /// + /// Opaque handle to the texture variable. + /// Name of the annotation. + /// Pointer to an array of floating-points that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_float_from_texture_variable(effect_texture_variable variable, const char *name, float *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified texture as signed integer values. + /// + /// Opaque handle to the texture variable. + /// Name of the annotation. + /// Pointer to an array of signed integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_int_from_texture_variable(effect_texture_variable variable, const char *name, int32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified texture as unsigned integer values. + /// + /// Opaque handle to the texture variable. + /// Name of the annotation. + /// Pointer to an array of unsigned integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_uint_from_texture_variable(effect_texture_variable variable, const char *name, uint32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from a string annotation attached to the specified texture . + /// + /// Opaque handle to the texture variable. + /// Name of the annotation. + /// Pointer to a string buffer that is filled with the value of the annotation, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual bool get_annotation_string_from_texture_variable(effect_texture_variable variable, const char *name, char *value, size_t *value_size) const = 0; + template + inline bool get_annotation_string_from_texture_variable(effect_texture_variable variable, const char *name, char(&value)[SIZE]) const + { + size_t value_size = SIZE; + return get_annotation_string_from_texture_variable(variable, name, value, &value_size); + } + + /// + /// Uploads 32 bits-per-pixel RGBA image data to the specified texture . + /// + /// Opaque handle to the texture variable. + /// Width of the image data. + /// Height of the image data. + /// Pointer to an array of width * height * 4 bytes the image data is read from. + virtual void update_texture(effect_texture_variable variable, const uint32_t width, const uint32_t height, const uint8_t *pixels) = 0; + + /// + /// Gets the shader resource view that is bound to the specified texture . + /// + /// Opaque handle to the texture variable. + /// Pointer to a variable that is set to the shader resource view. + /// Pointer to a variable that is set to the sRGB shader resource view. + virtual void get_texture_binding(effect_texture_variable variable, resource_view *out_srv, resource_view *out_srv_srgb = nullptr) const = 0; + + /// + /// Binds a new shader resource view to all texture variables that use the specified . + /// + /// + /// The resource the shader resource views point to has to be in the state at the time is executed. + /// + /// ReShade FX semantic to filter textures to update by (texture name : SEMANTIC). + /// Shader resource view to use for samplers with SRGBTexture state set to . + /// Shader resource view to use for samplers with SRGBTexture state set to , or zero in which case the view from is used. + virtual void update_texture_bindings(const char *semantic, resource_view srv, resource_view srv_srgb = { 0 }) = 0; + + /// + /// Enumerates all techniques of loaded effects and calls the specified function with a handle for each one. + /// + /// File name of the effect file to enumerate techniques from, or to enumerate those of all loaded effects. + /// Function to call for every technique. + /// Optional pointer passed to the callback function. + virtual void enumerate_techniques(const char *effect_name, void(*callback)(effect_runtime *runtime, effect_technique technique, void *user_data), void *user_data) = 0; + /// + /// Enumerates all techniques of loaded effects and calls the specified callback function with a handle for each one. + /// + /// File name of the effect file to enumerate techniques from, or to enumerate those of all loaded effects. + /// Function to call for every technique. + template + inline void enumerate_techniques(const char *effect_name, F lambda) + { + enumerate_techniques(effect_name, [](effect_runtime *runtime, effect_technique technique, void *user_data) { static_cast(user_data)->operator()(runtime, technique); }, &lambda); + } + + /// + /// Finds a specific technique in the loaded effects and returns a handle to it. + /// + /// File name of the effect file the technique is declared in, or to search in all loaded effects. + /// Name of the technique to find. + /// Opaque handle to the technique, or zero in case it was not found. + virtual effect_technique find_technique(const char *effect_name, const char *technique_name) = 0; + + /// + /// Gets the name of a . + /// + /// Opaque handle to the technique. + /// Pointer to a string buffer that is filled with the name of the technique, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_technique_name(effect_technique technique, char *name, size_t *name_size) const = 0; + template + inline void get_technique_name(effect_technique technique, char(&name)[SIZE]) const + { + size_t name_size = SIZE; + get_technique_name(technique, name, &name_size); + } + + /// + /// Gets the value from an annotation attached to the specified as boolean values. + /// + /// Opaque handle to the technique. + /// Name of the annotation. + /// Pointer to an array of booleans that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_bool_from_technique(effect_technique technique, const char *name, bool *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified as floating-point values. + /// + /// Opaque handle to the technique. + /// Name of the annotation. + /// Pointer to an array of floating-points that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_float_from_technique(effect_technique technique, const char *name, float *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified as signed integer values. + /// + /// Opaque handle to the technique. + /// Name of the annotation. + /// Pointer to an array of signed integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_int_from_technique(effect_technique technique, const char *name, int32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from an annotation attached to the specified as unsigned integer values. + /// + /// Opaque handle to the technique. + /// Name of the annotation. + /// Pointer to an array of unsigned integers that is filled with the values of the annotation. + /// Number of values to read. + /// Array offset to start reading values from when the annotation is an array. + virtual bool get_annotation_uint_from_technique(effect_technique technique, const char *name, uint32_t *values, size_t count, size_t array_index = 0) const = 0; + /// + /// Gets the value from a string annotation attached to the specified . + /// + /// Opaque handle to the technique. + /// Name of the annotation. + /// Pointer to a string buffer that is filled with the value of the annotation, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual bool get_annotation_string_from_technique(effect_technique technique, const char *name, char *value, size_t *value_size) const = 0; + template + inline bool get_annotation_string_from_technique(effect_technique technique, const char *name, char(&value)[SIZE]) const + { + size_t value_size = SIZE; + return get_annotation_string_from_technique(technique, name, value, &value_size); + } + + /// + /// Gets the state of a . + /// + /// Opaque handle to the technique. + virtual bool get_technique_state(effect_technique technique) const = 0; + /// + /// Enables or disables the specified . + /// + /// Opaque handle to the technique. + /// Set to to enable the technique, or to disable it. + virtual void set_technique_state(effect_technique technique, bool enabled) = 0; + + /// + /// Gets the value of a preprocessor definition. + /// + /// Name of the definition. + /// Pointer to a string buffer that is filled with the value of the definition, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual bool get_preprocessor_definition(const char *name, char *value, size_t *value_size) const = 0; + template + inline bool get_preprocessor_definition(const char *name, char(&value)[SIZE]) const + { + size_t value_size = SIZE; + return get_preprocessor_definition(name, value, &value_size); + } + /// + /// Defines a preprocessor definition to the specified . + /// + /// Name of the definition. + /// Value of the definition. + virtual void set_preprocessor_definition(const char *name, const char *value) = 0; + + /// + /// Applies a to the specified render targets (regardless of the state of this technique). + /// + /// + /// The width and height of the specified render target should match those used to render all other effects! + /// The resource the render target views point to has to be in the state. + /// This call may modify current state on the command list (pipeline, render targets, descriptor tables, ...), so it may be necessary for an add-on to backup and restore state around it if the application does not bind all state again afterwards already. + /// + /// Opaque handle to the technique. + /// Command list to add effect rendering commands to. + /// Render target view to use for passes that write to the back buffer with SRGBWriteEnabled state set to . + /// Render target view to use for passes that write to the back buffer with SRGBWriteEnabled state set to , or zero in which case the view from is used. + virtual void render_technique(effect_technique technique, command_list *cmd_list, resource_view rtv, resource_view rtv_srgb = { 0 }) = 0; + + /// + /// Gets whether effects are enabled or disabled. + /// + virtual bool get_effects_state() const = 0; + /// + /// Enables or disables all effects. + /// + /// Set to to enable effects, or to disable them. + virtual void set_effects_state(bool enabled) = 0; + + /// + /// Gets the file path to the currently active preset. + /// + /// Pointer to a string buffer that is filled with the file path to the preset, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_current_preset_path(char *path, size_t *path_size) const = 0; + template + inline void get_current_preset_path(char(&path)[SIZE]) const + { + size_t path_size = SIZE; + get_current_preset_path(path, &path_size); + } + /// + /// Saves the currently active preset and then switches to the specified new preset. + /// + /// File path to the preset to switch to. + virtual void set_current_preset_path(const char *path) = 0; + + /// + /// Changes the rendering order of loaded techniques to that of the specified technique list. + /// + /// Number of handles in the technique list. + /// Array of techniques in the order they should be rendered in. + virtual void reorder_techniques(size_t count, const effect_technique *techniques) = 0; + + /// + /// Makes ReShade block any keyboard and mouse input from reaching the game for the duration of the next frame. + /// Call this every frame for as long as input should be blocked. This can be used to ensure input is only applied to overlays created in a callback. + /// + virtual void block_input_next_frame() = 0; + + /// + /// Gets the virtual key code of the last key that was pressed. + /// + virtual uint32_t last_key_pressed() const = 0; + /// + /// Gets the virtual key code of the last key that was released. + /// + virtual uint32_t last_key_released() const = 0; + + /// + /// Gets the effect file name of a uniform . + /// + /// Opaque handle to the uniform variable. + /// Pointer to a string buffer that is filled with the effect file name of the uniform variable, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_uniform_variable_effect_name(effect_uniform_variable variable, char *effect_name, size_t *effect_name_size) const = 0; + template + inline void get_uniform_variable_effect_name(effect_uniform_variable variable, char(&effect_name)[SIZE]) const + { + size_t effect_name_size = SIZE; + get_uniform_variable_effect_name(variable, effect_name, &effect_name_size); + } + + /// + /// Gets the effect file name of a texture . + /// + /// Opaque handle to the texture variable. + /// Pointer to a string buffer that is filled with the effect file name of the texture variable, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_texture_variable_effect_name(effect_texture_variable variable, char *effect_name, size_t *effect_name_size) const = 0; + template + inline void get_texture_variable_effect_name(effect_texture_variable variable, char(&effect_name)[SIZE]) const + { + size_t effect_name_size = SIZE; + get_texture_variable_effect_name(variable, effect_name, &effect_name_size); + } + + /// + /// Gets the effect file name of a . + /// + /// Opaque handle to the technique. + /// Pointer to a string buffer that is filled with the effect file name of the technique, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and is set to the actual length of the string, including the null-terminator. + virtual void get_technique_effect_name(effect_technique technique, char *effect_name, size_t *effect_name_size) const = 0; + template + inline void get_technique_effect_name(effect_technique technique, char(&effect_name)[SIZE]) const + { + size_t effect_name_size = SIZE; + get_technique_effect_name(technique, effect_name, &effect_name_size); + } + + /// + /// Saves the current preset with the current state of the loaded techniques and uniform variables. + /// + virtual void save_current_preset() const = 0; + + /// + /// Gets the value of a preprocessor definition for the specified effect. + /// + /// File name of the effect file the preprocessor definition is defined for. + /// Name of the definition. + /// Pointer to a string buffer that is filled with the value of the definition, or to query the necessary size. + /// Pointer to an integer that contains the size of the string buffer and upon completion is set to the actual length of the string, including the null-terminator. + virtual bool get_preprocessor_definition_for_effect(const char *effect_name, const char *name, char *value, size_t *value_size) const = 0; + template + inline bool get_preprocessor_definition_for_effect(const char *effect_name, const char *name, char(&value)[SIZE]) const + { + size_t value_size = SIZE; + return get_preprocessor_definition_for_effect(effect_name, name, value, &value_size); + } + /// + /// Defines a preprocessor definition for the specified effect to the specified . + /// + /// File name of the effect file the preprocessor definition should be defined for. + /// Name of the definition. + /// Value of the definition. + virtual void set_preprocessor_definition_for_effect(const char *effect_name, const char *name, const char *value) = 0; + }; +} } diff --git a/Plugin/include/reshade/reshade_api_device.hpp b/Plugin/include/reshade/reshade_api_device.hpp new file mode 100644 index 00000000..92f8c3b3 --- /dev/null +++ b/Plugin/include/reshade/reshade_api_device.hpp @@ -0,0 +1,1017 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include "reshade_api_pipeline.hpp" + +namespace reshade { namespace api +{ + /// + /// The underlying render API a device is using, as returned by . + /// + enum class device_api + { + /// Direct3D 9 + /// https://docs.microsoft.com/windows/win32/direct3d9 + d3d9 = 0x9000, + /// Direct3D 10 + /// https://docs.microsoft.com/windows/win32/direct3d10 + d3d10 = 0xa000, + /// Direct3D 11 + /// https://docs.microsoft.com/windows/win32/direct3d11 + d3d11 = 0xb000, + /// Direct3D 12 + /// https://docs.microsoft.com/windows/win32/direct3d12 + d3d12 = 0xc000, + /// OpenGL + /// https://www.khronos.org/opengl/ + opengl = 0x10000, + /// Vulkan + /// https://www.khronos.org/vulkan/ + vulkan = 0x20000 + }; + + /// + /// The available features a device may support. + /// + enum class device_caps + { + /// + /// Specifies whether compute shaders are supported. + /// If this feature is not present, the stage and must not be used. + /// + compute_shader = 1, + /// + /// Specifies whether geometry shaders are supported. + /// If this feature is not present, the stage must not be used. + /// + geometry_shader, + /// + /// Specifies whether hull and domain (tessellation) shaders are supported. + /// If this feature is not present, the and stages must not be used. + /// + hull_and_domain_shader, + /// + /// Specifies whether logic operations are available in the blend state. + /// If this feature is not present, the and fields are ignored. + /// + logic_op, + /// + /// Specifies whether blend operations which take two sources are supported. + /// If this feature is not present, , , and must not be used. + /// + dual_source_blend, + /// + /// Specifies whether blend state is controlled independently per render target. + /// If this feature is not present, the blend state settings for all render targets must be identical. + /// + independent_blend, + /// + /// Specifies whether point and wireframe fill modes are supported. + /// If this feature is not present, and must not be used. + /// + fill_mode_non_solid, + /// + /// Specifies whether conservative rasterization is supported. + /// If this feature is not present, the field must be 0. + /// + conservative_rasterization, + /// + /// Specifies whether binding individual render target and depth-stencil resource views is supported. + /// If this feature is not present, must not be used (only render passes). + /// + bind_render_targets_and_depth_stencil, + /// + /// Specifies whther more than one viewport is supported. + /// If this feature is not present, the "first" and "count" parameters to and must be 0 and 1. + /// + multi_viewport, + /// + /// Specifies whether partial push constant updates are supported. + /// If this feature is not present, the "first" parameter to must be 0 and "count" must cover the entire constant range. + /// + partial_push_constant_updates, + /// + /// Specifies whether partial push descriptor updates are supported. + /// If this feature is not present, the "first" parameter to must be 0 and "count" must cover the entire descriptor range. + /// + partial_push_descriptor_updates, + /// + /// Specifies whether instancing is supported. + /// If this feature is not present, the "instance_count" and "first_instance" parameters to and must be 1 and 0. + /// + draw_instanced, + /// + /// Specifies whether indirect draw or dispatch calls are supported. + /// If this feature is not present, must not be used. + /// + draw_or_dispatch_indirect, + /// + /// Specifies whether copying between buffers is supported. + /// If this feature is not present, must not be used. + /// + copy_buffer_region, + /// + /// Specifies whether copying between buffers and textures is supported. + /// If this feature is not present, and must not be used. + /// + copy_buffer_to_texture, + /// + /// Specifies whether blitting between resources is supported. + /// If this feature is not present, the "source_box" and "dest_box" parameters to must have the same dimensions. + /// + blit, + /// + /// Specifies whether resolving a region of a resource rather than its entirety is supported. + /// If this feature is not present, the "source_box", "dest_x", "dest_y" and "dest_z" parameters to must be and zero. + /// + resolve_region, + /// + /// Specifies whether copying query results to a buffer is supported. + /// If this feature is not present, must not be used. + /// + copy_query_heap_results, + /// + /// Specifies whether comparison sampling is supported. + /// If this feature is not present, the field is ignored and the compare filter types have no effect. + /// + sampler_compare, + /// + /// Specifies whether anisotropic filtering is supported. + /// If this feature is not present, must not be used. + /// + sampler_anisotropic, + /// + /// Specifies whether combined sampler and resource view descriptors are supported. + /// If this feature is not present, must not be used. + /// + sampler_with_resource_view, + /// + /// Specifies whether resource sharing is supported. + /// If this feature is not present, must not be used. + /// + shared_resource, + /// + /// Specifies whether resource sharing with NT handles is supported. + /// If this feature is not present, must not be used. + /// + shared_resource_nt_handle + }; + + /// + /// The base class for objects provided by the ReShade API. + /// This lets you store and retrieve custom data with objects, e.g. to be able to communicate persistent information between event callbacks. + /// + struct __declspec(novtable) api_object + { + /// + /// Gets the underlying native object for this API object. + /// + /// + /// For this will be be a pointer to a 'IDirect3DDevice9', 'ID3D10Device', 'ID3D11Device' or 'ID3D12Device' object or a 'HGLRC' or 'VkDevice' handle.
+ /// For this will be a pointer to a 'ID3D11DeviceContext' (when recording), 'ID3D11CommandList' (when executing) or 'ID3D12GraphicsCommandList' object or a 'VkCommandBuffer' handle.
+ /// For this will be a pointer to a 'ID3D11DeviceContext' or 'ID3D12CommandQueue' object or a 'VkQueue' handle.
+ /// For this will be a pointer to a 'IDirect3DSwapChain9' or 'IDXGISwapChain' object or a 'HDC' or 'VkSwapchainKHR' handle. + ///
+ virtual uint64_t get_native() const = 0; + + /// + /// Gets a user-defined 64-bit value from the object that was previously set via , or zero if none associated with the specified exists. + /// + virtual void get_private_data(const uint8_t guid[16], uint64_t *data) const = 0; + /// + /// Stores a user-defined 64-bit value in the object and associates it with the specified . + /// + /// + /// This function may NOT be called concurrently from multiple threads! + /// + virtual void set_private_data(const uint8_t guid[16], const uint64_t data) = 0; + + /// + /// Gets a reference to user-defined data from the object that was previously allocated via . + /// + template inline T &get_private_data() const + { + uint64_t res; + get_private_data(reinterpret_cast(&__uuidof(T)), &res); + return *reinterpret_cast(static_cast(res)); + } + /// + /// Allocates user-defined data and stores it in the object. + /// + template inline T &create_private_data() + { + uint64_t res = reinterpret_cast(new T()); + set_private_data(reinterpret_cast(&__uuidof(T)), res); + return *reinterpret_cast(static_cast(res)); + } + /// + /// Frees user-defined data that was previously allocated via . + /// + template inline void destroy_private_data() + { + uint64_t res; + get_private_data(reinterpret_cast(&__uuidof(T)), &res); + delete reinterpret_cast(static_cast(res)); + set_private_data(reinterpret_cast(&__uuidof(T)), 0); + } + }; + + /// + /// A logical render device, used for resource creation and global operations. + /// Functionally equivalent to a 'IDirect3DDevice9', 'ID3D10Device', 'ID3D11Device', 'ID3D12Device', 'HGLRC' or 'VkDevice'. + /// + /// + /// This class is safe to use concurrently from multiple threads in D3D10+ and Vulkan. + /// + struct __declspec(novtable) device : public api_object + { + /// + /// Gets the underlying graphics API used by this device. + /// + virtual device_api get_api() const = 0; + + /// + /// Checks whether the device supports the specified . + /// + virtual bool check_capability(device_caps capability) const = 0; + /// + /// Checks whether the specified texture supports the specified . + /// + virtual bool check_format_support(format format, resource_usage usage) const = 0; + + /// + /// Creates a new sampler state object. + /// + /// Description of the sampler to create. + /// Pointer to a variable that is set to the handle of the created sampler. + /// if the sampler was successfully created, otherwise (in this case is set to zero). + virtual bool create_sampler(const sampler_desc &desc, sampler *out_handle) = 0; + /// + /// Instantly destroys a sampler that was previously created via . + /// + virtual void destroy_sampler(sampler handle) = 0; + + /// + /// Allocates and creates a new resource. + /// + /// Description of the resource to create. + /// Optional data to upload to the resource after creation. This should point to an array of , one for each subresource (mipmap levels and array layers). Can be to indicate no initial data to upload. + /// Initial state of the resource after creation. This can later be changed via . + /// Pointer to a variable that is set to the handle of the created resource. + /// Optional pointer to a variable of type HANDLE used when contains . When that variable is a , it is set to the exported shared handle of the created resource. When that variable is a valid handle, the resource is imported from that shared handle. + /// if the resource was successfully created, otherwise (in this case is set to zero). + virtual bool create_resource(const resource_desc &desc, const subresource_data *initial_data, resource_usage initial_state, resource *out_handle, void **shared_handle = nullptr) = 0; + /// + /// Instantly destroys a resource that was previously created via and frees its memory. + /// Make sure the resource is no longer in use on the GPU (via any command list that may reference it and is still being executed) before doing this and never try to destroy resources created by the application! + /// + virtual void destroy_resource(resource handle) = 0; + + /// + /// Gets the description of the specified resource. + /// + virtual resource_desc get_resource_desc(resource resource) const = 0; + + /// + /// Creates a new resource view for the specified . + /// + /// Resource to create the view to. + /// Usage type of the resource view to create. Set to to create a shader resource view, for a depth-stencil view, for a render target etc. + /// Description of the resource view to create. + /// Pointer to a variable that is set to the handle of the created resource view. + /// if the resource view was successfully created, otherwise (in this case is set to zero). + virtual bool create_resource_view(resource resource, resource_usage usage_type, const resource_view_desc &desc, resource_view *out_handle) = 0; + /// + /// Instantly destroys a resource view that was previously created via . + /// + virtual void destroy_resource_view(resource_view handle) = 0; + + /// + /// Gets the handle to the underlying resource the specified resource was created for. + /// + /// + /// Resource views may be created without a resource in D3D12, which is used to initialize a null descriptor (reading zeroes, writes are discarded). This may therefore return zero for such views. + /// + virtual resource get_resource_from_view(resource_view view) const = 0; + /// + /// Gets the description of the specified resource view. + /// + virtual resource_view_desc get_resource_view_desc(resource_view view) const = 0; + + /// + /// Maps the memory of a buffer resource into application address space. + /// + /// Buffer resource to map to host memory. + /// Offset (in bytes) into the buffer resource to start mapping. + /// Number of bytes to map. Set to -1 (UINT64_MAX) to indicate that the entire buffer should be mapped. + /// Hint on how the returned data pointer will be accessed. + /// Pointer to a variable that is set to a pointer to the memory of the buffer resource. + /// if the memory of the buffer resource was successfully mapped, otherwise (in this case is set to ). + virtual bool map_buffer_region(resource resource, uint64_t offset, uint64_t size, map_access access, void **out_data) = 0; + /// + /// Unmaps a previously mapped buffer resource. + /// + /// Buffer resource to unmap from host memory. + virtual void unmap_buffer_region(resource resource) = 0; + /// + /// Maps the memory of a texture resource into application address space. + /// + /// Texture resource to map to host memory. + /// Index of the subresource to map (level + (layer * levels)). + /// Optional 3D box (or to reference the entire subresource) that defines the region in the to map. + /// Hint on how the returned data pointer will be accessed. + /// Pointer to a variable that is set to a pointer to the memory of the texture resource and optionally the row and slice pitch of that data (depending on the resource type). + /// if the memory of the texture resource was successfully mapped, otherwise (in this case is set to ). + virtual bool map_texture_region(resource resource, uint32_t subresource, const subresource_box *box, map_access access, subresource_data *out_data) = 0; + /// + /// Unmaps a previously mapped texture resource. + /// + /// Texture resource to unmap from host memory. + /// Index of the subresource to unmap (level + (layer * levels)). + virtual void unmap_texture_region(resource resource, uint32_t subresource) = 0; + + /// + /// Uploads data to a buffer resource. + /// + /// Pointer to the data to upload. + /// Buffer resource to upload to. + /// Offset (in bytes) into the buffer resource to start uploading to. + /// Number of bytes to upload. + virtual void update_buffer_region(const void *data, resource resource, uint64_t offset, uint64_t size) = 0; + /// + /// Uploads data to a texture resource. + /// + /// Pointer to the data to upload. + /// Texture resource to upload to. + /// Index of the subresource to upload to (level + (layer * levels)). + /// Optional 3D box (or to reference the entire subresource) that defines the region in the to upload to. + virtual void update_texture_region(const subresource_data &data, resource resource, uint32_t subresource, const subresource_box *box = nullptr) = 0; + + /// + /// Creates a new pipeline state object. + /// + /// Pipeline layout to use. + /// Number of sub-objects. + /// Pointer to an array of sub-objects that describe this pipeline. + /// Pointer to a variable that is set to the handle of the created pipeline state object. + /// if the pipeline state object was successfully created, otherwise (in this case is set to zero). + virtual bool create_pipeline(pipeline_layout layout, uint32_t subobject_count, const pipeline_subobject *subobjects, pipeline *out_handle) = 0; + /// + /// Instantly destroys a pipeline state object that was previously created via . + /// + virtual void destroy_pipeline(pipeline handle) = 0; + + /// + /// Creates a new pipeline layout. + /// + /// Number of layout parameters. + /// Pointer to an array of layout parameters that describe this pipeline layout. + /// Pointer to a variable that is set to the handle of the created pipeline layout. + /// if the pipeline layout was successfully created, otherwise (in this case is set to zero). + virtual bool create_pipeline_layout(uint32_t param_count, const pipeline_layout_param *params, pipeline_layout *out_handle) = 0; + /// + /// Instantly destroys a pipeline layout that was previously created via . + /// + virtual void destroy_pipeline_layout(pipeline_layout handle) = 0; + + /// + /// Allocates a descriptor table from an internal heap. + /// + /// Pipeline layout that contains a parameter that describes the descriptor table. + /// Index of the pipeline layout parameter that describes the descriptor table. + /// Pointer to a a variable that is set to the handles of the created descriptor table. + /// if the descriptor table was successfully allocated, otherwise (in this case is set to zeroe). + inline bool allocate_descriptor_table(pipeline_layout layout, uint32_t param, descriptor_table *out_handle) { return allocate_descriptor_tables(1, layout, param, out_handle); } + /// + /// Allocates one or more descriptor tables from an internal heap. + /// + /// Number of descriptor tables to allocate. + /// Pipeline layout that contains a parameter that describes the descriptor table. + /// Index of the pipeline layout parameter that describes the descriptor table. + /// Pointer to an array of handles with at least elements that is filled with the handles of the created descriptor tables. + /// if the descriptor tables were successfully allocated, otherwise (in this case is filled with zeroes). + virtual bool allocate_descriptor_tables(uint32_t count, pipeline_layout layout, uint32_t param, descriptor_table *out_handles) = 0; + /// + /// Frees a descriptor table that was previously allocated via . + /// + inline void free_descriptor_table(descriptor_table handle) { free_descriptor_tables(1, &handle); } + /// + /// Frees one or more descriptor tables that were previously allocated via . + /// + virtual void free_descriptor_tables(uint32_t count, const descriptor_table *handles) = 0; + + /// + /// Gets the offset (in descriptors) of the specified binding in the underlying descriptor heap of a descriptor table. + /// + /// Descriptor table to get the offset from. + /// Binding in the descriptor table to get the offset from. + /// Array index in the specified . + /// Pointer to a variable that is set to the handle of the underlying descriptor heap the was allocated from. + /// Pointer to a variable that is set to the offset of the binding in the underlying descriptor heap. + virtual void get_descriptor_heap_offset(descriptor_table table, uint32_t binding, uint32_t array_offset, descriptor_heap *out_heap, uint32_t *out_offset) const = 0; + + /// + /// Copies the contents of a descriptor table to another descriptor table. + /// + /// Descriptor table copy to process. + inline void copy_descriptors(const descriptor_table_copy ©) { copy_descriptor_tables(1, ©); } + /// + /// Copies the contents between multiple descriptor tables. + /// + /// Number of to process. + /// Pointer to an array of descriptor table copies to process. + virtual void copy_descriptor_tables(uint32_t count, const descriptor_table_copy *copies) = 0; + /// + /// Updates the contents of a descriptor table with the specified descriptors. + /// + /// Descriptor table update to process. + inline void update_descriptors(const descriptor_table_update &update) { update_descriptor_tables(1, &update); } + /// + /// Updates the contents of multiple descriptor tables with the specified descriptors. + /// + /// Number of to process. + /// Pointer to an array of descriptor table updates to process. + virtual void update_descriptor_tables(uint32_t count, const descriptor_table_update *updates) = 0; + + /// + /// Creates a new query heap. + /// + /// Type of queries that will be used with this query heap. + /// Number of queries to allocate in the query heap. + /// Pointer to a variable that is set to the handle of the created query heap. + /// if the query heap was successfully created, otherwise (in this case is set to zero). + virtual bool create_query_heap(query_type type, uint32_t size, query_heap *out_handle) = 0; + /// + /// Instantly destroys a query heap that was previously created via . + /// + virtual void destroy_query_heap(query_heap handle) = 0; + + /// + /// Gets the results of queries in a query heap. + /// + /// Query heap that contains the queries. + /// Index of the first query in the query heap to copy the results from. + /// Number of query results to copy. + /// Pointer to an array that is filled with the results. + /// Size (in bytes) of each element in the array. + /// if the query results were successfully downloaded from the GPU, otherwise. + virtual bool get_query_heap_results(query_heap heap, uint32_t first, uint32_t count, void *results, uint32_t stride) = 0; + + /// + /// Associates a name with a resource, for easier debugging in external tools. + /// + /// Resource to associate a name with. + /// Null-terminated name string. + virtual void set_resource_name(resource handle, const char *name) = 0; + /// + /// Associates a name with a resource view, for easier debugging in external tools. + /// + /// Resource view to associate a name with. + /// Null-terminated name string. + virtual void set_resource_view_name(resource_view handle, const char *name) = 0; + }; + + /// + /// The base class for objects that are children to a logical render . + /// + struct __declspec(novtable) device_object : public api_object + { + /// + /// Gets the parent device for this object. + /// + virtual device *get_device() = 0; + }; + + /// + /// The available indirect command types. + /// + enum class indirect_command + { + unknown, + draw, + draw_indexed, + dispatch + }; + + /// + /// A command list, used to enqueue render commands on the CPU, before later executing them in a command queue. + /// Functionally equivalent to a 'ID3D11CommandList', 'ID3D12CommandList' or 'VkCommandBuffer'. + /// + /// + /// This class may NOT be used concurrently from multiple threads! + /// + struct __declspec(novtable) command_list : public device_object + { + /// + /// Adds a barrier for the specified to the command stream. + /// When both and are a UAV barrier is added, otherwise a state transition is performed. + /// + /// Resource to transition. + /// Usage flags describing how the was used before this barrier. + /// Usage flags describing how the will be used after this barrier. + inline void barrier(resource resource, resource_usage old_state, resource_usage new_state) { barrier(1, &resource, &old_state, &new_state); } + /// + /// Adds a barrier for the specified to the command stream. + /// + /// Number of resources to transition. + /// Pointer to an array of resources to transition. + /// Pointer to an array of usage flags describing how the were used before this barrier. + /// Pointer to an array of usage flags describing how the will be used after this barrier. + virtual void barrier(uint32_t count, const resource *resources, const resource_usage *old_states, const resource_usage *new_states) = 0; + + /// + /// Begins a render pass and binds render target and depth-stencil resource views. + /// + /// Number of render target views to bind. + /// Pointer to an array of render target descriptions. + /// Optional pointer to a depth-stencil description, or to bind none. + virtual void begin_render_pass(uint32_t count, const render_pass_render_target_desc *rts, const render_pass_depth_stencil_desc *ds = nullptr) = 0; + /// + /// Ends a render pass. + /// This must be preceeded by a call to . + /// Render passes cannot be nested. + /// + virtual void end_render_pass() = 0; + /// + /// Binds individual render target and depth-stencil resource views. + /// This must not be called between and . + /// + /// + /// Number of render target views to bind. + /// Pointer to an array of render target views to bind. + /// Depth-stencil view to bind, or zero to bind none. + virtual void bind_render_targets_and_depth_stencil(uint32_t count, const resource_view *rtvs, resource_view dsv = { 0 }) = 0; + + /// + /// Binds a pipeline state object. + /// + /// Pipeline stages to update with state from the pipeline state object. + /// Pipeline state object to bind. + virtual void bind_pipeline(pipeline_stage stages, pipeline pipeline) = 0; + /// + /// Updates the specfified pipeline to the specified . + /// This is only valid for states that have been listed in the dynamic states provided at creation of the currently bound pipeline state object (). + /// + /// Pipeline state to update. + /// Value to update the pipeline state to. + inline void bind_pipeline_state(dynamic_state state, uint32_t value) { bind_pipeline_states(1, &state, &value); } + /// + /// Updates the specfified pipeline to the specified . + /// This is only valid for states that have been listed in the dynamic states provided at creation of the currently bound pipeline state object (). + /// + /// Number of pipeline states to update. + /// Pointer to an array of pipeline states to update. + /// Pointer to an array of values to update the pipeline states to, with one for each state in . + virtual void bind_pipeline_states(uint32_t count, const dynamic_state *states, const uint32_t *values) = 0; + /// + /// Binds an array of viewports to the rasterizer stage. + /// + /// + /// Index of the first viewport to bind. In D3D9, D3D10, D3D11 and D3D12 this has to be 0. + /// Number of viewports to bind. + /// Pointer to an array of viewports. + virtual void bind_viewports(uint32_t first, uint32_t count, const viewport *viewports) = 0; + /// + /// Binds an array of scissor rectangles to the rasterizer stage. + /// + /// + /// Index of the first scissor rectangle to bind. In D3D9, D3D10, D3D11 and D3D12 this has to be 0. + /// Number of scissor rectangles to bind. + /// Pointer to an array of scissor rectangles. + virtual void bind_scissor_rects(uint32_t first, uint32_t count, const rect *rects) = 0; + + /// + /// Directly updates constant values in the specified shader pipeline stages. + /// In D3D9 this updates the values of uniform registers, in D3D10/11 and OpenGL the constant buffer specified in the pipeline layout, in D3D12 it sets root constants and in Vulkan push constants. + /// + /// + /// Shader stages that will use the updated constants. + /// Pipeline layout that describes where the constants are located. + /// Layout parameter index of the constant range in the pipeline (root parameter index in D3D12). + /// Start offset (in 32-bit values) to the first constant in the constant range to begin updating. + /// Number of 32-bit values to update. + /// Pointer to an array of 32-bit values to set the constants to. These can be floating-point, integer or boolean depending on what the shader is expecting. + virtual void push_constants(shader_stage stages, pipeline_layout layout, uint32_t param, uint32_t first, uint32_t count, const void *values) = 0; + /// + /// Directly binds a temporary descriptor table for the specfified shader pipeline stage and updates with an array of descriptors. + /// + /// + /// Shader stages that will use the updated descriptors. + /// Pipeline layout that describes the descriptors. + /// Layout parameter index of the descriptor table in the pipeline (root parameter index in D3D12, descriptor set index in Vulkan). + /// Range of descriptors to update in the temporary descriptor table ( is ignored). + virtual void push_descriptors(shader_stage stages, pipeline_layout layout, uint32_t param, const descriptor_table_update &update) = 0; + /// + /// Binds a single descriptor table. + /// + /// Shader stages that will use the descriptors. + /// Pipeline layout that describes the descriptors. + /// Index of the pipeline parameter that describes the descriptor table (root parameter index in D3D12, descriptor set index in Vulkan). + /// Descriptor table to bind. + inline void bind_descriptor_table(shader_stage stages, pipeline_layout layout, uint32_t param, descriptor_table table) { bind_descriptor_tables(stages, layout, param, 1, &table); } + /// + /// Binds an array of descriptor tables. + /// + /// Shader stages that will use the descriptors. + /// Pipeline layout that describes the descriptors. + /// Index of the first pipeline parameter that describes the first descriptor table to bind (root parameter index in D3D12, descriptor set index in Vulkan). + /// Number of descriptor tables to bind. + /// Pointer to an array of descriptor tables to bind. + virtual void bind_descriptor_tables(shader_stage stages, pipeline_layout layout, uint32_t first, uint32_t count, const descriptor_table *tables) = 0; + + /// + /// Binds an index buffer to the input-assembler stage. + /// + /// Index buffer resource. This resource must have been created with the usage. + /// Offset (in bytes) from the start of the index buffer to the first index to use. In D3D9 this has to be 0. + /// Size (in bytes) of each index. Can typically be 2 (16-bit indices) or 4 (32-bit indices). + virtual void bind_index_buffer(resource buffer, uint64_t offset, uint32_t index_size) = 0; + /// + /// Binds a single vertex buffer to the input-assembler stage. + /// + /// Input slot for binding. + /// Vertex buffer resource. This resources must have been created with the usage. + /// Offset (in bytes) from the start of the vertex buffer to the first vertex element to use. + /// Size (in bytes) of the vertex element that will be used from the vertex buffer (is added to an element offset to advance to the next). + inline void bind_vertex_buffer(uint32_t index, resource buffer, uint64_t offset, uint32_t stride) { bind_vertex_buffers(index, 1, &buffer, &offset, &stride); } + /// + /// Binds an array of vertex buffers to the input-assembler stage. + /// + /// First input slot for binding. + /// Number of vertex buffers to bind. + /// Pointer to an array of vertex buffer resources. These resources must have been created with the usage. + /// Pointer to an array of offset values, one for each buffer. Each offset is the number of bytes from the start of the vertex buffer to the first vertex element to use. + /// Pointer to an array of stride values, one for each buffer. Each stride is the size (in bytes) of the vertex element that will be used from that vertex buffer (is added to an element offset to advance to the next). + virtual void bind_vertex_buffers(uint32_t first, uint32_t count, const resource *buffers, const uint64_t *offsets, const uint32_t *strides) = 0; + + /// + /// Binds an array of buffers to the stream-output stage. + /// + /// First stream-output slot for binding. + /// Number of stream-output targets to bind. + /// Pointer to an array of buffer resources. These resources must have been created with the usage. + /// Pointer to an array of offset values, one for each buffer. Each offset is the number of bytes from the start of the buffer to the first element to write to. + /// Optional pointer to an array of size values, one for each buffer. Can be or have elements set to UINT64_MAX to use the entire buffer. + /// Pointer to an array of counter buffer resources. These resources must have been created with the usage. + /// Pointer to an array of counter offset values, one for each counter buffer. Each offset is the number of bytes from the start of the counter buffer to the first element to write to. + virtual void bind_stream_output_buffers(uint32_t first, uint32_t count, const api::resource *buffers, const uint64_t *offsets, const uint64_t *max_sizes, const api::resource *counter_buffers, const uint64_t *counter_offsets) = 0; + + /// + /// Draws non-indexed primitives. + /// + /// + /// Number of vertices to draw. + /// Number of instances to draw. In D3D9 this has to be 1. + /// Index of the first vertex. + /// Value added to each index before reading per-instance data from a vertex buffer. In D3D9 this has to be 0. + virtual void draw(uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance) = 0; + /// + /// Draws indexed primitives. + /// + /// + /// Number of indices read from the index buffer for each instance. + /// Number of instances to draw. In D3D9 this has to be 1. + /// Location of the first index read from the index buffer. + /// Value added to each index before reading per-vertex data from a vertex buffer. + /// Value added to each index before reading per-instance data from a vertex buffer. In D3D9 this has to be 0. + virtual void draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance) = 0; + /// + /// Performs a compute shader dispatch. + /// + /// + /// Number of thread groups dispatched in the x direction. + /// Number of thread groups dispatched in the y direction. + /// Number of thread groups dispatched in the z direction. + virtual void dispatch(uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z) = 0; + /// + /// Executes indirect draw or dispatch commands. + /// + /// + /// Specifies whether this is an indirect draw, indexed draw or dispatch command. + /// Buffer resource that contains command arguments. + /// Offset (in bytes) from the start of the argument buffer to the first argument to use. + /// Number of commands to execute. + /// Stride (in bytes) between commands in the argument buffer. + virtual void draw_or_dispatch_indirect(indirect_command type, resource buffer, uint64_t offset, uint32_t draw_count, uint32_t stride) = 0; + + /// + /// Copies the entire contents of the resource to the ination resource. Dimensions of the two resources have to match. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// Resource to copy from. + /// Resource to copy to. + virtual void copy_resource(resource source, resource dest) = 0; + /// + /// Copies a linear memory region from the buffer to the ination buffer. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// + /// Buffer resource to copy from. + /// Offset (in bytes) into the buffer to start copying at. + /// Buffer resource to copy to. + /// Offset (in bytes) into the ination buffer to start copying to. + /// Number of bytes to copy. + virtual void copy_buffer_region(resource source, uint64_t source_offset, resource dest, uint64_t dest_offset, uint64_t size) = 0; + /// + /// Copies a texture region from the buffer to the ination texture. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// + /// Buffer resource to copy from. + /// Offset (in bytes) into the buffer to start copying at. + /// Number of pixels from one row to the next (in the buffer), or zero if data is tightly packed. + /// Number of rows from one slice to the next (in the buffer) or zero if data is tightly packed. + /// Texture resource to copy to. + /// Index of the subresource of the ination texture to copy to. + /// Optional 3D box (or to reference the entire subresource) that defines the region in the ination texture to copy to. + virtual void copy_buffer_to_texture(resource source, uint64_t source_offset, uint32_t row_length, uint32_t slice_height, resource dest, uint32_t dest_subresource, const subresource_box *dest_box = nullptr) = 0; + /// + /// Copies or blits a texture region from the texture to the ination texture. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// + /// Texture resource to copy from. + /// Index of the subresource of the texture to copy from. + /// Optional 3D box (or to reference the entire subresource) that defines the region in the texture to blit from. + /// Texture resource to copy to. + /// Index of the subresource of the ination texture to copy to. + /// Optional 3D box (or to reference the entire subresource) that defines the region in the ination texture to blit to. + /// Filter to apply when copy requires scaling. + virtual void copy_texture_region(resource source, uint32_t source_subresource, const subresource_box *source_box, resource dest, uint32_t dest_subresource, const subresource_box *dest_box, filter_mode filter = filter_mode::min_mag_mip_point) = 0; + /// + /// Copies a texture region from the texture to the ination buffer. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// + /// Texture resource to copy from. + /// Index of the subresource of the texture to copy from. + /// Optional 3D box (or to reference the entire subresource) that defines the region in the texture to copy from. + /// Buffer resource to copy to. + /// Offset (in bytes) into the ination buffer to start copying to. + /// Number of pixels from one row to the next (in the buffer), or zero if data is tightly packed. + /// Number of rows from one slice to the next (in the buffer), or zero if data is tightly packed. + virtual void copy_texture_to_buffer(resource source, uint32_t source_subresource, const subresource_box *source_box, resource dest, uint64_t dest_offset, uint32_t row_length = 0, uint32_t slice_height = 0) = 0; + /// + /// Copies a region from the multisampled texture to the non-multisampled ination texture. + /// + /// + /// The resource has to be in the state. + /// The ination resource has to be in the state. + /// + /// + /// Texture resource to resolve from. + /// Index of the subresource of the texture to resolve from. + /// Optional 3D box (or to reference the entire subresource) that defines the region in the texture to resolve. + /// Texture resource to resolve to. + /// Index of the subresource of the ination texture to resolve to. + /// Optional X offset (in texels) that defines the region in the ination texture to resolve to. + /// Optional Y offset (in texels) that defines the region in the ination texture to resolve to. + /// Optional Z offset (in texels) that defines the region in the ination texture to resolve to. + /// Format of the resource data. + virtual void resolve_texture_region(resource source, uint32_t source_subresource, const subresource_box *source_box, resource dest, uint32_t dest_subresource, int32_t dest_x, int32_t dest_y, int32_t dest_z, format format) = 0; + + /// + /// Clears the resource referenced by the depth-stencil view. + /// + /// + /// The resource the depth-stencil view points to has to be in the state. + /// + /// Resource view handle of the depth-stencil. + /// Optional value to clear the depth buffer with. + /// Optional value to clear the stencil buffer with. + /// Number of rectangles to clear in the depth-stencil resource, or zero to clear the whole resource. + /// Pointer to an array of rectangles. + virtual void clear_depth_stencil_view(resource_view dsv, const float *depth, const uint8_t *stencil, uint32_t rect_count = 0, const rect *rects = nullptr) = 0; + /// + /// Clears the resource referenced by the render target view. + /// + /// + /// The resource the render target view points to has to be in the state. + /// + /// Resource view handle of the render target. + /// Value to clear the resource with. + /// Number of rectangles to clear in the render target resource, or zero to clear the whole resource. + /// Pointer to an array of rectangles. + virtual void clear_render_target_view(resource_view rtv, const float color[4], uint32_t rect_count = 0, const rect *rects = nullptr) = 0; + /// + /// Clears the resource referenced by the unordered access view. + /// + /// + /// The resource the unordered access view points to has to be in the state. + /// + /// Resource view handle of the unordered access view. + /// Value to clear the resource with. + /// Number of rectangles to clear in the unordered access resource, or zero to clear the whole resource. + /// Pointer to an array of rectangles. + virtual void clear_unordered_access_view_uint(resource_view uav, const uint32_t values[4], uint32_t rect_count = 0, const rect *rects = nullptr) = 0; + /// + /// Clears the resource referenced by the unordered access view. + /// + /// + /// The resource the unordered access view points to has to be in the state. + /// + /// Resource view handle of the unordered access view. + /// Value to clear the resource with. + /// Number of rectangles to clear in the unordered access resource, or zero to clear the whole resource. + /// Pointer to an array of rectangles. + virtual void clear_unordered_access_view_float(resource_view uav, const float values[4], uint32_t rect_count = 0, const rect *rects = nullptr) = 0; + + /// + /// Generates the lower mipmap levels for the specified shader resource view. + /// Uses the largest mipmap level of the view to recursively generate the lower levels of the mipmap chain and stops with the smallest level that is specified by the view. + /// + /// + /// This will invalidate all previous descriptor and pipeline bindings, which will need to be reset by calls to or and . + /// The resource the shader resource view points to has to be in the state and has to have been created with the flag. + /// + /// Shader resource view to update. + virtual void generate_mipmaps(resource_view srv) = 0; + + /// + /// Begins a query. + /// + /// Query heap that will manage the results of the query. + /// Type of the query to begin. + /// Index of the query in the query heap. + virtual void begin_query(query_heap heap, query_type type, uint32_t index) = 0; + /// + /// Ends a query. + /// + /// Query heap that will manage the results of the query. + /// Type of the query end. + /// Index of the query in the query heap. + virtual void end_query(query_heap heap, query_type type, uint32_t index) = 0; + /// + /// Copies the results of queries in a query heap to a buffer resource. + /// + /// + /// The ination resource has to be in the state. + /// + /// + /// Query heap that manages the results of the queries. + /// Type of the queries to copy. + /// Index of the first query in the query heap to copy the result from. + /// Number of query results to copy. + /// Buffer resource to copy to. + /// Offset (in bytes) into the ination buffer to start copying to. + /// Size (in bytes) of each result element. + virtual void copy_query_heap_results(query_heap heap, query_type type, uint32_t first, uint32_t count, resource dest, uint64_t dest_offset, uint32_t stride) = 0; + + /// + /// Opens a debug event region in the command list. + /// + /// Null-terminated string containing the label of the event. + /// Optional RGBA color value associated with the event. + virtual void begin_debug_event(const char *label, const float color[4] = nullptr) = 0; + /// + /// Closes the current debug event region (the last one opened with ). + /// + virtual void end_debug_event() = 0; + /// + /// Inserts a debug marker into the command list. + /// + /// Null-terminated string containing the label of the debug marker. + /// Optional RGBA color value associated with the debug marker. + virtual void insert_debug_marker(const char *label, const float color[4] = nullptr) = 0; + }; + + /// + /// A list of flags that represent the available command queue types, as returned by . + /// + enum class command_queue_type + { + graphics = 0x1, + compute = 0x2, + copy = 0x4 + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(command_queue_type); + + /// + /// A command queue, used to execute command lists on the GPU. + /// Functionally equivalent to the immediate 'ID3D11DeviceContext' or a 'ID3D12CommandQueue' or 'VkQueue'. + /// + /// + /// This class may NOT be used concurrently from multiple threads! + /// + struct __declspec(novtable) command_queue : public device_object + { + /// + /// Gets the type of the command queue, which specifies what commands can be executed on it. + /// + virtual command_queue_type get_type() const = 0; + + /// + /// Waits for all issued GPU operations on this queue to finish before returning. + /// This can be used to ensure that e.g. resources are no longer in use on the GPU before destroying them. + /// + virtual void wait_idle() const = 0; + + /// + /// Flushes and executes the special immediate command list returned by immediately. + /// This can be used to force commands to execute right away instead of waiting for the runtime to flush it automatically at some point. + /// + virtual void flush_immediate_command_list() const = 0; + + /// + /// Gets a special command list, on which all issued commands are executed as soon as possible (or right before the application executes its next command list on this queue). + /// This only exists on command queues that contain the flag, on other queues is returned. + /// + virtual command_list *get_immediate_command_list() = 0; + + /// + /// Opens a debug event region in the command queue. + /// + /// Null-terminated string containing the label of the event. + /// Optional RGBA color value associated with the event. + virtual void begin_debug_event(const char *label, const float color[4] = nullptr) = 0; + /// + /// Closes the current debug event region (the last one opened with ). + /// + virtual void end_debug_event() = 0; + /// + /// Inserts a debug marker into the command queue. + /// + /// Null-terminated string containing the label of the debug marker. + /// Optional RGBA color value associated with the debug marker. + virtual void insert_debug_marker(const char *label, const float color[4] = nullptr) = 0; + }; + + /// + /// Describes a swap chain and its back buffer resources. + /// + struct swapchain_desc + { + /// + /// Description of the back buffer resources. + /// + resource_desc back_buffer; + + /// + /// Number of back buffer resources in the swap chain. + /// + uint32_t back_buffer_count = 0; + + /// + /// Defines how the back buffers should be swapped when a present occurs. + /// Depending on the render API this can be a 'D3DSWAPEFFECT', 'DXGI_SWAP_EFFECT', 'WGL_SWAP_METHOD_ARB' or 'VkPresentModeKHR' value. + /// + uint32_t present_mode = 0; + + /// + /// Swap chain creation flags. + /// Depending on the render API this can be a 'D3DPRESENT', 'DXGI_PRESENT', 'PFD_*' or 'VkSwapchainCreateFlagsKHR' value. + /// + uint32_t present_flags = 0; + }; + + /// + /// A swap chain, used to present images to the screen. + /// Functionally equivalent to a 'IDirect3DSwapChain9', 'IDXGISwapChain', 'HDC' or 'VkSwapchainKHR'. + /// + struct __declspec(novtable) swapchain : public device_object + { + /// + /// Gets the handle of the window this swap chain was created with, or if this is an offscreen swap chain. + /// + virtual void *get_hwnd() const = 0; + + /// + /// Gets the back buffer resource at the specified in this swap chain. + /// + /// Index of the back buffer. This has to be between zero and the value returned by . + virtual resource get_back_buffer(uint32_t index) = 0; + + /// + /// Gets the number of back buffer resources in this swap chain. + /// + virtual uint32_t get_back_buffer_count() const = 0; + + /// + /// Gets the current back buffer resource. + /// + inline resource get_current_back_buffer() { return get_back_buffer(get_current_back_buffer_index()); } + /// + /// Gets the index of the back buffer resource that can currently be rendered into. + /// + virtual uint32_t get_current_back_buffer_index() const = 0; + }; +} } diff --git a/Plugin/include/reshade/reshade_api_format.hpp b/Plugin/include/reshade/reshade_api_format.hpp new file mode 100644 index 00000000..023b87e0 --- /dev/null +++ b/Plugin/include/reshade/reshade_api_format.hpp @@ -0,0 +1,460 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include +#include + +namespace reshade { namespace api +{ + /// + /// The available data and texture formats. + /// This is mostly compatible with 'DXGI_FORMAT'. + /// + enum class format : uint32_t + { + unknown = 0, + + // Color formats + + r1_unorm = 66, + l8_unorm = 0x3030384C, + a8_unorm = 65, + r8_typeless = 60, + r8_uint = 62, + r8_sint = 64, + r8_unorm = 61, + r8_snorm = 63, + l8a8_unorm = 0x3038414C, + r8g8_typeless = 48, + r8g8_uint = 50, + r8g8_sint = 52, + r8g8_unorm = 49, + r8g8_snorm = 51, + r8g8b8a8_typeless = 27, + r8g8b8a8_uint = 30, + r8g8b8a8_sint = 32, + r8g8b8a8_unorm = 28, + r8g8b8a8_unorm_srgb = 29, + r8g8b8a8_snorm = 31, + r8g8b8x8_unorm = 0x424757B9, + r8g8b8x8_unorm_srgb = 0x424757BA, + b8g8r8a8_typeless = 90, + b8g8r8a8_unorm = 87, + b8g8r8a8_unorm_srgb = 91, + b8g8r8x8_typeless = 92, + b8g8r8x8_unorm = 88, + b8g8r8x8_unorm_srgb = 93, + r10g10b10a2_typeless = 23, + r10g10b10a2_uint = 25, + r10g10b10a2_unorm = 24, + r10g10b10a2_xr_bias = 89, + b10g10r10a2_typeless = 0x42475330, + b10g10r10a2_uint = 0x42475332, + b10g10r10a2_unorm = 0x42475331, + l16_unorm = 0x3036314C, + r16_typeless = 53, + r16_uint = 57, + r16_sint = 59, + r16_unorm = 56, + r16_snorm = 58, + r16_float = 54, + l16a16_unorm = 0x3631414C, + r16g16_typeless = 33, + r16g16_uint = 36, + r16g16_sint = 38, + r16g16_unorm = 35, + r16g16_snorm = 37, + r16g16_float = 34, + r16g16b16a16_typeless = 9, + r16g16b16a16_uint = 12, + r16g16b16a16_sint = 14, + r16g16b16a16_unorm = 11, + r16g16b16a16_snorm = 13, + r16g16b16a16_float = 10, + r32_typeless = 39, + r32_uint = 42, + r32_sint = 43, + r32_float = 41, + r32g32_typeless = 15, + r32g32_uint = 17, + r32g32_sint = 18, + r32g32_float = 16, + r32g32b32_typeless = 5, + r32g32b32_uint = 7, + r32g32b32_sint = 8, + r32g32b32_float = 6, + r32g32b32a32_typeless = 1, + r32g32b32a32_uint = 3, + r32g32b32a32_sint = 4, + r32g32b32a32_float = 2, + r9g9b9e5 = 67, + r11g11b10_float = 26, + b5g6r5_unorm = 85, + b5g5r5a1_unorm = 86, + b5g5r5x1_unorm = 0x424757B5, + b4g4r4a4_unorm = 115, + a4b4g4r4_unorm = 191, + + // Depth-stencil formats + + s8_uint = 0x30303853, + d16_unorm = 55, + d16_unorm_s8_uint = 0x38363144, + d24_unorm_x8_uint = 0x38343244, + d24_unorm_s8_uint = 45, + d32_float = 40, + d32_float_s8_uint = 20, + + r24_g8_typeless = 44, + r24_unorm_x8_uint = 46, + x24_unorm_g8_uint = 47, + r32_g8_typeless = 19, + r32_float_x8_uint = 21, + x32_float_g8_uint = 22, + + // Compressed data formats + + bc1_typeless = 70, + bc1_unorm = 71, + bc1_unorm_srgb = 72, + bc2_typeless = 73, + bc2_unorm = 74, + bc2_unorm_srgb = 75, + bc3_typeless = 76, + bc3_unorm = 77, + bc3_unorm_srgb = 78, + bc4_typeless = 79, + bc4_unorm = 80, + bc4_snorm = 81, + bc5_typeless = 82, + bc5_unorm = 83, + bc5_snorm = 84, + bc6h_typeless = 94, + bc6h_ufloat = 95, + bc6h_sfloat = 96, + bc7_typeless = 97, + bc7_unorm = 98, + bc7_unorm_srgb = 99, + + // Video formats + + r8g8_b8g8_unorm = 68, + g8r8_g8b8_unorm = 69, + + // Special purpose formats + + intz = 0x5A544E49, + }; + + /// + /// The available color space types for presentation. + /// + enum class color_space : uint32_t + { + unknown = 0, + + srgb_nonlinear, + extended_srgb_linear, + hdr10_st2084, + hdr10_hlg, + }; + + /// + /// Converts the specified format to its equivalent typeless variant. + /// + /// The format to convert. + inline format format_to_typeless(format value) + { + switch (value) + { + case format::l8_unorm: + case format::r8_typeless: + case format::r8_uint: + case format::r8_sint: + case format::r8_unorm: + case format::r8_snorm: + return format::r8_typeless; + case format::l8a8_unorm: + case format::r8g8_typeless: + case format::r8g8_uint: + case format::r8g8_sint: + case format::r8g8_unorm: + case format::r8g8_snorm: + return format::r8g8_typeless; + case format::r8g8b8a8_typeless: + case format::r8g8b8a8_uint: + case format::r8g8b8a8_sint: + case format::r8g8b8a8_unorm: + case format::r8g8b8a8_unorm_srgb: + case format::r8g8b8a8_snorm: + case format::r8g8b8x8_unorm: + case format::r8g8b8x8_unorm_srgb: + return format::r8g8b8a8_typeless; + case format::b8g8r8a8_typeless: + case format::b8g8r8a8_unorm: + case format::b8g8r8a8_unorm_srgb: + return format::b8g8r8a8_typeless; + case format::b8g8r8x8_typeless: + case format::b8g8r8x8_unorm: + case format::b8g8r8x8_unorm_srgb: + return format::b8g8r8x8_typeless; + case format::r10g10b10a2_typeless: + case format::r10g10b10a2_uint: + case format::r10g10b10a2_unorm: + case format::r10g10b10a2_xr_bias: + return format::r10g10b10a2_typeless; + case format::b10g10r10a2_typeless: + case format::b10g10r10a2_uint: + case format::b10g10r10a2_unorm: + return format::b10g10r10a2_typeless; + case format::l16_unorm: + case format::d16_unorm: + case format::r16_typeless: + case format::r16_uint: + case format::r16_sint: + case format::r16_float: + case format::r16_unorm: + case format::r16_snorm: + return format::r16_typeless; + case format::l16a16_unorm: + case format::r16g16_typeless: + case format::r16g16_uint: + case format::r16g16_sint: + case format::r16g16_float: + case format::r16g16_unorm: + case format::r16g16_snorm: + return format::r16g16_typeless; + case format::r16g16b16a16_typeless: + case format::r16g16b16a16_uint: + case format::r16g16b16a16_sint: + case format::r16g16b16a16_float: + case format::r16g16b16a16_unorm: + case format::r16g16b16a16_snorm: + return format::r16g16b16a16_typeless; + case format::d32_float: + case format::r32_typeless: + case format::r32_uint: + case format::r32_sint: + case format::r32_float: + return format::r32_typeless; + case format::r32g32_typeless: + case format::r32g32_uint: + case format::r32g32_sint: + case format::r32g32_float: + return format::r32g32_typeless; + case format::r32g32b32_typeless: + case format::r32g32b32_uint: + case format::r32g32b32_sint: + case format::r32g32b32_float: + return format::r32g32b32_typeless; + case format::r32g32b32a32_typeless: + case format::r32g32b32a32_uint: + case format::r32g32b32a32_sint: + case format::r32g32b32a32_float: + return format::r32g32b32a32_typeless; + case format::d32_float_s8_uint: + case format::r32_g8_typeless: + case format::r32_float_x8_uint: + case format::x32_float_g8_uint: + return format::r32_g8_typeless; + case format::d24_unorm_s8_uint: // Do not also convert 'd24_unorm_x8_uint' here, to keep it distinguishable from 'd24_unorm_s8_uint' + case format::r24_g8_typeless: + case format::r24_unorm_x8_uint: + case format::x24_unorm_g8_uint: + return format::r24_g8_typeless; + case format::bc1_typeless: + case format::bc1_unorm: + case format::bc1_unorm_srgb: + return format::bc1_typeless; + case format::bc2_typeless: + case format::bc2_unorm: + case format::bc2_unorm_srgb: + return format::bc2_typeless; + case format::bc3_typeless: + case format::bc3_unorm: + case format::bc3_unorm_srgb: + return format::bc2_typeless; + case format::bc4_typeless: + case format::bc4_unorm: + case format::bc4_snorm: + return format::bc4_typeless; + case format::bc5_typeless: + case format::bc5_unorm: + case format::bc5_snorm: + return format::bc5_typeless; + case format::bc6h_typeless: + case format::bc6h_ufloat: + case format::bc6h_sfloat: + return format::bc6h_typeless; + case format::bc7_typeless: + case format::bc7_unorm: + case format::bc7_unorm_srgb: + return format::bc7_typeless; + default: + return value; + } + } + + /// + /// Converts the specified format to its equivalent typed variant ("unorm" or "float"). + /// + /// The format to convert. + /// Set to 1 to get sRGB variant, 0 to get linear variant and -1 to preserve existing one. + inline format format_to_default_typed(format value, int srgb_variant = -1) + { + switch (value) + { + case format::r8_typeless: + return format::r8_unorm; + case format::r8g8_typeless: + return format::r8g8_unorm; + case format::r8g8b8a8_typeless: + case format::r8g8b8a8_unorm: + return srgb_variant == 1 ? format::r8g8b8a8_unorm_srgb : format::r8g8b8a8_unorm; + case format::r8g8b8a8_unorm_srgb: + return srgb_variant != 0 ? format::r8g8b8a8_unorm_srgb : format::r8g8b8a8_unorm; + case format::r8g8b8x8_unorm: + return srgb_variant == 1 ? format::r8g8b8x8_unorm_srgb : format::r8g8b8x8_unorm; + case format::r8g8b8x8_unorm_srgb: + return srgb_variant != 0 ? format::r8g8b8x8_unorm_srgb : format::r8g8b8x8_unorm; + case format::b8g8r8a8_typeless: + case format::b8g8r8a8_unorm: + return srgb_variant == 1 ? format::b8g8r8a8_unorm_srgb : format::b8g8r8a8_unorm; + case format::b8g8r8a8_unorm_srgb: + return srgb_variant != 0 ? format::b8g8r8a8_unorm_srgb : format::b8g8r8a8_unorm; + case format::b8g8r8x8_typeless: + case format::b8g8r8x8_unorm: + return srgb_variant == 1 ? format::b8g8r8x8_unorm_srgb : format::b8g8r8x8_unorm; + case format::b8g8r8x8_unorm_srgb: + return srgb_variant != 0 ? format::b8g8r8x8_unorm_srgb : format::b8g8r8x8_unorm; + case format::r10g10b10a2_typeless: + return format::r10g10b10a2_unorm; + case format::b10g10r10a2_typeless: + return format::b10g10r10a2_unorm; + case format::d16_unorm: + case format::r16_typeless: + return format::r16_float; + case format::r16g16_typeless: + return format::r16g16_float; + case format::r16g16b16a16_typeless: + return format::r16g16b16a16_float; + case format::d32_float: + case format::r32_typeless: + return format::r32_float; + case format::r32g32_typeless: + return format::r32g32_float; + case format::r32g32b32_typeless: + return format::r32g32b32_float; + case format::r32g32b32a32_typeless: + return format::r32g32b32a32_float; + case format::d32_float_s8_uint: + case format::r32_g8_typeless: + return format::r32_float_x8_uint; + case format::d24_unorm_s8_uint: // Do not also convert 'd24_unorm_x8_uint' here, to keep it distinguishable from 'd24_unorm_s8_uint' + case format::r24_g8_typeless: + return format::r24_unorm_x8_uint; + case format::bc1_typeless: + case format::bc1_unorm: + return srgb_variant == 1 ? format::bc1_unorm_srgb : format::bc1_unorm; + case format::bc1_unorm_srgb: + return srgb_variant != 0 ? format::bc1_unorm_srgb : format::bc1_unorm; + case format::bc2_typeless: + case format::bc2_unorm: + return srgb_variant == 1 ? format::bc2_unorm_srgb : format::bc2_unorm; + case format::bc2_unorm_srgb: + return srgb_variant != 0 ? format::bc2_unorm_srgb : format::bc2_unorm; + case format::bc3_typeless: + case format::bc3_unorm: + return srgb_variant == 1 ? format::bc3_unorm_srgb : format::bc3_unorm; + case format::bc3_unorm_srgb: + return srgb_variant != 0 ? format::bc3_unorm_srgb : format::bc3_unorm; + case format::bc4_typeless: + return format::bc4_unorm; + case format::bc5_typeless: + return format::bc5_unorm; + case format::bc6h_typeless: + return format::bc6h_ufloat; + case format::bc7_typeless: + case format::bc7_unorm: + return srgb_variant == 1 ? format::bc7_unorm_srgb : format::bc7_unorm; + case format::bc7_unorm_srgb: + return srgb_variant != 0 ? format::bc7_unorm_srgb : format::bc7_unorm; + default: + return value; + } + } + + /// + /// Converts the specified format to its equivalent depth-stencil variant. + /// + /// The format to convert. + inline format format_to_depth_stencil_typed(format value) + { + switch (value) + { + case format::r16_typeless: + case format::r16_unorm: + return format::d16_unorm; + case format::r32_typeless: + case format::r32_float: + return format::d32_float; + case format::r32_g8_typeless: + case format::r32_float_x8_uint: + case format::x32_float_g8_uint: + return format::d32_float_s8_uint; + case format::r24_g8_typeless: + case format::r24_unorm_x8_uint: + case format::x24_unorm_g8_uint: + return format::d24_unorm_s8_uint; + default: + return value; + } + } + + /// + /// Gets the number of bytes a texture row of the specified format occupies. + /// + inline const uint32_t format_row_pitch(format value, uint32_t width) + { + if (value == format::unknown) + return 0; + + if (value <= format::r32g32b32a32_sint) + return 16 * width; + if (value <= format::r32g32b32_sint) + return 12 * width; + if (value <= format::x32_float_g8_uint) + return 8 * width; + if (value <= format::x24_unorm_g8_uint || value == format::l16a16_unorm) + return 4 * width; + if (value <= format::r16_sint || value == format::b5g6r5_unorm || value == format::b5g5r5a1_unorm || value == format::b5g5r5x1_unorm || value == format::l8a8_unorm || value == format::l16_unorm) + return 2 * width; + if (value <= format::a8_unorm || value == format::l8_unorm) + return 1 * width; + if (value <= format::g8r8_g8b8_unorm || (value >= format::b8g8r8a8_unorm && value <= format::b8g8r8x8_unorm_srgb) || (value == format::r8g8b8x8_unorm || value == format::r8g8b8x8_unorm_srgb)) + return 4 * width; + + // Block compressed formats are bytes per block, rather than per pixel + if ((value >= format::bc1_typeless && value <= format::bc1_unorm_srgb) || (value >= format::bc4_typeless && value <= format::bc4_snorm)) + return 8 * ((width + 3) / 4); + if ((value >= format::bc2_typeless && value <= format::bc2_unorm_srgb) || (value >= format::bc3_typeless && value <= format::bc3_unorm_srgb) || (value >= format::bc5_typeless && value <= format::bc7_unorm_srgb)) + return 16 * ((width + 3) / 4); + + return 0; + } + + /// + /// Gets the number of bytes a texture slice of the specified format occupies. + /// + inline const uint32_t format_slice_pitch(format value, uint32_t row_pitch, uint32_t height) + { + if ((value >= format::bc1_typeless && value <= format::bc5_snorm) || (value >= format::bc6h_typeless && value <= format::bc7_unorm_srgb)) + return row_pitch * ((height + 3) / 4); + + return row_pitch * height; + } +} } diff --git a/Plugin/include/reshade/reshade_api_pipeline.hpp b/Plugin/include/reshade/reshade_api_pipeline.hpp new file mode 100644 index 00000000..51601617 --- /dev/null +++ b/Plugin/include/reshade/reshade_api_pipeline.hpp @@ -0,0 +1,1001 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include "reshade_api_resource.hpp" + +namespace reshade { namespace api +{ + /// + /// A list of flags that represent the available shader stages in the render pipeline. + /// + enum class shader_stage : uint32_t + { + vertex = 0x1, + hull = 0x2, + domain = 0x4, + geometry = 0x8, + pixel = 0x10, + compute = 0x20, + + all = 0x7FFFFFFF, + all_compute = compute, + all_graphics = vertex | hull | domain | geometry | pixel + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(shader_stage); + + /// + /// A list of flags that represent the available pipeline stages in the render pipeline. + /// + enum class pipeline_stage : uint32_t + { + vertex_shader = 0x8, + hull_shader = 0x10, + domain_shader = 0x20, + geometry_shader = 0x40, + pixel_shader = 0x80, + compute_shader = 0x800, + + input_assembler = 0x2, + stream_output = 0x4, + rasterizer = 0x100, + depth_stencil = 0x200, + output_merger = 0x400, + + all = 0x7FFFFFFF, + all_compute = compute_shader, + all_graphics = vertex_shader | hull_shader | domain_shader | geometry_shader | pixel_shader | input_assembler | stream_output | rasterizer | depth_stencil | output_merger, + all_shader_stages = vertex_shader | hull_shader | domain_shader | geometry_shader | pixel_shader | compute_shader + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(pipeline_stage); + + /// + /// The available descriptor types. + /// + enum class descriptor_type : uint32_t + { + sampler = 0, + sampler_with_resource_view = 1, + shader_resource_view = 2, + unordered_access_view = 3, + constant_buffer = 6, + shader_storage_buffer = 7 + }; + + /// + /// The available pipeline layout parameter types. + /// + enum class pipeline_layout_param_type : uint32_t + { + push_constants = 1, + descriptor_table = 0, + push_descriptors = 2, + push_descriptors_with_ranges = 3 + }; + + /// + /// Describes a range of constants in a pipeline layout. + /// + struct constant_range + { + /// + /// OpenGL uniform buffer binding index. + /// + uint32_t binding = 0; + /// + /// D3D10/D3D11/D3D12 constant buffer register index. + /// + uint32_t dx_register_index = 0; + /// + /// D3D12 constant buffer register space. + /// + uint32_t dx_register_space = 0; + /// + /// Number of constants in this range (in 32-bit values). + /// + uint32_t count = 0; + /// + /// Shader pipeline stages that can make use of the constants in this range. + /// + shader_stage visibility = shader_stage::all; + }; + + /// + /// Describes a range of descriptors of a descriptor table in a pipeline layout. + /// + struct descriptor_range + { + /// + /// OpenGL/Vulkan binding index (layout(binding=X) in GLSL). + /// In D3D this is equivalent to the offset (in descriptors) of this range in the descriptor table (since each binding can only have an array size of 1). + /// + uint32_t binding = 0; + /// + /// D3D9/D3D10/D3D11/D3D12 shader register index (register(xX) in HLSL). + /// + uint32_t dx_register_index = 0; + /// + /// D3D12 register space (register(..., spaceX) in HLSL). + /// + uint32_t dx_register_space = 0; + /// + /// Number of descriptors in this range. + /// Set to -1 (UINT32_MAX) to indicate an unbounded range. + /// + uint32_t count = 0; + /// + /// Shader pipeline stages that can make use of the descriptors in this range. + /// + shader_stage visibility = shader_stage::all; + /// + /// Size of the array in case this is an array binding. + /// Only meaningful in Vulkan, in OpenGL and other APIs this has to be 1 (since each array element is a separate binding there). + /// If this is less than the total number of descriptors specified in , then the remaining descriptors are assigned a separate binding (with an array size of 1), with the binding index incrementing with each additional descriptor. + /// + uint32_t array_size = 1; + /// + /// Type of the descriptors in this range. + /// + descriptor_type type = descriptor_type::sampler; + }; + + /// + /// Describes a single parameter in a pipeline layout. + /// + struct pipeline_layout_param + { + constexpr pipeline_layout_param() : push_descriptors() {} + constexpr pipeline_layout_param(const constant_range &push_constants) : type(pipeline_layout_param_type::push_constants), push_constants(push_constants) {} + constexpr pipeline_layout_param(const descriptor_range &push_descriptors) : type(pipeline_layout_param_type::push_descriptors), push_descriptors(push_descriptors) {} + constexpr pipeline_layout_param(uint32_t count, const descriptor_range *ranges) : type(pipeline_layout_param_type::descriptor_table), descriptor_table({ count, ranges }) {} + + /// + /// Type of the parameter. + /// + pipeline_layout_param_type type = pipeline_layout_param_type::push_descriptors; + + union + { + /// + /// Used when parameter type is . + /// + constant_range push_constants; + + /// + /// Used when parameter type is . + /// + descriptor_range push_descriptors; + + /// + /// Used when parameter type is or . + /// + struct + { + uint32_t count; + const descriptor_range *ranges; + } descriptor_table; + }; + }; + + /// + /// An opaque handle to a pipeline layout object. + /// In D3D12 this is a pointer to a 'ID3D12RootSignature' object, in Vulkan a 'VkPipelineLayout' handle. + /// + RESHADE_DEFINE_HANDLE(pipeline_layout); + + /// + /// The fill mode to use when rendering triangles. + /// + enum class fill_mode : uint32_t + { + solid = 0, + wireframe = 1, + point = 2 + }; + + /// + /// Indicates triangles facing a particular direction are not drawn. + /// + enum class cull_mode : uint32_t + { + none = 0, + front = 1, + back = 2, + front_and_back = front | back + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(cull_mode); + + /// + /// The available logic operations. + /// + enum class logic_op : uint32_t + { + clear = 0, + bitwise_and = 1, + bitwise_and_reverse = 2, + copy = 3, + bitwise_and_inverted = 4, + noop = 5, + bitwise_xor = 6, + bitwise_or = 7, + bitwise_nor = 8, + equivalent = 9, + invert = 10, + bitwise_or_reverse = 11, + copy_inverted = 12, + bitwise_or_inverted = 13, + bitwise_nand = 14, + set = 15 + }; + + /// + /// The available color or alpha blending operations. + /// + enum class blend_op : uint32_t + { + add = 0, + subtract = 1, + reverse_subtract = 2, + min = 3, + max = 4 + }; + + /// + /// The available blend factors in color or alpha blending operations. + /// + enum class blend_factor : uint32_t + { + zero = 0, + one = 1, + source_color = 2, + one_minus_source_color = 3, + dest_color = 4, + one_minus_dest_color = 5, + source_alpha = 6, + one_minus_source_alpha = 7, + dest_alpha = 8, + one_minus_dest_alpha = 9, + constant_color = 10, + one_minus_constant_color = 11, + constant_alpha = 12, + one_minus_constant_alpha = 13, + source_alpha_saturate = 14, + source1_color = 15, + one_minus_source1_color = 16, + source1_alpha = 17, + one_minus_source1_alpha = 18 + }; + + /// + /// The available stencil operations that can be performed during depth-stencil testing. + /// + enum class stencil_op : uint32_t + { + keep = 0, + zero = 1, + replace = 2, + increment_saturate = 3, + decrement_saturate = 4, + invert = 5, + increment = 6, + decrement = 7 + }; + + /// + /// Specifies how the pipeline interprets vertex data that is bound to the vertex input stage and subsequently renders it. + /// + enum class primitive_topology : uint32_t + { + undefined = 0, + + point_list = 1, + line_list = 2, + line_strip = 3, + triangle_list = 4, + triangle_strip = 5, + triangle_fan = 6, + quad_list = 8, + quad_strip = 9, + line_list_adj = 10, + line_strip_adj = 11, + triangle_list_adj = 12, + triangle_strip_adj = 13, + + patch_list_01_cp = 33, + patch_list_02_cp, + patch_list_03_cp, + patch_list_04_cp, + patch_list_05_cp, + patch_list_06_cp, + patch_list_07_cp, + patch_list_08_cp, + patch_list_09_cp, + patch_list_10_cp, + patch_list_11_cp, + patch_list_12_cp, + patch_list_13_cp, + patch_list_14_cp, + patch_list_15_cp, + patch_list_16_cp, + patch_list_17_cp, + patch_list_18_cp, + patch_list_19_cp, + patch_list_20_cp, + patch_list_21_cp, + patch_list_22_cp, + patch_list_23_cp, + patch_list_24_cp, + patch_list_25_cp, + patch_list_26_cp, + patch_list_27_cp, + patch_list_28_cp, + patch_list_29_cp, + patch_list_30_cp, + patch_list_31_cp, + patch_list_32_cp + }; + + /// + /// Describes a shader object. + /// + struct shader_desc + { + /// + /// Shader source code or binary. + /// + const void *code = nullptr; + /// + /// Size (in bytes) of the shader source or binary. + /// + size_t code_size = 0; + /// + /// Optional entry point name if the shader source or binary contains multiple entry points. + /// Can be if it does not, or to use the default "main" entry point. + /// + const char *entry_point = nullptr; + + /// + /// Number of entries in the and arrays. + /// This is meaningful only when the shader binary is a SPIR-V module and is ignored otherwise. + /// + uint32_t spec_constants = 0; + /// + /// Pointer to an array of specialization constant indices. + /// + const uint32_t *spec_constant_ids = nullptr; + /// + /// Pointer to an array of constant values, one for each specialization constant index in . + /// + const uint32_t *spec_constant_values = nullptr; + }; + + /// + /// Describes a single element in the vertex layout for the input-assembler stage. + /// + struct input_element + { + /// + /// GLSL attribute location associated with this element (layout(location = X)). + /// + uint32_t location = 0; + /// + /// HLSL semantic associated with this element. + /// + const char *semantic = nullptr; + /// + /// Optional index for the HLSL semantic (e.g. for "TEXCOORD1" set to "TEXCOORD" and to 1). + /// + uint32_t semantic_index = 0; + /// + /// Format of the element data. + /// + format format = format::unknown; + /// + /// Index of the vertex buffer binding. + /// + uint32_t buffer_binding = 0; + /// + /// Offset (in bytes) from the start of the vertex to this element. + /// + uint32_t offset = 0; + /// + /// Stride of the entire vertex (this has to be consistent for all elements per vertex buffer binding). + /// Set to zero in case this is unknown. + /// + uint32_t stride = 0; + /// + /// Number of instances to draw using the same per-instance data before advancing by one element. + /// This has to be consistent for all elements per vertex buffer binding. + /// Set to zero to indicate that this element is per-vertex rather than per-instance. + /// + uint32_t instance_step_rate = 0; + }; + + /// + /// Describes the state of the stream-output stage. + /// + struct stream_output_desc + { + /// + /// Index of the stream output stream to be sent to the rasterizer stage. + /// + uint32_t rasterized_stream = 0; + }; + + /// + /// Describes the state of the output-merger stage. + /// + struct blend_desc + { + /// + /// Use alpha-to-coverage as a multisampling technique when setting a pixel to a render target. + /// + bool alpha_to_coverage_enable = false; + /// + /// Enable or disable blending for each render target. + /// + /// + bool blend_enable[8] = { false, false, false, false, false, false, false, false }; + /// + /// Enable or disable a logical operation for each render target. + /// + /// + bool logic_op_enable[8] = { false, false, false, false, false, false, false, false }; + /// + /// Source to use for the RGB value that the pixel shader outputs. + /// + /// + blend_factor source_color_blend_factor[8] = { blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one }; + /// + /// Destination to use for the current RGB value in the render target. + /// + /// + blend_factor dest_color_blend_factor[8] = { blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero }; + /// + /// Operation to use to combine and . + /// + /// + blend_op color_blend_op[8] = { blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add }; + /// + /// Source to use for the alpha value that the pixel shader outputs. + /// + /// + blend_factor source_alpha_blend_factor[8] = { blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one, blend_factor::one }; + /// + /// Destination to use for the current alpha value in the render target. + /// + /// + blend_factor dest_alpha_blend_factor[8] = { blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero, blend_factor::zero }; + /// + /// Operation to use to combine and . + /// + /// + blend_op alpha_blend_op[8] = { blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add, blend_op::add }; + /// + /// Constant RGBA value to use when or is . + /// + float blend_constant[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + /// + /// Logical operation for each render target. Ignored if is . + /// + /// + logic_op logic_op[8] = { logic_op::noop, logic_op::noop, logic_op::noop, logic_op::noop, logic_op::noop, logic_op::noop, logic_op::noop, logic_op::noop }; + /// + /// A write mask specifying which color components are written to each render target. Bitwise combination of 0x1 for red, 0x2 for green, 0x4 for blue and 0x8 for alpha. + /// + uint8_t render_target_write_mask[8] = { 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF }; + }; + + /// + /// Describes the state of the rasterizer stage. + /// + struct rasterizer_desc + { + /// + /// Fill mode to use when rendering triangles. + /// + /// + fill_mode fill_mode = fill_mode::solid; + /// + /// Triangles facing the specified direction are not drawn. + /// + cull_mode cull_mode = cull_mode::back; + /// + /// Determines if a triangle is front or back-facing. + /// + bool front_counter_clockwise = false; + /// + /// Depth value added to a given pixel. + /// + float depth_bias = 0.0f; + /// + /// Maximum depth bias of a pixel. + /// + float depth_bias_clamp = 0.0f; + /// + /// Scalar on the slope of a given pixel. + /// + float slope_scaled_depth_bias = 0.0f; + /// + /// Enable or disable clipping based on distance. + /// + bool depth_clip_enable = true; + /// + /// Enable or disable scissor testing (scissor rectangle culling). + /// + bool scissor_enable = false; + /// + /// Use the quadrilateral or alpha line anti-aliasing algorithm on multisample antialiasing render targets. + /// + bool multisample_enable = false; + /// + /// Enable or disable line antialiasing. Only applies if doing line drawing and is . + /// + bool antialiased_line_enable = false; + /// + /// Enable or disable conservative rasterization mode. + /// + /// + uint32_t conservative_rasterization = 0; + }; + + /// + /// Describes the state of the depth-stencil stage. + /// + struct depth_stencil_desc + { + /// + /// Enable or disable depth testing. + /// + bool depth_enable = true; + /// + /// Enable or disable writes to the depth-stencil buffer. + /// + bool depth_write_mask = true; + /// + /// Comparison function to use to compare new depth value from a fragment against current depth value in the depth-stencil buffer. + /// + compare_op depth_func = compare_op::less; + /// + /// Enable or disable stencil testing. + /// + bool stencil_enable = false; + /// + /// Mask applied to stencil values read from the depth-stencil buffer for pixels whose surface normal is towards the camera. + /// + uint8_t front_stencil_read_mask = 0xFF; + /// + /// Mask applied to stencil values written to the depth-stencil buffer for pixels whose surface normal is towards the camera. + /// + uint8_t front_stencil_write_mask = 0xFF; + /// + /// Reference value to perform against when stencil testing pixels whose surface normal is towards the camera. + /// + uint8_t front_stencil_reference_value = 0; + /// + /// Comparison function to use to compare new stencil value from a fragment against current stencil value for pixels whose surface normal is facing towards the camera. + /// + compare_op front_stencil_func = compare_op::always; + /// + /// Stencil operation to perform when stencil testing and depth testing both pass for pixels whose surface normal is facing towards the camera. + /// + stencil_op front_stencil_pass_op = stencil_op::keep; + /// + /// Stencil operation to perform when stencil testing fails for pixels whose surface normal is towards the camera. + /// + stencil_op front_stencil_fail_op = stencil_op::keep; + /// + /// Stencil operation to perform when stencil testing passes and depth testing fails for pixels whose surface normal is facing towards the camera. + /// + stencil_op front_stencil_depth_fail_op = stencil_op::keep; + /// + /// Mask applied to stencil values read from the depth-stencil buffer for pixels whose surface normal is facing away from the camera. + /// + uint8_t back_stencil_read_mask = 0xFF; + /// + /// Mask applied to stencil values written to the depth-stencil buffer for pixels whose surface normal is facing away from the camera. + /// + uint8_t back_stencil_write_mask = 0xFF; + /// + /// Reference value to perform against when stencil testing pixels whose surface normal is facing away from the camera. + /// + uint8_t back_stencil_reference_value = 0; + /// + /// Comparison function to use to compare new stencil value from a fragment against current stencil value for pixels whose surface normal is facing away from the camera. + /// + compare_op back_stencil_func = compare_op::always; + /// + /// Stencil operation to perform when stencil testing and depth testing both pass for pixels whose surface normal is facing away from the camera. + /// + stencil_op back_stencil_pass_op = stencil_op::keep; + /// + /// Stencil operation to perform when stencil testing fails for pixels whose surface normal is facing away from the camera. + /// + stencil_op back_stencil_fail_op = stencil_op::keep; + /// + /// Stencil operation to perform when stencil testing passes and depth testing fails for pixels whose surface normal is facing away from the camera. + /// + stencil_op back_stencil_depth_fail_op = stencil_op::keep; + }; + + /// + /// The available pipeline sub-object types. + /// + enum class pipeline_subobject_type : uint32_t + { + unknown, + + /// + /// Vertex shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + vertex_shader, + /// + /// Hull shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + hull_shader, + /// + /// Domain shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + domain_shader, + /// + /// Geometry shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + geometry_shader, + /// + /// Pixel shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + pixel_shader, + /// + /// Compute shader to use. + /// Sub-object data is a pointer to a . + /// + /// + /// + compute_shader, + /// + /// Vertex layout for the input-assembler stage. + /// Sub-object data is a pointer to an array of . + /// + /// + input_layout, + /// + /// State of the stream-output stage. + /// Sub-object data is a pointer to a . + /// + /// + stream_output_state, + /// + /// State of the output-merger stage. + /// Sub-object data is a pointer to a . + /// + /// + blend_state, + /// + /// State of the rasterizer stage. + /// Sub-object data is a pointer to a . + /// + /// + rasterizer_state, + /// + /// State of the depth-stencil stage. + /// Sub-object data is a pointer to a . + /// + /// + depth_stencil_state, + /// + /// Primitive topology to use when rendering. + /// Sub-object data is a pointer to a value. + /// + primitive_topology, + /// + /// Format of the depth-stencil view that may be used with this pipeline. + /// Sub-object data is a pointer to a value. + /// + depth_stencil_format, + /// + /// Formats of the render target views that may be used with this pipeline. + /// Sub-object data is a pointer to an array of values. + /// + render_target_formats, + /// + /// Mask applied to the coverage mask for a fragment during rasterization. + /// Sub-object data is a pointer to a 32-bit unsigned integer value. + /// + sample_mask, + /// + /// Number of samples used in rasterization. + /// Sub-object data is a pointer to a 32-bit unsigned integer value. + /// + sample_count, + /// + /// Maximum number of viewports that may be bound via with this pipeline. + /// Sub-object data is a pointer to a 32-bit unsigned integer value. + /// + viewport_count, + /// + /// States that may be dynamically updated via after binding this pipeline. + /// Sub-object data is a pointer to an array of values. + /// + dynamic_pipeline_states, + /// + /// Maximum number of vertices a draw call with this pipeline will draw. + /// Sub-object data is a pointer to a 32-bit unsigned integer value. + /// + max_vertex_count + }; + + /// + /// Describes a pipeline sub-object. + /// + struct pipeline_subobject + { + /// + /// Type of the specified sub-object . + /// + pipeline_subobject_type type = pipeline_subobject_type::unknown; + /// + /// Number of sub-object descriptions. + /// This should usually be 1, except for array sub-objects like (where this specifies the number of render targets) or . + /// + uint32_t count = 0; + /// + /// Pointer to an array of sub-object descriptions (which should be as large as the specified ). + /// Depending on the sub-object this should be a pointer to a , , , or ... + /// + void *data = nullptr; + }; + + /// + /// An opaque handle to a pipeline state object. + /// In D3D9, D3D10, D3D11 or D3D12 this is a pointer to a 'IDirect3D(...)Shader', 'ID3D10(...)(Shader/State)', 'ID3D11(...)(Shader/State)' or 'ID3D12PipelineState' object, in Vulkan a 'VkPipeline' handle. + /// + RESHADE_DEFINE_HANDLE(pipeline); + + /// + /// A constant buffer resource descriptor. + /// + struct buffer_range + { + /// + /// Constant buffer resource. + /// + resource buffer = { 0 }; + /// + /// Offset from the start of the buffer resource (in bytes). + /// + uint64_t offset = 0; + /// + /// Number of elements this range covers in the buffer resource (in bytes). + /// Set to -1 (UINT64_MAX) to indicate that the whole buffer should be used. + /// + uint64_t size = UINT64_MAX; + }; + + /// + /// A combined sampler and resource view descriptor. + /// + struct sampler_with_resource_view + { + /// + /// Sampler to sampler the shader resource view with. + /// + sampler sampler = { 0 }; + /// + /// Shader resource view. + /// + resource_view view = { 0 }; + }; + + /// + /// An opaque handle to a descriptor table in a descriptor heap. + /// In Vulkan this is a 'VkDescriptorSet' handle. + /// + RESHADE_DEFINE_HANDLE(descriptor_table); + + /// + /// All information needed to copy descriptors between descriptor tables. + /// + struct descriptor_table_copy + { + /// + /// Descriptor table to copy from. + /// + descriptor_table source_table = { 0 }; + /// + /// Index of the binding in the source descriptor table. + /// + uint32_t source_binding = 0; + /// + /// Array index in the specified source binding to begin copying from. + /// + uint32_t source_array_offset = 0; + /// + /// Descriptor table to copy to. + /// + descriptor_table dest_table = { 0 }; + /// + /// Index of the binding in the destination descriptor table. + /// + uint32_t dest_binding = 0; + /// + /// Array index in the specified destination binding to begin copying to. + /// + uint32_t dest_array_offset = 0; + /// + /// Number of descriptors to copy. + /// + uint32_t count = 0; + }; + + /// + /// All information needed to update descriptors in a descriptor table. + /// + struct descriptor_table_update + { + /// + /// Descriptor table to update. + /// + descriptor_table table = { 0 }; + /// + /// OpenGL/Vulkan binding index in the descriptor set. + /// In D3D this is equivalent to the offset (in descriptors) from the start of the table. + /// + uint32_t binding = 0; + /// + /// Array index in the specified to begin updating at. + /// Only meaningful in Vulkan, in OpenGL and other APIs this has to be 0 (since each array element gets a separate binding). + /// + uint32_t array_offset = 0; + /// + /// Number of descriptors to update, starting at the specified . + /// If the specified has fewer than array elements starting from , then the remainder will be used to update the subsequent binding starting at array element zero, recursively. + /// + uint32_t count = 0; + /// + /// Type of the specified . + /// + descriptor_type type = descriptor_type::sampler; + /// + /// Pointer to an array of descriptors to update in the descriptor table (which should be as large as the specified ). + /// Depending on the descriptor this should be pointer to an array of , , or . + /// + const void *descriptors = nullptr; + }; + + /// + /// An opaque handle to a descriptor heap. + /// In D3D12 this is a pointer to a 'ID3D12DescriptorHeap' object, in Vulkan a 'VkDescriptorPool' handle. + /// + RESHADE_DEFINE_HANDLE(descriptor_heap); + + /// + /// The available query types. + /// + enum class query_type + { + occlusion = 0, + binary_occlusion = 1, + timestamp = 2, + pipeline_statistics = 3, + stream_output_statistics_0 = 4, + stream_output_statistics_1, + stream_output_statistics_2, + stream_output_statistics_3 + }; + + /// + /// An opaque handle to a query heap. + /// In D3D12 this is a pointer to a 'ID3D12QueryHeap' object, in Vulkan a 'VkQueryPool' handle. + /// + RESHADE_DEFINE_HANDLE(query_heap); + + /// + /// A list of all possible render pipeline states that can be set independent of pipeline state objects. + /// Support for these varies between render APIs (e.g. modern APIs like D3D12 and Vulkan support much less dynamic states than D3D9). + /// + enum class dynamic_state + { + unknown = 0, + + alpha_test_enable = 15, + alpha_reference_value = 24, + alpha_func = 25, + srgb_write_enable = 194, + primitive_topology = 1000, + sample_mask = 162, + + // Blend state + + alpha_to_coverage_enable = 1003, + blend_enable = 27, + logic_op_enable = 1004, + source_color_blend_factor = 19, + dest_color_blend_factor = 20, + color_blend_op = 171, + source_alpha_blend_factor = 207, + dest_alpha_blend_factor = 208, + alpha_blend_op = 209, + blend_constant = 193, + logic_op = 1005, + render_target_write_mask = 168, + + // Rasterizer state + + fill_mode = 8, + cull_mode = 22, + front_counter_clockwise = 1001, + depth_bias = 195, + depth_bias_clamp = 1002, + depth_bias_slope_scaled = 175, + depth_clip_enable = 136, + scissor_enable = 174, + multisample_enable = 161, + antialiased_line_enable = 176, + + // Depth-stencil state + + depth_enable = 7, + depth_write_mask = 14, + depth_func = 23, + stencil_enable = 52, + front_stencil_read_mask = 58, + front_stencil_write_mask = 59, + front_stencil_reference_value = 57, + front_stencil_func = 56, + front_stencil_pass_op = 55, + front_stencil_fail_op = 53, + front_stencil_depth_fail_op = 54, + back_stencil_read_mask = 1006, + back_stencil_write_mask = 1007, + back_stencil_reference_value = 1008, + back_stencil_func = 189, + back_stencil_pass_op = 188, + back_stencil_fail_op = 186, + back_stencil_depth_fail_op = 187, + }; + + /// + /// Describes a rectangle. + /// + struct rect + { + int32_t left = 0; + int32_t top = 0; + int32_t right = 0; + int32_t bottom = 0; + + constexpr uint32_t width() const { return right - left; } + constexpr uint32_t height() const { return bottom - top; } + }; + + /// + /// Describes a render viewport. + /// + struct viewport + { + float x = 0.0f; + float y = 0.0f; + float width = 0.0f; + float height = 0.0f; + float min_depth = 0.0f; + float max_depth = 1.0f; + }; +} } diff --git a/Plugin/include/reshade/reshade_api_resource.hpp b/Plugin/include/reshade/reshade_api_resource.hpp new file mode 100644 index 00000000..9da2df04 --- /dev/null +++ b/Plugin/include/reshade/reshade_api_resource.hpp @@ -0,0 +1,528 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#define RESHADE_DEFINE_HANDLE(name) \ + typedef struct { uint64_t handle; } name; \ + constexpr bool operator< (name lhs, name rhs) { return lhs.handle < rhs.handle; } \ + constexpr bool operator!=(name lhs, name rhs) { return lhs.handle != rhs.handle; } \ + constexpr bool operator!=(name lhs, uint64_t rhs) { return lhs.handle != rhs; } \ + constexpr bool operator==(name lhs, name rhs) { return lhs.handle == rhs.handle; } \ + constexpr bool operator==(name lhs, uint64_t rhs) { return lhs.handle == rhs; } + +#define RESHADE_DEFINE_ENUM_FLAG_OPERATORS(type) \ + constexpr type operator~(type a) { return static_cast(~static_cast(a)); } \ + inline type &operator&=(type &a, type b) { return reinterpret_cast(reinterpret_cast(a) &= static_cast(b)); } \ + constexpr type operator&(type a, type b) { return static_cast(static_cast(a) & static_cast(b)); } \ + inline type &operator|=(type &a, type b) { return reinterpret_cast(reinterpret_cast(a) |= static_cast(b)); } \ + constexpr type operator|(type a, type b) { return static_cast(static_cast(a) | static_cast(b)); } \ + inline type &operator^=(type &a, type b) { return reinterpret_cast(reinterpret_cast(a) ^= static_cast(b)); } \ + constexpr type operator^(type a, type b) { return static_cast(static_cast(a) ^ static_cast(b)); } \ + constexpr bool operator==(type lhs, uint32_t rhs) { return static_cast(lhs) == rhs; } \ + constexpr bool operator!=(type lhs, uint32_t rhs) { return static_cast(lhs) != rhs; } + +#include "reshade_api_format.hpp" + +namespace reshade { namespace api +{ + /// + /// The available comparison types. + /// + enum class compare_op : uint32_t + { + never = 0, + less = 1, + equal = 2, + less_equal = 3, + greater = 4, + not_equal = 5, + greater_equal = 6, + always = 7 + }; + + /// + /// The available filtering modes used for texture sampling operations. + /// + enum class filter_mode : uint32_t + { + min_mag_mip_point = 0, + min_mag_point_mip_linear = 0x1, + min_point_mag_linear_mip_point = 0x4, + min_point_mag_mip_linear = 0x5, + min_linear_mag_mip_point = 0x10, + min_linear_mag_point_mip_linear = 0x11, + min_mag_linear_mip_point = 0x14, + min_mag_mip_linear = 0x15, + min_mag_anisotropic_mip_point = 0x54, + anisotropic = 0x55, + compare_min_mag_mip_point = 0x80, + compare_min_mag_point_mip_linear = 0x81, + compare_min_point_mag_linear_mip_point = 0x84, + compare_min_point_mag_mip_linear = 0x85, + compare_min_linear_mag_mip_point = 0x90, + compare_min_linear_mag_point_mip_linear = 0x91, + compare_min_mag_linear_mip_point = 0x94, + compare_min_mag_mip_linear = 0x95, + compare_min_mag_anisotropic_mip_point = 0xd4, + compare_anisotropic = 0xd5 + }; + + /// + /// Specifies behavior of sampling with texture coordinates outside a texture resource. + /// + enum class texture_address_mode : uint32_t + { + wrap = 1, + mirror = 2, + clamp = 3, + border = 4, + mirror_once = 5 + }; + + /// + /// Describes a sampler state. + /// + struct sampler_desc + { + /// + /// Filtering mode to use when sampling a texture. + /// + filter_mode filter = filter_mode::min_mag_mip_linear; + /// + /// Method to use for resolving U texture coordinates outside 0 to 1 range. + /// + texture_address_mode address_u = texture_address_mode::clamp; + /// + /// Method to use for resolving V texture coordinates outside 0 to 1 range. + /// + texture_address_mode address_v = texture_address_mode::clamp; + /// + /// Method to use for resolving W texture coordinates outside 0 to 1 range. + /// + texture_address_mode address_w = texture_address_mode::clamp; + /// + /// Offset applied to the calculated mipmap level when sampling a texture. + /// + float mip_lod_bias = 0.0f; + /// + /// Clamping value to use when filtering mode is . + /// + float max_anisotropy = 1.0f; + /// + /// Comparison function to use to compare sampled data against existing sampled data. + /// + compare_op compare_op = compare_op::never; + /// + /// RGBA value to return for texture coordinates outside 0 to 1 range when addressing mode is . + /// + float border_color[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + /// + /// Lower end of the mipmap range to clamp access to. + /// + float min_lod = -FLT_MAX; + /// + /// Upper end of the mipmap range to clamp access to. + /// + float max_lod = +FLT_MAX; + }; + + /// + /// An opaque handle to a sampler state object. + /// Depending on the render API this can be a pointer to a 'ID3D10SamplerState', 'ID3D11SamplerState' or a 'D3D12_CPU_DESCRIPTOR_HANDLE' (to a sampler descriptor) or 'VkSampler' handle. + /// + RESHADE_DEFINE_HANDLE(sampler); + + /// + /// The available memory mapping access types. + /// + enum class map_access + { + read_only = 1, + write_only, + read_write, + write_discard + }; + + /// + /// The available memory heap types, which give a hint as to where to place the memory allocation for a resource. + /// + enum class memory_heap : uint32_t + { + unknown, // Usually indicates a resource that is reserved, but not yet bound to any memory. + gpu_only, + // Upload heap + cpu_to_gpu, + // Readback heap + gpu_to_cpu, + cpu_only, + custom + }; + + /// + /// The available resource types. The type of a resource is specified during creation and is immutable. + /// Various operations may have special requirements on the type of resources they operate on (e.g. copies can only happen between resources of the same type, ...). + /// + enum class resource_type : uint32_t + { + unknown, + buffer, + texture_1d, + texture_2d, + texture_3d, + surface // Special type for resources that are implicitly both resource and render target view. + }; + + /// + /// A list of flags that describe additional parameters of a resource. + /// + enum class resource_flags : uint32_t + { + none = 0, + dynamic = (1 << 3), + cube_compatible = (1 << 2), + generate_mipmaps = (1 << 0), + shared = (1 << 1), + shared_nt_handle = (1 << 11), + structured = (1 << 6), + sparse_binding = (1 << 18) + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(resource_flags); + + /// + /// A list of flags that specify how a resource is to be used. + /// This needs to be specified during creation and is also used to transition between different resource states within a command list. + /// + enum class resource_usage : uint32_t + { + undefined = 0, + + index_buffer = 0x2, + vertex_buffer = 0x1, + constant_buffer = 0x8000, + stream_output = 0x100, + indirect_argument = 0x200, + + depth_stencil = 0x30, + depth_stencil_read = 0x20, + depth_stencil_write = 0x10, + render_target = 0x4, + shader_resource = 0xC0, + shader_resource_pixel = 0x80, + shader_resource_non_pixel = 0x40, + unordered_access = 0x8, + + copy_dest = 0x400, + copy_source = 0x800, + resolve_dest = 0x1000, + resolve_source = 0x2000, + + // The following are special resource states and may only be used in barriers: + + general = 0x80000000, + present = 0x80000000 | render_target | copy_source, + cpu_access = vertex_buffer | index_buffer | shader_resource | indirect_argument | copy_source + }; + RESHADE_DEFINE_ENUM_FLAG_OPERATORS(resource_usage); + + /// + /// Describes a resource, such as a buffer or texture. + /// + struct [[nodiscard]] resource_desc + { + constexpr resource_desc() : texture() {} + constexpr resource_desc(uint64_t size, memory_heap heap, resource_usage usage) : + type(resource_type::buffer), buffer({ size }), heap(heap), usage(usage) {} + constexpr resource_desc(uint32_t width, uint32_t height, uint16_t layers, uint16_t levels, format format, uint16_t samples, memory_heap heap, resource_usage usage, resource_flags flags = resource_flags::none) : + type(resource_type::texture_2d), texture({ width, height, layers, levels, format, samples }), heap(heap), usage(usage), flags(flags) {} + constexpr resource_desc(resource_type type, uint32_t width, uint32_t height, uint16_t depth_or_layers, uint16_t levels, format format, uint16_t samples, memory_heap heap, resource_usage usage, resource_flags flags = resource_flags::none) : + type(type), texture({ width, height, depth_or_layers, levels, format, samples }), heap(heap), usage(usage), flags(flags) {} + + /// + /// Type of the resource. + /// + resource_type type = resource_type::unknown; + + union + { + /// + /// Used when resource type is a buffer. + /// + struct + { + /// + /// Size of the buffer (in bytes). + /// + uint64_t size = 0; + /// + /// Structure stride for structured buffers (in bytes), otherwise zero. + /// + uint32_t stride = 0; + } buffer; + + /// + /// Used when resource type is a texture or surface. + /// + struct + { + /// + /// Width of the texture (in texels). + /// + uint32_t width = 1; + /// + /// If this is a 2D or 3D texture, height of the texture (in texels), otherwise 1. + /// + uint32_t height = 1; + /// + /// If this is a 3D texture, depth of the texture (in texels), otherwise number of array layers. + /// + uint16_t depth_or_layers = 1; + /// + /// Maximum number of mipmap levels in the texture, including the base level, so at least 1. + /// Can also be zero in case the exact number of mipmap levels is unknown. + /// + uint16_t levels = 1; + /// + /// Data format of each texel in the texture. + /// + format format = format::unknown; + /// + /// The number of samples per texel. Set to a value higher than 1 for multisampling. + /// + uint16_t samples = 1; + } texture; + }; + + /// + /// Memory heap the resource allocation is placed in. + /// + memory_heap heap = memory_heap::unknown; + /// + /// Flags that specify how this resource may be used. + /// + resource_usage usage = resource_usage::undefined; + /// + /// Flags that describe additional parameters. + /// + resource_flags flags = resource_flags::none; + }; + + /// + /// An opaque handle to a resource object (buffer, texture, ...). + /// Resources created by the application are only guaranteed to be valid during event callbacks. + /// Depending on the render API this can be a pointer to a 'IDirect3DResource9', 'ID3D10Resource', 'ID3D11Resource' or 'ID3D12Resource' object or a 'VkImage' handle. + /// + RESHADE_DEFINE_HANDLE(resource); + + /// + /// The available resource view types. These identify how a resource view interprets the data of its resource. + /// + enum class resource_view_type : uint32_t + { + unknown, + buffer, + texture_1d, + texture_1d_array, + texture_2d, + texture_2d_array, + texture_2d_multisample, + texture_2d_multisample_array, + texture_3d, + texture_cube, + texture_cube_array + }; + + /// + /// Describes a resource view, which specifies how to interpret the data of a resource. + /// + struct [[nodiscard]] resource_view_desc + { + constexpr resource_view_desc() : texture() {} + constexpr resource_view_desc(format format, uint64_t offset, uint64_t size) : + type(resource_view_type::buffer), format(format), buffer({ offset, size }) {} + constexpr resource_view_desc(format format, uint32_t first_level, uint32_t levels, uint32_t first_layer, uint32_t layers) : + type(resource_view_type::texture_2d), format(format), texture({ first_level, levels, first_layer, layers }) {} + constexpr resource_view_desc(resource_view_type type, format format, uint32_t first_level, uint32_t levels, uint32_t first_layer, uint32_t layers) : + type(type), format(format), texture({ first_level, levels, first_layer, layers }) {} + constexpr explicit resource_view_desc(format format) : type(resource_view_type::texture_2d), format(format), texture({ 0, 1, 0, 1 }) {} + + /// + /// Resource type the view should interpret the resource data to. + /// + resource_view_type type = resource_view_type::unknown; + /// + /// Format the view should reinterpret the resource data to (can be different than the format of the resource as long as they are compatible). + /// + format format = format::unknown; + + union + { + /// + /// Used when view type is a buffer. + /// + struct + { + /// + /// Offset from the start of the buffer resource (in bytes). + /// + uint64_t offset = 0; + /// + /// Number of elements this view covers in the buffer resource (in bytes). + /// Set to -1 (UINT64_MAX) to indicate that the entire buffer resource should be used. + /// + uint64_t size = UINT64_MAX; + } buffer; + + /// + /// Used when view type is a texture. + /// + struct + { + /// + /// Index of the most detailed mipmap level to use. This number has to be between zero and the maximum number of mipmap levels in the texture minus 1. + /// + uint32_t first_level = 0; + /// + /// Maximum number of mipmap levels for the view of the texture. + /// Set to -1 (UINT32_MAX) to indicate that all mipmap levels down to the least detailed should be used. + /// + uint32_t level_count = UINT32_MAX; + /// + /// Index of the first array layer of the texture array to use. This value is ignored if the texture is not layered. + /// + uint32_t first_layer = 0; + /// + /// Maximum number of array layers for the view of the texture array. This value is ignored if the texture is not layered. + /// Set to -1 (UINT32_MAX) to indicate that all array layers should be used. + /// + uint32_t layer_count = UINT32_MAX; + } texture; + }; + }; + + /// + /// An opaque handle to a resource view object (depth-stencil, render target, shader resource view, ...). + /// Resource views created by the application are only guaranteed to be valid during event callbacks. + /// Depending on the render API this can be a pointer to a 'IDirect3DResource9', 'ID3D10View' or 'ID3D11View' object, or a 'D3D12_CPU_DESCRIPTOR_HANDLE' (to a view descriptor) or 'VkImageView' handle. + /// + RESHADE_DEFINE_HANDLE(resource_view); + + /// + /// Describes a region inside a subresource. + /// + struct subresource_box + { + int32_t left = 0; + int32_t top = 0; + int32_t front = 0; + int32_t right = 0; + int32_t bottom = 0; + int32_t back = 0; + + constexpr uint32_t width() const { return right - left; } + constexpr uint32_t height() const { return bottom - top; } + constexpr uint32_t depth() const { return back - front; } + }; + + /// + /// Describes the data of a subresource. + /// + struct subresource_data + { + /// + /// Pointer to the data. + /// + void *data = nullptr; + /// + /// Row pitch of the data (added to the data pointer to move between texture rows, unused for buffers and 1D textures). + /// + /// + uint32_t row_pitch = 0; + /// + /// Depth pitch of the data (added to the data pointer to move between texture depth/array slices, unused for buffers and 1D/2D textures). + /// + /// + uint32_t slice_pitch = 0; + }; + + /// + /// Specifies how the contents of a render target or depth-stencil view are treated at the start of a render pass. + /// + enum class render_pass_load_op : uint32_t + { + load, + clear, + discard, + no_access + }; + + /// + /// Specifies how the contents of a render target or depth-stencil view are treated at the end of a render pass. + /// + enum class render_pass_store_op : uint32_t + { + store, + discard, + no_access + }; + + /// + /// Describes a depth-stencil view and how it is treated at the start and end of a render pass. + /// + struct render_pass_depth_stencil_desc + { + /// + /// Depth-stencil resource view. + /// + resource_view view = { 0 }; + /// + /// Specifies how the depth contents of the depth-stencil view are treated at the start of the render pass. + /// + render_pass_load_op depth_load_op = render_pass_load_op::load; + /// + /// Specifies how the depth contents of the depth-stencil view are treated at the end of the render pass. + /// + render_pass_store_op depth_store_op = render_pass_store_op::store; + /// + /// Specifies how the stencil contents of the depth-stencil view are treated at the start of the render pass. + /// + render_pass_load_op stencil_load_op = render_pass_load_op::load; + /// + /// Specifies how the stencil contents of the depth-stencil view are treated at the end of the render pass. + /// + render_pass_store_op stencil_store_op = render_pass_store_op::store; + /// + /// Value the depth contents of the depth-stencil resource is cleared to when is . + /// + float clear_depth = 0.0f; + /// + /// Value the stencil contents of the depth-stencil resource is cleared to when is . + /// + uint8_t clear_stencil = 0; + }; + + /// + /// Describes a render target view and how it is treated at the start and end of a render pass. + /// + struct render_pass_render_target_desc + { + /// + /// Render target resource view. + /// + resource_view view = { 0 }; + /// + /// Specifies how the contents of the render target view are treated at the start of the render pass. + /// + render_pass_load_op load_op = render_pass_load_op::load; + /// + /// Specifies how the contents of the render target view are treated at the end of the render pass. + /// + render_pass_store_op store_op = render_pass_store_op::store; + /// + /// Value the render target resource is cleared to when is . + /// + float clear_color[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + }; +} } diff --git a/Plugin/include/reshade/reshade_events.hpp b/Plugin/include/reshade/reshade_events.hpp new file mode 100644 index 00000000..52eeb61b --- /dev/null +++ b/Plugin/include/reshade/reshade_events.hpp @@ -0,0 +1,1696 @@ +/* + * Copyright (C) 2021 Patrick Mours + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#pragma once + +#include "reshade_api.hpp" + +namespace reshade +{ + enum class addon_event : uint32_t + { + /// + /// Called after successfull device creation, from: + /// + /// IDirect3D9::CreateDevice + /// IDirect3D9Ex::CreateDeviceEx + /// IDirect3DDevice9::Reset + /// IDirect3DDevice9Ex::ResetEx + /// D3D10CreateDevice + /// D3D10CreateDevice1 + /// D3D10CreateDeviceAndSwapChain + /// D3D10CreateDeviceAndSwapChain1 + /// D3D11CreateDevice + /// D3D11CreateDeviceAndSwapChain + /// D3D12CreateDevice + /// glMakeCurrent + /// vkCreateDevice + /// + /// Callback function signature: void (api::device *device) + /// + init_device, + + /// + /// Called on device destruction, before: + /// + /// IDirect3DDevice9::Reset + /// IDirect3DDevice9Ex::ResetEx + /// IDirect3DDevice9::Release + /// ID3D10Device::Release + /// ID3D11Device::Release + /// ID3D12Device::Release + /// wglDeleteContext + /// vkDestroyDevice + /// + /// Callback function signature: void (api::device *device) + /// + destroy_device, + + /// + /// Called after successfull command list creation, from: + /// + /// ID3D11Device::CreateDeferredContext + /// ID3D11Device1::CreateDeferredContext1 + /// ID3D11Device2::CreateDeferredContext2 + /// ID3D11Device3::CreateDeferredContext3 + /// ID3D12Device::CreateCommandList + /// ID3D12Device4::CreateCommandList1 + /// vkAllocateCommandBuffers + /// + /// Callback function signature: void (api::command_list *cmd_list) + /// + /// + /// In case of D3D9, D3D10, D3D11 and OpenGL this is called during device initialization as well and behaves as if an implicit immediate command list was created. + /// + init_command_list, + + /// + /// Called on command list destruction, before: + /// + /// ID3D11CommandList::Release + /// ID3D12CommandList::Release + /// vkFreeCommandBuffers + /// + /// Callback function signature: void (api::command_list *cmd_list) + /// + destroy_command_list, + + /// + /// Called after successfull command queue creation, from: + /// + /// ID3D12Device::CreateCommandQueue + /// vkCreateDevice (for every queue associated with the device) + /// + /// Callback function signature: void (api::command_queue *queue) + /// + /// + /// In case of D3D9, D3D10, D3D11 and OpenGL this is called during device initialization as well and behaves as if an implicit command queue was created. + /// + init_command_queue, + + /// + /// Called on command queue destruction, before: + /// + /// ID3D12CommandQueue::Release + /// vkDestroyDevice (for every queue associated with the device) + /// + /// Callback function signature: void (api::command_queue *queue) + /// + destroy_command_queue, + + /// + /// Called after successfull swap chain creation, from: + /// + /// IDirect3D9::CreateDevice (for the implicit swap chain) + /// IDirect3D9Ex::CreateDeviceEx (for the implicit swap chain) + /// IDirect3D9Device::CreateAdditionalSwapChain + /// IDirect3DDevice9::Reset (for the implicit swap chain) + /// IDirect3DDevice9Ex::ResetEx (for the implicit swap chain) + /// IDXGIFactory::CreateSwapChain + /// IDXGIFactory2::CreateSwapChain(...) + /// IDXGISwapChain::ResizeBuffers + /// IDXGISwapChain3::ResizeBuffers1 + /// wglMakeCurrent + /// wglSwapBuffers (after window was resized) + /// vkCreateSwapchainKHR + /// + /// Callback function signature: void (api::swapchain *swapchain) + /// + init_swapchain, + + /// + /// Called on swap chain creation, before: + /// + /// IDirect3D9::CreateDevice (for the implicit swap chain) + /// IDirect3D9Ex::CreateDeviceEx (for the implicit swap chain) + /// IDirect3D9Device::CreateAdditionalSwapChain + /// IDirect3D9Device::Reset (for the implicit swap chain) + /// IDirect3D9DeviceEx::ResetEx (for the implicit swap chain) + /// IDXGIFactory::CreateSwapChain + /// IDXGIFactory2::CreateSwapChain(...) + /// IDXGISwapChain::ResizeBuffers + /// IDXGISwapChain3::ResizeBuffers1 + /// wglSetPixelFormat + /// vkCreateSwapchainKHR + /// + /// Callback function signature: bool (api::swapchain_desc &desc, void *hwnd) + /// + /// + /// To overwrite the swap chain description, modify desc in the callback and return , otherwise return . + /// + create_swapchain, + + /// + /// Called on swap chain destruction, before: + /// + /// IDirect3DDevice9::Release (for the implicit swap chain) + /// IDirect3DSwapChain9::Release + /// IDXGISwapChain::Release + /// wglDeleteContext + /// wglSwapBuffers (after window was resized) + /// vkDestroySwapchainKHR + /// + /// In addition, called when swap chain is reset, before: + /// + /// IDirect3DDevice9::Reset (for the implicit swap chain) + /// IDirect3DDevice9Ex::ResetEx (for the implicit swap chain) + /// IDXGISwapChain::ResizeBuffers + /// IDXGISwapChain1::ResizeBuffers1 + /// + /// Callback function signature: void (api::swapchain *swapchain) + /// + destroy_swapchain, + + /// + /// Called after effect runtime initialization (which happens after swap chain creation or a swap chain buffer resize). + /// Callback function signature: void (api::effect_runtime *runtime) + /// + init_effect_runtime, + + /// + /// Called when an effect runtime is reset or destroyed. + /// Callback function signature: void (api::effect_runtime *runtime) + /// + destroy_effect_runtime, + + /// + /// Called after successfull sampler creation from: + /// + /// ID3D10Device::CreateSamplerState + /// ID3D11Device::CreateSamplerState + /// ID3D12Device::CreateSampler + /// vkCreateSampler + /// + /// Callback function signature: void (api::device *device, const api::sampler_desc &desc, api::sampler sampler) + /// + /// + /// Is not called in D3D9 (since samplers are loose state there) or OpenGL. + /// + init_sampler, + + /// + /// Called on sampler creation, before: + /// + /// ID3D10Device::CreateSamplerState + /// ID3D11Device::CreateSamplerState + /// ID3D12Device::CreateSampler + /// ID3D12Device::CreateRootSignature + /// vkCreateSampler + /// + /// Callback function signature: bool (api::device *device, api::sampler_desc &desc) + /// + /// + /// To overwrite the sampler description, modify desc in the callback and return , otherwise return . + /// Is not called in D3D9 (since samplers are loose state there) or OpenGL. + /// + create_sampler, + + /// + /// Called on sampler destruction, before: + /// + /// ID3D10SamplerState::Release + /// ID3D11SamplerState::Release + /// glDeleteSamplers + /// vkDestroySampler + /// + /// Callback function signature: void (api::device *device, api::sampler sampler) + /// + /// + /// Is not called in D3D9 (since samplers are loose state there), D3D12 (since samplers are descriptor handles instead of objects there) or OpenGL. + /// + destroy_sampler, + + /// + /// Called after successfull resource creation from: + /// + /// IDirect3DDevice9::CreateVertexBuffer + /// IDirect3DDevice9::CreateIndexBuffer + /// IDirect3DDevice9::CreateTexture + /// IDirect3DDevice9::CreateCubeTexture + /// IDirect3DDevice9::CreateVolumeTexture + /// IDirect3DDevice9::CreateRenderTargetSurface + /// IDirect3DDevice9::CreateDepthStencilSurface + /// IDirect3DDevice9::CreateOffscreenPlainSurface + /// IDirect3DDevice9Ex::CreateRenderTargetSurfaceEx + /// IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx + /// IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx + /// ID3D10Device::CreateBuffer + /// ID3D10Device::CreateTexture1D + /// ID3D10Device::CreateTexture2D + /// ID3D10Device::CreateTexture2D + /// ID3D11Device::CreateBuffer + /// ID3D11Device::CreateTexture1D + /// ID3D11Device::CreateTexture2D + /// ID3D11Device::CreateTexture3D + /// ID3D11Device3::CreateTexture2D + /// ID3D11Device3::CreateTexture3D + /// ID3D12Device::CreateCommittedResource + /// ID3D12Device::CreatePlacedResource + /// ID3D12Device::CreateReservedResource + /// ID3D12Device4::CreateCommittedResource1 + /// ID3D12Device4::CreateReservedResource1 + /// glBufferData + /// glBufferStorage + /// glNamedBufferData + /// glNamedBufferStorage + /// glTexImage1D + /// glTexImage2D + /// glTexImage2DMultisample + /// glTexImage3D + /// glTexImage3DMultisample + /// glCompressedTexImage1D + /// glCompressedTexImage2D + /// glCompressedTexImage3D + /// glTexStorage1D + /// glTexStorage2D + /// glTexStorage2DMultisample + /// glTexStorage3D + /// glTexStorage3DMultisample + /// glTextureStorage1D + /// glTextureStorage2D + /// glTextureStorage2DMultisample + /// glTextureStorage3D + /// glTextureStorage3DMultisample + /// glRenderbufferStorage + /// glRenderbufferStorageMultisample + /// glNamedRenderbufferStorage + /// glNamedRenderbufferStorageMultisample + /// vkBindBufferMemory + /// vkBindBufferMemory2 + /// vkBindImageMemory + /// vkBindImageMemory2 + /// + /// Callback function signature: void (api::device *device, const api::resource_desc &desc, const api::subresource_data *initial_data, api::resource_usage initial_state, api::resource resource) + /// + init_resource, + + /// + /// Called on resource creation, before: + /// + /// IDirect3DDevice9::CreateVertexBuffer + /// IDirect3DDevice9::CreateIndexBuffer + /// IDirect3DDevice9::CreateTexture + /// IDirect3DDevice9::CreateCubeTexture + /// IDirect3DDevice9::CreateVolumeTexture + /// IDirect3DDevice9::CreateRenderTargetSurface + /// IDirect3DDevice9::CreateDepthStencilSurface + /// IDirect3DDevice9::CreateOffscreenPlainSurface + /// IDirect3DDevice9Ex::CreateRenderTargetSurfaceEx + /// IDirect3DDevice9Ex::CreateDepthStencilSurfaceEx + /// IDirect3DDevice9Ex::CreateOffscreenPlainSurfaceEx + /// ID3D10Device::CreateBuffer + /// ID3D10Device::CreateTexture1D + /// ID3D10Device::CreateTexture2D + /// ID3D10Device::CreateTexture2D + /// ID3D11Device::CreateBuffer + /// ID3D11Device::CreateTexture1D + /// ID3D11Device::CreateTexture2D + /// ID3D11Device::CreateTexture3D + /// ID3D11Device3::CreateTexture2D + /// ID3D11Device3::CreateTexture3D + /// ID3D12Device::CreateCommittedResource + /// ID3D12Device::CreatePlacedResource + /// ID3D12Device::CreateReservedResource + /// ID3D12Device4::CreateCommittedResource1 + /// ID3D12Device4::CreateReservedResource1 + /// glBufferData + /// glBufferStorage + /// glNamedBufferData + /// glNamedBufferStorage + /// glTexImage1D + /// glTexImage2D + /// glTexImage2DMultisample + /// glTexImage3D + /// glTexImage3DMultisample + /// glCompressedTexImage1D + /// glCompressedTexImage2D + /// glCompressedTexImage3D + /// glTexStorage1D + /// glTexStorage2D + /// glTexStorage2DMultisample + /// glTexStorage3D + /// glTexStorage3DMultisample + /// glTextureStorage1D + /// glTextureStorage2D + /// glTextureStorage2DMultisample + /// glTextureStorage3D + /// glTextureStorage3DMultisample + /// glRenderbufferStorage + /// glRenderbufferStorageMultisample + /// glNamedRenderbufferStorage + /// glNamedRenderbufferStorageMultisample + /// vkCreateBuffer + /// vkCreateImage + /// + /// Callback function signature: bool (api::device *device, api::resource_desc &desc, api::subresource_data *initial_data, api::resource_usage initial_state) + /// + /// + /// To overwrite the resource description, modify desc in the callback and return , otherwise return . + /// + create_resource, + + /// + /// Called on resource destruction, before: + /// + /// IDirect3DResource9::Release + /// ID3D10Resource::Release + /// ID3D11Resource::Release + /// ID3D12Resource::Release + /// glDeleteBuffers + /// glDeleteTextures + /// glDeleteRenderbuffers + /// vkDestroyBuffer + /// vkDestroyImage + /// + /// Callback function signature: void (api::device *device, api::resource resource) + /// + destroy_resource, + + /// + /// Called after successfull resource view creation from: + /// + /// IDirect3DDevice9::CreateTexture + /// IDirect3DDevice9::CreateCubeTexture + /// IDirect3DDevice9::CreateVolumeTexture + /// ID3D10Device::CreateShaderResourceView + /// ID3D10Device::CreateRenderTargetView + /// ID3D10Device::CreateDepthStencilView + /// ID3D10Device1::CreateShaderResourceView1 + /// ID3D11Device::CreateShaderResourceView + /// ID3D11Device::CreateUnorderedAccessView + /// ID3D11Device::CreateRenderTargetView + /// ID3D11Device::CreateDepthStencilView + /// ID3D11Device3::CreateShaderResourceView1 + /// ID3D11Device3::CreateUnorderedAccessView1 + /// ID3D11Device3::CreateRenderTargetView1 + /// ID3D12Device::CreateShaderResourceView + /// ID3D12Device::CreateUnorderedAccessView + /// ID3D12Device::CreateRenderTargetView + /// ID3D12Device::CreateDepthStencilView + /// glTexBuffer + /// glTextureBuffer + /// glTextureView + /// vkCreateBufferView + /// vkCreateImageView + /// + /// Callback function signature: void (api::device *device, api::resource resource, api::resource_usage usage_type, const api::resource_view_desc &desc, api::resource_view view) + /// + init_resource_view, + + /// + /// Called on resource view creation, before: + /// + /// ID3D10Device::CreateShaderResourceView + /// ID3D10Device::CreateRenderTargetView + /// ID3D10Device::CreateDepthStencilView + /// ID3D10Device1::CreateShaderResourceView1 + /// ID3D11Device::CreateShaderResourceView + /// ID3D11Device::CreateUnorderedAccessView + /// ID3D11Device::CreateRenderTargetView + /// ID3D11Device::CreateDepthStencilView + /// ID3D11Device3::CreateShaderResourceView1 + /// ID3D11Device3::CreateUnorderedAccessView1 + /// ID3D11Device3::CreateRenderTargetView1 + /// ID3D12Device::CreateShaderResourceView + /// ID3D12Device::CreateUnorderedAccessView + /// ID3D12Device::CreateRenderTargetView + /// ID3D12Device::CreateDepthStencilView + /// glTexBuffer + /// glTextureBuffer + /// glTextureView + /// vkCreateBufferView + /// vkCreateImageView + /// + /// Callback function signature: bool (api::device *device, api::resource resource, api::resource_usage usage_type, api::resource_view_desc &desc) + /// + /// + /// To overwrite the resource view description, modify desc in the callback and return , otherwise return . + /// Is not called in D3D9 (since resource views are tied to resources there). + /// + create_resource_view, + + /// + /// Called on resource view destruction, before: + /// + /// IDirect3DResource9::Release + /// ID3D10View::Release + /// ID3D11View::Release + /// glDeleteTextures + /// vkDestroyBufferView + /// vkDestroyImageView + /// + /// Callback function signature: void (api::device *device, api::resource_view view) + /// + /// + /// Is not called in D3D12 (since resource views are descriptor handles instead of objects there). + /// + destroy_resource_view, + + /// + /// Called after: + /// + /// IDirect3DVertexBuffer9::Lock + /// IDirect3DIndexBuffer9::Lock + /// ID3D10Resource::Map + /// ID3D11DeviceContext::Map + /// ID3D12Resource::Map + /// glMapBuffer + /// glMapBufferRange + /// glMapNamedBuffer + /// glMapNamedBufferRange + /// + /// Callback function signature: void (api::device *device, api::resource resource, uint64_t offset, uint64_t size, api::map_access access, void **data) + /// + map_buffer_region, + + /// + /// Called before: + /// + /// IDirect3DVertexBuffer9::Unlock + /// IDirect3DIndexBuffer9::Unlock + /// ID3D10Resource::Unmap + /// ID3D11DeviceContext::Unmap + /// ID3D12Resource::Unmap + /// glUnmapBuffer + /// glUnmapNamedBuffer + /// + /// Callback function signature: void (api::device *device, api::resource resource) + /// + unmap_buffer_region, + + /// + /// Called after: + /// + /// IDirect3DSurface9::LockRect + /// IDirect3DVolume9::LockBox + /// IDirect3DTexture9::LockRect + /// IDirect3DVolumeTexture9::LockBox + /// IDirect3DCubeTexture9::LockRect + /// ID3D10Resource::Map + /// ID3D11DeviceContext::Map + /// ID3D12Resource::Map + /// + /// Callback function signature: void (api::device *device, api::resource resource, uint32_t subresource, const api::subresource_box *box, api::map_access access, api::subresource_data *data) + /// + map_texture_region, + + /// + /// Called before: + /// + /// IDirect3DSurface9::UnlockRect + /// IDirect3DVolume9::UnlockBox + /// IDirect3DTexture9::UnlockRect + /// IDirect3DVolumeTexture9::UnlockBox + /// IDirect3DCubeTexture9::UnlockRect + /// ID3D10Resource::Unmap + /// ID3D11DeviceContext::Unmap + /// ID3D12Resource::Unmap + /// + /// Callback function signature: void (api::device *device, api::resource resource, uint32_t subresource) + /// + unmap_texture_region, + + /// + /// Called before: + /// + /// ID3D10Device::UpdateSubresource + /// ID3D11DeviceContext::UpdateSubresource + /// glBufferSubData + /// glNamedBufferSubData + /// + /// Callback function signature: bool (api::device *device, const void *data, api::resource resource, uint64_t offset, uint64_t size) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Destination resource will be in the state. + /// + update_buffer_region, + + /// + /// Called before: + /// + /// ID3D10Device::UpdateSubresource + /// ID3D11DeviceContext::UpdateSubresource + /// glTexSubData1D + /// glTexSubData2D + /// glTexSubData3D + /// glTextureSubData1D + /// glTextureSubData2D + /// glTextureSubData3D + /// glCompressedTexSubData1D + /// glCompressedTexSubData2D + /// glCompressedTexSubData3D + /// glCompressedTextureSubData1D + /// glCompressedTextureSubData2D + /// glCompressedTextureSubData3D + /// + /// Callback function signature: bool (api::device *device, const api::subresource_data &data, api::resource resource, uint32_t subresource, const api::subresource_box *box) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Destination resource will be in the state. + /// + update_texture_region, + + /// + /// Called after successfull pipeline creation from: + /// + /// IDirect3DDevice9::CreateVertexShader + /// IDirect3DDevice9::CreatePixelShader + /// IDirect3DDevice9::CreateVertexDeclaration + /// ID3D10Device::CreateVertexShader + /// ID3D10Device::CreateGeometryShader + /// ID3D10Device::CreateGeometryShaderWithStreamOutput + /// ID3D10Device::CreatePixelShader + /// ID3D10Device::CreateInputLayout + /// ID3D10Device::CreateBlendState + /// ID3D10Device::CreateDepthStencilState + /// ID3D10Device::CreateRasterizerState + /// ID3D10Device1::CreateBlendState1 + /// ID3D11Device::CreateVertexShader + /// ID3D11Device::CreateHullShader + /// ID3D11Device::CreateDomainShader + /// ID3D11Device::CreateGeometryShader + /// ID3D11Device::CreateGeometryShaderWithStreamOutput + /// ID3D11Device::CreatePixelShader + /// ID3D11Device::CreateComputeShader + /// ID3D11Device::CreateInputLayout + /// ID3D11Device::CreateBlendState + /// ID3D11Device::CreateDepthStencilState + /// ID3D11Device::CreateRasterizerState + /// ID3D11Device1::CreateBlendState1 + /// ID3D11Device1::CreateRasterizerState1 + /// ID3D11Device3::CreateRasterizerState2 + /// ID3D12Device::CreateComputePipelineState + /// ID3D12Device::CreateGraphicsPipelineState + /// ID3D12Device2::CreatePipelineState + /// ID3D12PipelineLibrary::LoadComputePipeline + /// ID3D12PipelineLibrary::LoadGraphicsPipeline + /// ID3D12PipelineLibrary1::LoadPipeline + /// glLinkProgram + /// vkCreateComputePipelines + /// vkCreateGraphicsPipelines + /// + /// Callback function signature: void (api::device *device, api::pipeline_layout layout, uint32_t subobject_count, const api::pipeline_subobject *subobjects, api::pipeline pipeline) + /// + /// + /// May be called multiple times with the same pipeline handle (whenever the pipeline is updated or its reference count is incremented). + /// + init_pipeline, + + /// + /// Called on pipeline creation, before: + /// + /// IDirect3DDevice9::CreateVertexShader + /// IDirect3DDevice9::CreatePixelShader + /// IDirect3DDevice9::CreateVertexDeclaration + /// ID3D10Device::CreateVertexShader + /// ID3D10Device::CreateGeometryShader + /// ID3D10Device::CreateGeometryShaderWithStreamOutput + /// ID3D10Device::CreatePixelShader + /// ID3D10Device::CreateInputLayout + /// ID3D10Device::CreateBlendState + /// ID3D10Device::CreateDepthStencilState + /// ID3D10Device::CreateRasterizerState + /// ID3D10Device1::CreateBlendState1 + /// ID3D11Device::CreateVertexShader + /// ID3D11Device::CreateHullShader + /// ID3D11Device::CreateDomainShader + /// ID3D11Device::CreateGeometryShader + /// ID3D11Device::CreateGeometryShaderWithStreamOutput + /// ID3D11Device::CreatePixelShader + /// ID3D11Device::CreateComputeShader + /// ID3D11Device::CreateInputLayout + /// ID3D11Device::CreateBlendState + /// ID3D11Device::CreateDepthStencilState + /// ID3D11Device::CreateRasterizerState + /// ID3D11Device1::CreateBlendState1 + /// ID3D11Device1::CreateRasterizerState1 + /// ID3D11Device3::CreateRasterizerState2 + /// ID3D12Device::CreateComputePipelineState + /// ID3D12Device::CreateGraphicsPipelineState + /// ID3D12Device2::CreatePipelineState + /// glShaderSource + /// vkCreateComputePipelines + /// vkCreateGraphicsPipelines + /// + /// Callback function signature: bool (api::device *device, api::pipeline_layout layout, uint32_t subobject_count, const api::pipeline_subobject *subobjects) + /// + /// + /// To overwrite the pipeline description, modify desc in the callback and return , otherwise return . + /// + create_pipeline, + + /// + /// Called on pipeline destruction, before: + /// + /// ID3D10VertexShader::Release + /// ID3D10GeometryShader::Release + /// ID3D10PixelShader::Release + /// ID3D10InputLayout::Release + /// ID3D10BlendState::Release + /// ID3D10DepthStencilState::Release + /// ID3D10RasterizerState::Release + /// ID3D11VertexShader::Release + /// ID3D11HullShader::Release + /// ID3D11DomainShader::Release + /// ID3D11GeometryShader::Release + /// ID3D11PixelShader::Release + /// ID3D11ComputeShader::Release + /// ID3D11InputLayout::Release + /// ID3D11BlendState::Release + /// ID3D11DepthStencilState::Release + /// ID3D11RasterizerState::Release + /// ID3D12PipelineState::Release + /// glDeleteProgram + /// vkDestroyPipeline + /// + /// Callback function signature: void (api::device *device, api::pipeline pipeline) + /// + /// + /// Is not called in D3D9. + /// + destroy_pipeline, + + /// + /// Called after successfull pipeline layout creation from: + /// + /// ID3D12Device::CreateRootSignature + /// vkCreatePipelineLayout + /// + /// Callback function signature: void (api::device *device, uint32_t param_count, const api::pipeline_layout_param *params, api::pipeline_layout layout) + /// + init_pipeline_layout, + + /// + /// Called on pipeline layout creation. + /// Callback function signature: bool (api::device *device, uint32_t param_count, const api::pipeline_layout_param *params) + /// + create_pipeline_layout, + + /// + /// Called on pipeline layout destruction, before: + /// + /// ID3D12RootSignature::Release + /// VkDestroyPipelineLayout + /// + /// Callback function signature: void (api::device *device, api::pipeline_layout layout) + /// + destroy_pipeline_layout, + + /// + /// Called before: + /// + /// ID3D12Device::CopyDescriptors + /// ID3D12Device::CopyDescriptorsSimple + /// vkUpdateDescriptorSets + /// + /// Callback function signature: bool (api::device *device, uint32_t count, const api::descriptor_table_copy *copies) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + copy_descriptor_tables, + + /// + /// Called before: + /// + /// ID3D12Device::CreateConstantBufferView + /// ID3D12Device::CreateShaderResourceView + /// ID3D12Device::CreateUnorderedAccessView + /// ID3D12Device::CreateSampler + /// vkUpdateDescriptorSets + /// + /// Callback function signature: bool (api::device *device, uint32_t count, const api::descriptor_table_update *updates) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + update_descriptor_tables, + + /// + /// Called after successfull query heap creation from: + /// + /// ID3D12Device::CreateQueryHeap + /// vkCreateQueryPool + /// + /// Callback function signature: void (api::device *device, api::query_type type, uint32_t size, api::query_heap heap) + /// + init_query_heap, + + /// + /// Called on query heap creation, before: + /// + /// ID3D12Device::CreateQueryHeap + /// vkCreateQueryPool + /// + /// Callback function signature: bool (api::device *device, api::query_type type, uint32_t &size) + /// + create_query_heap, + + /// + /// Called on query heap destruction, before: + /// + /// ID3D12QueryHeap::Release + /// vkDestroyQueryPool + /// + /// Callback function signature: void (api::device *device, api::query_heap heap) + /// + destroy_query_heap, + + /// + /// Called before: + /// + /// vkGetQueryPoolResults + /// + /// Callback function signature: bool (api::device *device, api::query_heap heap, uint32_t first, uint32_t count, void *results, uint32_t stride) + /// + get_query_heap_results, + + /// + /// Called after: + /// + /// ID3D12GraphicsCommandList::ResourceBarrier + /// ID3D12GraphicsCommandList7::Barrier + /// vkCmdPipelineBarrier + /// vkCmdPipelineBarrier2 + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t count, const api::resource *resources, const api::resource_usage *old_states, const api::resource_usage *new_states) + /// + barrier, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList4::BeginRenderPass + /// vkCmdBeginRenderPass + /// vkCmdBeginRenderPass2 + /// vkCmdNextSubpass + /// vkCmdNextSubpass2 + /// vkCmdBeginRendering + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t count, const api::render_pass_render_target_desc *rts, const api::render_pass_depth_stencil_desc *ds) + /// + /// + /// The depth-stencil description argument is optional and may be . + /// + begin_render_pass, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList4::EndRenderPass + /// vkCmdEndRenderPass + /// vkCmdEndRenderPass2 + /// vkCmdNextSubpass + /// vkCmdNextSubpass2 + /// vkCmdEndRendering + /// + /// Callback function signature: void (api::command_list *cmd_list) + /// + end_render_pass, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetRenderTarget + /// IDirect3DDevice9::SetDepthStencilSurface + /// ID3D10Device::OMSetRenderTargets + /// ID3D11DeviceContext::OMSetRenderTargets + /// ID3D11DeviceContext::OMSetRenderTargetsAndUnorderedAccessViews + /// ID3D12GraphicsCommandList::OMSetRenderTargets + /// glBindFramebuffer + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t count, const api::resource_view *rtvs, api::resource_view dsv) + /// + bind_render_targets_and_depth_stencil, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetVertexShader + /// IDirect3DDevice9::SetPixelShader + /// IDirect3DDevice9::SetVertexDeclaration + /// IDirect3DDevice9::ProcessVertices + /// ID3D10Device::VSSetShader + /// ID3D10Device::GSSetShader + /// ID3D10Device::PSSetShader + /// ID3D10Device::IASetInputLayout + /// ID3D10Device::OMSetBlendState + /// ID3D10Device::OMSetDepthStencilState + /// ID3D10Device::RSSetState + /// ID3D11DeviceContext::VSSetShader + /// ID3D11DeviceContext::HSSetShader + /// ID3D11DeviceContext::DSSetShader + /// ID3D11DeviceContext::GSSetShader + /// ID3D11DeviceContext::PSSetShader + /// ID3D11DeviceContext::CSSetShader + /// ID3D11DeviceContext::IASetInputLayout + /// ID3D11DeviceContext::OMSetBlendState + /// ID3D11DeviceContext::OMSetDepthStencilState + /// ID3D11DeviceContext::RSSetState + /// ID3D12GraphicsCommandList::Reset + /// ID3D12GraphicsCommandList::SetPipelineState + /// glUseProgram + /// vkCmdBindPipeline + /// + /// Callback function signature: void (api::command_list *cmd_list, api::pipeline_stage stages, api::pipeline pipeline) + /// + bind_pipeline, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetRenderState + /// ID3D10Device::IASetPrimitiveTopology + /// ID3D10Device::OMSetBlendState + /// ID3D10Device::OMSetDepthStencilState + /// ID3D11DeviceContext::IASetPrimitiveTopology + /// ID3D11DeviceContext::OMSetBlendState + /// ID3D11DeviceContext::OMSetDepthStencilState + /// ID3D12GraphicsCommandList::IASetPrimitiveTopology + /// ID3D12GraphicsCommandList::OMSetBlendFactor + /// ID3D12GraphicsCommandList::OMSetStencilRef + /// gl(...) + /// vkCmdSetDepthBias + /// vkCmdSetBlendConstants + /// vkCmdSetStencilCompareMask + /// vkCmdSetStencilWriteMask + /// vkCmdSetStencilReference + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t count, const api::dynamic_state *states, const uint32_t *values) + /// + bind_pipeline_states, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetViewport + /// IDirect3DDevice9::SetRenderTarget (implicitly updates the viewport) + /// ID3D10Device::RSSetViewports + /// ID3D11DeviceContext::RSSetViewports + /// ID3D12GraphicsCommandList::RSSetViewports + /// glViewport + /// glViewportArrayv + /// glViewportIndexedf + /// glViewportIndexedfv + /// vkCmdSetViewport + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t first, uint32_t count, const api::viewport *viewports) + /// + bind_viewports, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetScissorRect + /// ID3D10Device::RSSetScissorRects + /// ID3D11DeviceContext::RSSetScissorRects + /// ID3D12GraphicsCommandList::RSSetScissorRects + /// glScissor + /// glScissorArrayv + /// glScissorIndexed + /// glScissorIndexedv + /// vkCmdSetScissor + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t first, uint32_t count, const api::rect *rects) + /// + bind_scissor_rects, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetVertexShaderConstantF + /// IDirect3DDevice9::SetPixelShaderConstantF + /// ID3D12GraphicsCommandList::SetComputeRoot32BitConstant + /// ID3D12GraphicsCommandList::SetComputeRoot32BitConstants + /// ID3D12GraphicsCommandList::SetGraphicsRoot32BitConstant + /// ID3D12GraphicsCommandList::SetGraphicsRoot32BitConstants + /// glUniform(...) + /// vkCmdPushConstants + /// + /// Callback function signature: void (api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t layout_param, uint32_t first, uint32_t count, const void *values) + /// + push_constants, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetTexture + /// ID3D10Device::VSSetSamplers + /// ID3D10Device::VSSetShaderResources + /// ID3D10Device::VSSetConstantBuffers + /// ID3D10Device::GSSetSamplers + /// ID3D10Device::GSSetShaderResources + /// ID3D10Device::GSSetConstantBuffers + /// ID3D10Device::PSSetSamplers + /// ID3D10Device::PSSetShaderResources + /// ID3D10Device::PSSetConstantBuffers + /// ID3D11DeviceContext::VSSetSamplers + /// ID3D11DeviceContext::VSSetShaderResources + /// ID3D11DeviceContext::VSSetConstantBuffers + /// ID3D11DeviceContext::HSSetSamplers + /// ID3D11DeviceContext::HSSetShaderResources + /// ID3D11DeviceContext::HSSetConstantBuffers + /// ID3D11DeviceContext::DSSetSamplers + /// ID3D11DeviceContext::DSSetShaderResources + /// ID3D11DeviceContext::DSSetConstantBuffers + /// ID3D11DeviceContext::GSSetSamplers + /// ID3D11DeviceContext::GSSetShaderResources + /// ID3D11DeviceContext::GSSetConstantBuffers + /// ID3D11DeviceContext::PSSetSamplers + /// ID3D11DeviceContext::PSSetShaderResources + /// ID3D11DeviceContext::PSSetConstantBuffers + /// ID3D11DeviceContext::CSSetSamplers + /// ID3D11DeviceContext::CSSetShaderResources + /// ID3D11DeviceContext::CSSetUnorderedAccessViews + /// ID3D11DeviceContext::CSSetConstantBuffers + /// ID3D12GraphicsCommandList::SetComputeRootConstantBufferView + /// ID3D12GraphicsCommandList::SetGraphicsRootConstantBufferView + /// ID3D12GraphicsCommandList::SetComputeRootShaderResourceView + /// ID3D12GraphicsCommandList::SetGraphicsRootShaderResourceView + /// ID3D12GraphicsCommandList::SetComputeRootUnorderedAccessView + /// ID3D12GraphicsCommandList::SetGraphicsRootUnorderedAccessView + /// glBindBufferBase + /// glBindBufferRange + /// glBindBuffersBase + /// glBindBuffersRange + /// glBindTexture + /// glBindImageTexture + /// glBindTextures + /// glBindImageTextures + /// glBindTextureUnit + /// glBindMultiTextureEXT + /// vkCmdPushDescriptorSetKHR + /// + /// Callback function signature: void (api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t layout_param, const api::descriptor_table_update &update) + /// + push_descriptors, + + /// + /// Called after: + /// + /// ID3D12GraphicsCommandList::SetComputeRootSignature + /// ID3D12GraphicsCommandList::SetGraphicsRootSignature + /// ID3D12GraphicsCommandList::SetComputeRootDescriptorTable + /// ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable + /// vkCmdBindDescriptorSets + /// + /// Callback function signature: void (api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t first, uint32_t count, const api::descriptor_table *tables) + /// + bind_descriptor_tables, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetIndices + /// ID3D10Device::IASetIndexBuffer + /// ID3D11DeviceContext::IASetIndexBuffer + /// ID3D12GraphicsCommandList::IASetIndexBuffer + /// glBindBuffer + /// vkCmdBindIndexBuffer + /// + /// Callback function signature: void (api::command_list *cmd_list, api::resource buffer, uint64_t offset, uint32_t index_size) + /// + bind_index_buffer, + + /// + /// Called after: + /// + /// IDirect3DDevice9::SetStreamSource + /// ID3D10Device::IASetVertexBuffers + /// ID3D11DeviceContext::IASetVertexBuffers + /// ID3D12GraphicsCommandList::IASetVertexBuffers + /// glBindBuffer + /// glBindVertexBuffer + /// glBindVertexBuffers + /// vkCmdBindVertexBuffers + /// vkCmdBindVertexBuffers2 + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t first, uint32_t count, const api::resource *buffers, const uint64_t *offsets, const uint32_t *strides) + /// + /// + /// The strides argument is optional and may be . + /// + bind_vertex_buffers, + + /// + /// Called after: + /// + /// IDirect3DDevice9::ProcessVertices + /// ID3D10Device::SOSetTargets + /// ID3D11DeviceContext::SOSetTargets + /// ID3D12GraphicsCommandList::SOSetTargets + /// glBindBufferBase + /// glBindBufferRange + /// glBindBuffersBase + /// glBindBuffersRange + /// vkCmdBindTransformFeedbackBuffersEXT + /// + /// Callback function signature: void (api::command_list *cmd_list, uint32_t first, uint32_t count, const api::resource *buffers, const uint64_t *offsets, const uint64_t *max_sizes, const api::resource *counter_buffers, const uint64_t *counter_offsets) + /// + /// + /// The counter arguments are optional and may be . + /// + bind_stream_output_buffers, + + /// + /// Called before: + /// + /// IDirect3DDevice9::DrawPrimitive + /// IDirect3DDevice9::DrawPrimitiveUP + /// IDirect3DDevice9::ProcessVertices + /// ID3D10Device::Draw + /// ID3D10Device::DrawInstanced + /// ID3D11DeviceContext::Draw + /// ID3D11DeviceContext::DrawInstanced + /// ID3D12GraphicsCommandList::DrawInstanced + /// glDrawArrays + /// glDrawArraysInstanced + /// glDrawArraysInstancedBaseInstance + /// glMultiDrawArrays + /// vkCmdDraw + /// + /// Callback function signature: bool (api::command_list *cmd_list, uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + draw, + + /// + /// Called before: + /// + /// IDirect3DDevice9::DrawIndexedPrimitive + /// IDirect3DDevice9::DrawIndexedPrimitiveUP + /// ID3D10Device::DrawIndexed + /// ID3D10Device::DrawIndexedInstanced + /// ID3D11DeviceContext::DrawIndexed + /// ID3D11DeviceContext::DrawIndexedInstanced + /// ID3D12GraphicsCommandList::DrawIndexedInstanced + /// glDrawElements + /// glDrawElementsBaseVertex + /// glDrawElementsInstanced + /// glDrawElementsInstancedBaseVertex + /// glDrawElementsInstancedBaseInstance + /// glDrawElementsInstancedBaseVertexBaseInstance + /// glMultiDrawElements + /// glMultiDrawElementsBaseVertex + /// vkCmdDrawIndexed + /// + /// Callback function signature: bool (api::command_list *cmd_list, uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + draw_indexed, + + /// + /// Called before: + /// + /// ID3D11DeviceContext::Dispatch + /// ID3D12GraphicsCommandList::Dispatch + /// glDispatchCompute + /// vkCmdDispatch + /// + /// Callback function signature: bool (api::command_list *cmd_list, uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + dispatch, + + /// + /// Called before: + /// + /// ID3D11DeviceContext::DrawInstancedIndirect + /// ID3D11DeviceContext::DrawIndexedInstancedIndirect + /// ID3D11DeviceContext::DispatchIndirect + /// ID3D12GraphicsCommandList::ExecuteIndirect + /// glDrawArraysIndirect + /// glDrawElementsIndirect + /// glMultiDrawArraysIndirect + /// glMultiDrawElementsIndirect + /// glDispatchComputeIndirect + /// vkCmdDrawIndirect + /// vkCmdDrawIndexedIndirect + /// vkCmdDispatchIndirect + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::indirect_command type, api::resource buffer, uint64_t offset, uint32_t draw_count, uint32_t stride) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + draw_or_dispatch_indirect, + + /// + /// Called before: + /// + /// IDirect3DDevice9::UpdateTexture + /// IDirect3DDevice9::GetRenderTargetData + /// ID3D10Device::CopyResource + /// ID3D11DeviceContext::CopyResource + /// ID3D12GraphicsCommandList::CopyResource + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, api::resource dest) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// + copy_resource, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::CopyBufferRegion + /// glCopyBufferSubData + /// glCopyNamedBufferSubData + /// vkCmdCopyBuffer + /// vkCmdCopyBuffer2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, uint64_t source_offset, api::resource dest, uint64_t dest_offset, uint64_t size) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// + copy_buffer_region, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::CopyTextureRegion + /// vkCmdCopyBufferToImage + /// vkCmdCopyBufferToImage2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, uint64_t source_offset, uint32_t row_length, uint32_t slice_height, api::resource dest, uint32_t dest_subresource, const api::subresource_box *dest_box) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// The subresource box argument is optional and may be . + /// + copy_buffer_to_texture, + + /// + /// Called before: + /// + /// IDirect3DDevice9::UpdateSurface + /// IDirect3DDevice9::StretchRect + /// ID3D10Device::CopySubresourceRegion + /// ID3D11DeviceContext::CopySubresourceRegion + /// ID3D12GraphicsCommandList::CopyTextureRegion + /// glBlitFramebuffer + /// glBlitNamedFramebuffer + /// glCopyImageSubData + /// glCopyTexSubImage1D + /// glCopyTexSubImage2D + /// glCopyTexSubImage3D + /// glCopyTextureSubImage1D + /// glCopyTextureSubImage2D + /// glCopyTextureSubImage3D + /// vkCmdBlitImage + /// vkCmdBlitImage2 + /// vkCmdCopyImage + /// vkCmdCopyImage2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint32_t dest_subresource, const api::subresource_box *dest_box, api::filter_mode filter) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// The subresource box arguments are optional and may be . + /// + copy_texture_region, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::CopyTextureRegion + /// vkCmdCopyImageToBuffer + /// vkCmdCopyImageToBuffer2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint64_t dest_offset, uint32_t row_length, uint32_t slice_height) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// The subresource box argument is optional and may be . + /// + copy_texture_to_buffer, + + /// + /// Called before: + /// + /// IDirect3DDevice9::StretchRect + /// ID3D10Device::ResolveSubresource + /// ID3D11DeviceContext::ResolveSubresource + /// ID3D12GraphicsCommandList::ResolveSubresource + /// ID3D12GraphicsCommandList1::ResolveSubresourceRegion + /// glBlitFramebuffer + /// glBlitNamedFramebuffer + /// vkCmdResolveImage + /// vkCmdResolveImage2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint32_t dest_subresource, int32_t dest_x, int32_t dest_y, int32_t dest_z, api::format format) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Source resource will be in the state. + /// Destination resource will be in the state. + /// The subresource box argument is optional and may be . + /// + resolve_texture_region, + + /// + /// Called before: + /// + /// IDirect3DDevice9::Clear + /// ID3D10Device::ClearDepthStencilView + /// ID3D11DeviceContext::ClearDepthStencilView + /// ID3D11DeviceContext1::ClearView (for depth-stencil views) + /// ID3D12GraphicsCommandList::ClearDepthStencilView + /// glClear + /// glClearBufferfi + /// glClearBufferfv + /// glClearNamedFramebufferfi + /// glClearNamedFramebufferfv + /// vkCmdClearDepthStencilImage + /// vkCmdClearAttachments + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource_view dsv, const float *depth, const uint8_t *stencil, uint32_t rect_count, const api::rect *rects) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Resource will be in the state. + /// One of the depth or stencil clear value arguments may be when the respective component is not cleared. + /// + clear_depth_stencil_view, + + /// + /// Called before: + /// + /// IDirect3DDevice9::Clear + /// IDirect3DDevice9::ColorFill + /// ID3D10Device::ClearRenderTargetView + /// ID3D11DeviceContext::ClearRenderTargetView + /// ID3D11DeviceContext1::ClearView (for render target views) + /// ID3D12GraphicsCommandList::ClearRenderTargetView + /// glClear + /// glClearBufferfv + /// glClearNamedFramebufferfv + /// vkCmdClearColorImage + /// vkCmdClearAttachments + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource_view rtv, const float color[4], uint32_t rect_count, const api::rect *rects) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Resources will be in the state. + /// + clear_render_target_view, + + /// + /// Called before: + /// + /// ID3D11DeviceContext::ClearUnorderedAccessViewUint + /// ID3D12GraphicsCommandList::ClearUnorderedAccessViewUint + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource_view uav, const uint32_t values[4], uint32_t rect_count, const api::rect *rects) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Resource will be in the state. + /// + clear_unordered_access_view_uint, + + /// + /// Called before: + /// + /// ID3D11DeviceContext::ClearUnorderedAccessViewFloat + /// ID3D11DeviceContext1::ClearView (for unordered access views) + /// ID3D12GraphicsCommandList::ClearUnorderedAccessViewFloat + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource_view uav, const float values[4], uint32_t rect_count, const api::rect *rects) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// Resource will be in the state. + /// + clear_unordered_access_view_float, + + /// + /// Called before: + /// + /// ID3D10Device::GenerateMips + /// ID3D11DeviceContext::GenerateMips + /// glGenerateMipmap + /// glGenerateTextureMipmap + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::resource_view srv) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + generate_mipmaps, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::BeginQuery + /// vkCmdBeginQuery + /// vkCmdBeginQueryIndexedEXT + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t index) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + begin_query, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::EndQuery + /// vkCmdEndQuery + /// vkCmdEndQueryIndexedEXT + /// vkCmdWriteTimestamp + /// vkCmdWriteTimestamp2 + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t index) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + end_query, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::ResolveQueryData + /// vkCmdCopyQueryPoolResults + /// + /// Callback function signature: bool (api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t first, uint32_t count, api::resource dest, uint64_t dest_offset, uint32_t stride) + /// + /// + /// To prevent this command from being executed, return , otherwise return . + /// + copy_query_heap_results, + + /// + /// Called before: + /// + /// ID3D12GraphicsCommandList::Reset + /// vkBeginCommandBuffer + /// + /// Callback function signature: void (api::command_list *cmd_list) + /// + /// + /// Is not called for immediate command lists (since they cannot be reset). + /// + reset_command_list, + + /// + /// Called before: + /// + /// ID3D11DeviceContext::FinishCommandList + /// ID3D12GraphicsCommandList::Close + /// vkEndCommandBuffer + /// + /// Callback function signature: void (api::command_list *cmd_list) + /// + /// + /// Is not called for immediate command lists (since they cannot be closed). + /// + close_command_list, + + /// + /// Called when a command list is submitted to a command queue (or an immediate command list is flushed), before: + /// + /// IDirect3DDevice9::EndScene + /// ID3D10Device::Flush + /// ID3D11DeviceContext::Flush + /// ID3D11DeviceContext3::Flush1 + /// ID3D12CommandQueue::ExecuteCommandLists + /// glFlush + /// vkQueueSubmit + /// + /// Callback function signature: void (api::command_queue *queue, api::command_list *cmd_list) + /// + execute_command_list, + + /// + /// Called when a secondary command list is executed on a primary command list, before: + /// + /// ID3D11DeviceContext::ExecuteCommandList + /// ID3D12GraphicsCommandList::ExecuteBundle + /// vkCmdExecuteCommands + /// + /// In addition, called after: + /// + /// ID3D11DeviceContext::FinishCommandList + /// + /// Callback function signature: void (api::command_list *cmd_list, api::command_list *secondary_cmd_list) + /// + execute_secondary_command_list, + + /// + /// Called before: + /// + /// IDirect3DDevice9::Present + /// IDirect3DDevice9Ex::PresentEx + /// IDirect3DSwapChain9::Present + /// IDXGISwapChain::Present + /// IDXGISwapChain3::Present1 + /// ID3D12CommandQueueDownlevel::Present + /// wglSwapBuffers + /// vkQueuePresentKHR + /// IVRCompositor::Submit + /// + /// Callback function signature: void (api::command_queue *queue, api::swapchain *swapchain, const api::rect *source_rect, const api::rect *dest_rect, uint32_t dirty_rect_count, const api::rect *dirty_rects) + /// + /// + /// The source and destination rectangle arguments are optional and may be . + /// + present, + + /// + /// Called after ReShade has rendered its overlay. + /// Callback function signature: void (api::effect_runtime *runtime) + /// + reshade_present, + + /// + /// Called right before ReShade effects are rendered. + /// Callback function signature: void (api::effect_runtime *runtime, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb) + /// + reshade_begin_effects, + + /// + /// Called right after ReShade effects were rendered. + /// Callback function signature: void (api::effect_runtime *runtime, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb) + /// + reshade_finish_effects, + + /// + /// Called right after all ReShade effects were reloaded. + /// This occurs during effect runtime initialization or because the user pressed the "Reload" button in the overlay. + /// Callback function signature: void (api::effect_runtime *runtime) + /// + reshade_reloaded_effects, + + /// + /// Called before a uniform variable is changed. + /// Callback function signature: bool (api::effect_runtime *runtime, api::effect_uniform_variable variable, const void *data, size_t size) + /// + /// + /// To prevent the variable from being changed, return , otherwise return . + /// + reshade_set_uniform_value, + /// + /// Called before a technique is enabled or disabled. + /// Callback function signature: bool (api::effect_runtime *runtime, api::effect_technique technique, bool enabled) + /// + /// + /// To prevent the technique from being changed, return , otherwise return . + /// + reshade_set_technique_state, + + /// + /// Called between the ImGui::NewFrame and ImGui::EndFrame calls for the ReShade overlay. + /// Can be used to perform custom Dear ImGui calls, but it is recommended to instead use to register a dedicated overlay. + /// Callback function signature: void (api::effect_runtime *runtime) + /// + /// + /// This is not called for effect runtimes in VR. + /// + reshade_overlay, + + /// + /// Called after a screenshot was taken and saved to disk. + /// Callback function signature: void (api::effect_runtime *runtime, const char *path) + /// + reshade_screenshot, + + /// + /// Called for each technique after it was rendered, usually between and . + /// Callback function signature: void (api::effect_runtime *runtime, api::effect_technique technique, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb) + /// + reshade_render_technique, + + /// + /// Called after a preset was loaded and applied. + /// This occurs during reloading or when the user chooses a new preset in the overlay. + /// Callback function signature: void (api::effect_runtime *runtime, const char *path) + /// + reshade_set_current_preset_path, + + /// + /// Called when the rendering order of loaded techniques is changed. + /// Callback function signature: bool (api::effect_runtime *runtime, size_t count, api::effect_technique *techniques) + /// + /// + /// To prevent the order from being changed, return , otherwise return . + /// + reshade_reorder_techniques, + +#if RESHADE_ADDON + max // Last value used internally by ReShade to determine number of events in this enum +#endif + }; + + template + struct addon_event_traits; + +#define RESHADE_DEFINE_ADDON_EVENT_TRAITS(ev, ret, ...) \ + template <> \ + struct addon_event_traits { \ + using decl = ret(*)(__VA_ARGS__); \ + using type = ret; \ + } + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_device, void, api::device *device); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_device, void, api::device *device); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_command_list, void, api::command_list *cmd_list); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_command_list, void, api::command_list *cmd_list); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_command_queue, void, api::command_queue *queue); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_command_queue, void, api::command_queue *queue); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_swapchain, void, api::swapchain *swapchain); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_swapchain, bool, api::swapchain_desc &desc, void *hwnd); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_swapchain, void, api::swapchain *swapchain); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_effect_runtime, void, api::effect_runtime *runtime); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_effect_runtime, void, api::effect_runtime *runtime); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_sampler, void, api::device *device, const api::sampler_desc &desc, api::sampler sampler); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_sampler, bool, api::device *device, api::sampler_desc &desc); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_sampler, void, api::device *device, api::sampler sampler); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_resource, void, api::device *device, const api::resource_desc &desc, const api::subresource_data *initial_data, api::resource_usage initial_state, api::resource resource); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_resource, bool, api::device *device, api::resource_desc &desc, api::subresource_data *initial_data, api::resource_usage initial_state); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_resource, void, api::device *device, api::resource resource); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_resource_view, void, api::device *device, api::resource resource, api::resource_usage usage_type, const api::resource_view_desc &desc, api::resource_view view); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_resource_view, bool, api::device *device, api::resource resource, api::resource_usage usage_type, api::resource_view_desc &desc); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_resource_view, void, api::device *device, api::resource_view view); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::map_buffer_region, void, api::device *device, api::resource resource, uint64_t offset, uint64_t size, api::map_access access, void **data); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::unmap_buffer_region, void, api::device *device, api::resource resource); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::map_texture_region, void, api::device *device, api::resource resource, uint32_t subresource, const api::subresource_box *box, api::map_access access, api::subresource_data *data); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::unmap_texture_region, void, api::device *device, api::resource resource, uint32_t subresource); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::update_buffer_region, bool, api::device *device, const void *data, api::resource resource, uint64_t offset, uint64_t size); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::update_texture_region, bool, api::device *device, const api::subresource_data &data, api::resource resource, uint32_t subresource, const api::subresource_box *box); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_pipeline, void, api::device *device, api::pipeline_layout layout, uint32_t subobject_count, const api::pipeline_subobject *subobjects, api::pipeline pipeline); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_pipeline, bool, api::device *device, api::pipeline_layout layout, uint32_t subobject_count, const api::pipeline_subobject *subobjects); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_pipeline, void, api::device *device, api::pipeline pipeline); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_pipeline_layout, void, api::device *device, uint32_t param_count, const api::pipeline_layout_param *params, api::pipeline_layout layout); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_pipeline_layout, bool, api::device *device, uint32_t param_count, const api::pipeline_layout_param *params); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_pipeline_layout, void, api::device *device, api::pipeline_layout layout); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_descriptor_tables, bool, api::device *device, uint32_t count, const api::descriptor_table_copy *copies); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::update_descriptor_tables, bool, api::device *device, uint32_t count, const api::descriptor_table_update *updates); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::init_query_heap, void, api::device *device, api::query_type type, uint32_t size, api::query_heap heap); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::create_query_heap, bool, api::device *device, api::query_type type, uint32_t &size); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::destroy_query_heap, void, api::device *device, api::query_heap heap); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::get_query_heap_results, bool, api::device *device, api::query_heap heap, uint32_t first, uint32_t count, void *results, uint32_t stride); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::barrier, void, api::command_list *cmd_list, uint32_t count, const api::resource *resources, const api::resource_usage *old_states, const api::resource_usage *new_states); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::begin_render_pass, void, api::command_list *cmd_list, uint32_t count, const api::render_pass_render_target_desc *rts, const api::render_pass_depth_stencil_desc *ds); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::end_render_pass, void, api::command_list *cmd_list); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_render_targets_and_depth_stencil, void, api::command_list *cmd_list, uint32_t count, const api::resource_view *rtvs, api::resource_view dsv); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_pipeline, void, api::command_list *cmd_list, api::pipeline_stage stages, api::pipeline pipeline); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_pipeline_states, void, api::command_list *cmd_list, uint32_t count, const api::dynamic_state *states, const uint32_t *values); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_viewports, void, api::command_list *cmd_list, uint32_t first, uint32_t count, const api::viewport *viewports); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_scissor_rects, void, api::command_list *cmd_list, uint32_t first, uint32_t count, const api::rect *rects); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::push_constants, void, api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t layout_param, uint32_t first, uint32_t count, const void *values); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::push_descriptors, void, api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t layout_param, const api::descriptor_table_update &update); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_descriptor_tables, void, api::command_list *cmd_list, api::shader_stage stages, api::pipeline_layout layout, uint32_t first, uint32_t count, const api::descriptor_table *tables); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_index_buffer, void, api::command_list *cmd_list, api::resource buffer, uint64_t offset, uint32_t index_size); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_vertex_buffers, void, api::command_list *cmd_list, uint32_t first, uint32_t count, const api::resource *buffers, const uint64_t *offsets, const uint32_t *strides); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::bind_stream_output_buffers, void, api::command_list *cmd_list, uint32_t first, uint32_t count, const api::resource *buffers, const uint64_t *offsets, const uint64_t *max_sizes, const api::resource *counter_buffers, const uint64_t *counter_offsets); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::draw, bool, api::command_list *cmd_list, uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::draw_indexed, bool, api::command_list *cmd_list, uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::dispatch, bool, api::command_list *cmd_list, uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::draw_or_dispatch_indirect, bool, api::command_list *cmd_list, api::indirect_command type, api::resource buffer, uint64_t offset, uint32_t draw_count, uint32_t stride); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_resource, bool, api::command_list *cmd_list, api::resource source, api::resource dest); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_buffer_region, bool, api::command_list *cmd_list, api::resource source, uint64_t source_offset, api::resource dest, uint64_t dest_offset, uint64_t size); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_buffer_to_texture, bool, api::command_list *cmd_list, api::resource source, uint64_t source_offset, uint32_t row_length, uint32_t slice_height, api::resource dest, uint32_t dest_subresource, const api::subresource_box *dest_box); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_texture_region, bool, api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint32_t dest_subresource, const api::subresource_box *dest_box, api::filter_mode filter); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_texture_to_buffer, bool, api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint64_t dest_offset, uint32_t row_length, uint32_t slice_height); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::resolve_texture_region, bool, api::command_list *cmd_list, api::resource source, uint32_t source_subresource, const api::subresource_box *source_box, api::resource dest, uint32_t dest_subresource, int32_t dest_x, int32_t dest_y, int32_t dest_z, api::format format); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::clear_depth_stencil_view, bool, api::command_list *cmd_list, api::resource_view dsv, const float *depth, const uint8_t *stencil, uint32_t rect_count, const api::rect *rects); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::clear_render_target_view, bool, api::command_list *cmd_list, api::resource_view rtv, const float color[4], uint32_t rect_count, const api::rect *rects); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::clear_unordered_access_view_uint, bool, api::command_list *cmd_list, api::resource_view uav, const uint32_t values[4], uint32_t rect_count, const api::rect *rects); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::clear_unordered_access_view_float, bool, api::command_list *cmd_list, api::resource_view uav, const float values[4], uint32_t rect_count, const api::rect *rects); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::generate_mipmaps, bool, api::command_list *cmd_list, api::resource_view srv); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::begin_query, bool, api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t index); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::end_query, bool, api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t index); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::copy_query_heap_results, bool, api::command_list *cmd_list, api::query_heap heap, api::query_type type, uint32_t first, uint32_t count, api::resource dest, uint64_t dest_offset, uint32_t stride); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reset_command_list, void, api::command_list *cmd_list); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::close_command_list, void, api::command_list *cmd_list); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::execute_command_list, void, api::command_queue *queue, api::command_list *cmd_list); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::execute_secondary_command_list, void, api::command_list *cmd_list, api::command_list *secondary_cmd_list); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::present, void, api::command_queue *queue, api::swapchain *swapchain, const api::rect *source_rect, const api::rect *dest_rect, uint32_t dirty_rect_count, const api::rect *dirty_rects); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_present, void, api::effect_runtime *runtime); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_begin_effects, void, api::effect_runtime *runtime, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_finish_effects, void, api::effect_runtime *runtime, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_reloaded_effects, void, api::effect_runtime *runtime); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_set_uniform_value, bool, api::effect_runtime *runtime, api::effect_uniform_variable variable, const void *data, size_t size); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_set_technique_state, bool, api::effect_runtime *runtime, api::effect_technique technique, bool enabled); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_overlay, void, api::effect_runtime *runtime); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_screenshot, void, api::effect_runtime *runtime, const char *path); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_render_technique, void, api::effect_runtime *runtime, api::effect_technique technique, api::command_list *cmd_list, api::resource_view rtv, api::resource_view rtv_srgb); + + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_set_current_preset_path, void, api::effect_runtime *runtime, const char *path); + RESHADE_DEFINE_ADDON_EVENT_TRAITS(addon_event::reshade_reorder_techniques, bool, api::effect_runtime *runtime, size_t count, api::effect_technique *techniques); +} diff --git a/Plugin/include/reshade/reshade_overlay.hpp b/Plugin/include/reshade/reshade_overlay.hpp new file mode 100644 index 00000000..a68ffaef --- /dev/null +++ b/Plugin/include/reshade/reshade_overlay.hpp @@ -0,0 +1,870 @@ +/* + * Copyright (C) 2021 Patrick Mours + * Copyright (C) 2014-2023 Omar Cornut + * SPDX-License-Identifier: BSD-3-Clause OR MIT + */ + +#if defined(IMGUI_VERSION_NUM) + +#if IMGUI_VERSION_NUM != 18971 +#error Unexpected ImGui version, please update the "imgui.h" header to version 18971! +#endif + +// Check that the 'ImTextureID' type has the same size as 'reshade::api::resource_view' +static_assert(sizeof(ImTextureID) == 8, "missing \"#define ImTextureID ImU64\" before \"#include \""); + +struct imgui_function_table_18971 +{ + ImGuiIO&(*GetIO)(); + ImGuiStyle&(*GetStyle)(); + const char*(*GetVersion)(); + bool(*Begin)(const char* name, bool* p_open, ImGuiWindowFlags flags); + void(*End)(); + bool(*BeginChild)(const char* str_id, const ImVec2& size, bool border, ImGuiWindowFlags flags); + bool(*BeginChild2)(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags flags); + void(*EndChild)(); + bool(*IsWindowAppearing)(); + bool(*IsWindowCollapsed)(); + bool(*IsWindowFocused)(ImGuiFocusedFlags flags); + bool(*IsWindowHovered)(ImGuiHoveredFlags flags); + ImDrawList*(*GetWindowDrawList)(); + float(*GetWindowDpiScale)(); + ImVec2(*GetWindowPos)(); + ImVec2(*GetWindowSize)(); + float(*GetWindowWidth)(); + float(*GetWindowHeight)(); + void(*SetNextWindowPos)(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot); + void(*SetNextWindowSize)(const ImVec2& size, ImGuiCond cond); + void(*SetNextWindowSizeConstraints)(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_data); + void(*SetNextWindowContentSize)(const ImVec2& size); + void(*SetNextWindowCollapsed)(bool collapsed, ImGuiCond cond); + void(*SetNextWindowFocus)(); + void(*SetNextWindowScroll)(const ImVec2& scroll); + void(*SetNextWindowBgAlpha)(float alpha); + void(*SetWindowPos)(const ImVec2& pos, ImGuiCond cond); + void(*SetWindowSize)(const ImVec2& size, ImGuiCond cond); + void(*SetWindowCollapsed)(bool collapsed, ImGuiCond cond); + void(*SetWindowFocus)(); + void(*SetWindowFontScale)(float scale); + void(*SetWindowPos2)(const char* name, const ImVec2& pos, ImGuiCond cond); + void(*SetWindowSize2)(const char* name, const ImVec2& size, ImGuiCond cond); + void(*SetWindowCollapsed2)(const char* name, bool collapsed, ImGuiCond cond); + void(*SetWindowFocus2)(const char* name); + ImVec2(*GetContentRegionAvail)(); + ImVec2(*GetContentRegionMax)(); + ImVec2(*GetWindowContentRegionMin)(); + ImVec2(*GetWindowContentRegionMax)(); + float(*GetScrollX)(); + float(*GetScrollY)(); + void(*SetScrollX)(float scroll_x); + void(*SetScrollY)(float scroll_y); + float(*GetScrollMaxX)(); + float(*GetScrollMaxY)(); + void(*SetScrollHereX)(float center_x_ratio); + void(*SetScrollHereY)(float center_y_ratio); + void(*SetScrollFromPosX)(float local_x, float center_x_ratio); + void(*SetScrollFromPosY)(float local_y, float center_y_ratio); + void(*PushFont)(ImFont* font); + void(*PopFont)(); + void(*PushStyleColor)(ImGuiCol idx, ImU32 col); + void(*PushStyleColor2)(ImGuiCol idx, const ImVec4& col); + void(*PopStyleColor)(int count); + void(*PushStyleVar)(ImGuiStyleVar idx, float val); + void(*PushStyleVar2)(ImGuiStyleVar idx, const ImVec2& val); + void(*PopStyleVar)(int count); + void(*PushTabStop)(bool tab_stop); + void(*PopTabStop)(); + void(*PushButtonRepeat)(bool repeat); + void(*PopButtonRepeat)(); + void(*PushItemWidth)(float item_width); + void(*PopItemWidth)(); + void(*SetNextItemWidth)(float item_width); + float(*CalcItemWidth)(); + void(*PushTextWrapPos)(float wrap_local_pos_x); + void(*PopTextWrapPos)(); + ImFont*(*GetFont)(); + float(*GetFontSize)(); + ImVec2(*GetFontTexUvWhitePixel)(); + ImU32(*GetColorU32)(ImGuiCol idx, float alpha_mul); + ImU32(*GetColorU322)(const ImVec4& col); + ImU32(*GetColorU323)(ImU32 col); + const ImVec4&(*GetStyleColorVec4)(ImGuiCol idx); + void(*Separator)(); + void(*SameLine)(float offset_from_start_x, float spacing); + void(*NewLine)(); + void(*Spacing)(); + void(*Dummy)(const ImVec2& size); + void(*Indent)(float indent_w); + void(*Unindent)(float indent_w); + void(*BeginGroup)(); + void(*EndGroup)(); + ImVec2(*GetCursorPos)(); + float(*GetCursorPosX)(); + float(*GetCursorPosY)(); + void(*SetCursorPos)(const ImVec2& local_pos); + void(*SetCursorPosX)(float local_x); + void(*SetCursorPosY)(float local_y); + ImVec2(*GetCursorStartPos)(); + ImVec2(*GetCursorScreenPos)(); + void(*SetCursorScreenPos)(const ImVec2& pos); + void(*AlignTextToFramePadding)(); + float(*GetTextLineHeight)(); + float(*GetTextLineHeightWithSpacing)(); + float(*GetFrameHeight)(); + float(*GetFrameHeightWithSpacing)(); + void(*PushID)(const char* str_id); + void(*PushID2)(const char* str_id_begin, const char* str_id_end); + void(*PushID3)(const void* ptr_id); + void(*PushID4)(int int_id); + void(*PopID)(); + ImGuiID(*GetID)(const char* str_id); + ImGuiID(*GetID2)(const char* str_id_begin, const char* str_id_end); + ImGuiID(*GetID3)(const void* ptr_id); + void(*TextUnformatted)(const char* text, const char* text_end); + void(*TextV)(const char* fmt, va_list args); + void(*TextColoredV)(const ImVec4& col, const char* fmt, va_list args); + void(*TextDisabledV)(const char* fmt, va_list args); + void(*TextWrappedV)(const char* fmt, va_list args); + void(*LabelTextV)(const char* label, const char* fmt, va_list args); + void(*BulletTextV)(const char* fmt, va_list args); + void(*SeparatorText)(const char* label); + bool(*Button)(const char* label, const ImVec2& size); + bool(*SmallButton)(const char* label); + bool(*InvisibleButton)(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags); + bool(*ArrowButton)(const char* str_id, ImGuiDir dir); + bool(*Checkbox)(const char* label, bool* v); + bool(*CheckboxFlags)(const char* label, int* flags, int flags_value); + bool(*CheckboxFlags2)(const char* label, unsigned int* flags, unsigned int flags_value); + bool(*RadioButton)(const char* label, bool active); + bool(*RadioButton2)(const char* label, int* v, int v_button); + void(*ProgressBar)(float fraction, const ImVec2& size_arg, const char* overlay); + void(*Bullet)(); + void(*Image)(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); + bool(*ImageButton)(const char* str_id, ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col); + bool(*BeginCombo)(const char* label, const char* preview_value, ImGuiComboFlags flags); + void(*EndCombo)(); + bool(*Combo)(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items); + bool(*Combo2)(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items); + bool(*Combo3)(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items); + bool(*DragFloat)(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragFloat2)(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragFloat3)(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragFloat4)(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragFloatRange2)(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags); + bool(*DragInt)(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragInt2)(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragInt3)(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragInt4)(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*DragIntRange2)(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags); + bool(*DragScalar)(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + bool(*DragScalarN)(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderFloat)(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderFloat2)(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderFloat3)(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderFloat4)(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderAngle)(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderInt)(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderInt2)(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderInt3)(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderInt4)(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderScalar)(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + bool(*SliderScalarN)(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + bool(*VSliderFloat)(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags); + bool(*VSliderInt)(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags); + bool(*VSliderScalar)(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); + bool(*InputText)(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); + bool(*InputTextMultiline)(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); + bool(*InputTextWithHint)(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); + bool(*InputFloat)(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags); + bool(*InputFloat2)(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags); + bool(*InputFloat3)(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags); + bool(*InputFloat4)(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags); + bool(*InputInt)(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags); + bool(*InputInt2)(const char* label, int v[2], ImGuiInputTextFlags flags); + bool(*InputInt3)(const char* label, int v[3], ImGuiInputTextFlags flags); + bool(*InputInt4)(const char* label, int v[4], ImGuiInputTextFlags flags); + bool(*InputDouble)(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags); + bool(*InputScalar)(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags); + bool(*InputScalarN)(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags); + bool(*ColorEdit3)(const char* label, float col[3], ImGuiColorEditFlags flags); + bool(*ColorEdit4)(const char* label, float col[4], ImGuiColorEditFlags flags); + bool(*ColorPicker3)(const char* label, float col[3], ImGuiColorEditFlags flags); + bool(*ColorPicker4)(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col); + bool(*ColorButton)(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size); + void(*SetColorEditOptions)(ImGuiColorEditFlags flags); + bool(*TreeNode)(const char* label); + bool(*TreeNodeV)(const char* str_id, const char* fmt, va_list args); + bool(*TreeNodeV2)(const void* ptr_id, const char* fmt, va_list args); + bool(*TreeNodeEx)(const char* label, ImGuiTreeNodeFlags flags); + bool(*TreeNodeExV)(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + bool(*TreeNodeExV2)(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + void(*TreePush)(const char* str_id); + void(*TreePush2)(const void* ptr_id); + void(*TreePop)(); + float(*GetTreeNodeToLabelSpacing)(); + bool(*CollapsingHeader)(const char* label, ImGuiTreeNodeFlags flags); + bool(*CollapsingHeader2)(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags); + void(*SetNextItemOpen)(bool is_open, ImGuiCond cond); + bool(*Selectable)(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size); + bool(*Selectable2)(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size); + bool(*BeginListBox)(const char* label, const ImVec2& size); + void(*EndListBox)(); + bool(*ListBox)(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items); + bool(*ListBox2)(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items); + void(*PlotLines)(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride); + void(*PlotLines2)(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + void(*PlotHistogram)(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride); + void(*PlotHistogram2)(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + void(*Value)(const char* prefix, bool b); + void(*Value2)(const char* prefix, int v); + void(*Value3)(const char* prefix, unsigned int v); + void(*Value4)(const char* prefix, float v, const char* float_format); + bool(*BeginMenuBar)(); + void(*EndMenuBar)(); + bool(*BeginMainMenuBar)(); + void(*EndMainMenuBar)(); + bool(*BeginMenu)(const char* label, bool enabled); + void(*EndMenu)(); + bool(*MenuItem)(const char* label, const char* shortcut, bool selected, bool enabled); + bool(*MenuItem2)(const char* label, const char* shortcut, bool* p_selected, bool enabled); + bool(*BeginTooltip)(); + void(*EndTooltip)(); + void(*SetTooltipV)(const char* fmt, va_list args); + bool(*BeginItemTooltip)(); + void(*SetItemTooltipV)(const char* fmt, va_list args); + bool(*BeginPopup)(const char* str_id, ImGuiWindowFlags flags); + bool(*BeginPopupModal)(const char* name, bool* p_open, ImGuiWindowFlags flags); + void(*EndPopup)(); + void(*OpenPopup)(const char* str_id, ImGuiPopupFlags popup_flags); + void(*OpenPopup2)(ImGuiID id, ImGuiPopupFlags popup_flags); + void(*OpenPopupOnItemClick)(const char* str_id, ImGuiPopupFlags popup_flags); + void(*CloseCurrentPopup)(); + bool(*BeginPopupContextItem)(const char* str_id, ImGuiPopupFlags popup_flags); + bool(*BeginPopupContextWindow)(const char* str_id, ImGuiPopupFlags popup_flags); + bool(*BeginPopupContextVoid)(const char* str_id, ImGuiPopupFlags popup_flags); + bool(*IsPopupOpen)(const char* str_id, ImGuiPopupFlags flags); + bool(*BeginTable)(const char* str_id, int column, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width); + void(*EndTable)(); + void(*TableNextRow)(ImGuiTableRowFlags row_flags, float min_row_height); + bool(*TableNextColumn)(); + bool(*TableSetColumnIndex)(int column_n); + void(*TableSetupColumn)(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id); + void(*TableSetupScrollFreeze)(int cols, int rows); + void(*TableHeadersRow)(); + void(*TableHeader)(const char* label); + ImGuiTableSortSpecs*(*TableGetSortSpecs)(); + int(*TableGetColumnCount)(); + int(*TableGetColumnIndex)(); + int(*TableGetRowIndex)(); + const char*(*TableGetColumnName)(int column_n); + ImGuiTableColumnFlags(*TableGetColumnFlags)(int column_n); + void(*TableSetColumnEnabled)(int column_n, bool v); + void(*TableSetBgColor)(ImGuiTableBgTarget target, ImU32 color, int column_n); + void(*Columns)(int count, const char* id, bool border); + void(*NextColumn)(); + int(*GetColumnIndex)(); + float(*GetColumnWidth)(int column_index); + void(*SetColumnWidth)(int column_index, float width); + float(*GetColumnOffset)(int column_index); + void(*SetColumnOffset)(int column_index, float offset_x); + int(*GetColumnsCount)(); + bool(*BeginTabBar)(const char* str_id, ImGuiTabBarFlags flags); + void(*EndTabBar)(); + bool(*BeginTabItem)(const char* label, bool* p_open, ImGuiTabItemFlags flags); + void(*EndTabItem)(); + bool(*TabItemButton)(const char* label, ImGuiTabItemFlags flags); + void(*SetTabItemClosed)(const char* tab_or_docked_window_label); + ImGuiID(*DockSpace)(ImGuiID id, const ImVec2& size, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class); + void(*SetNextWindowDockID)(ImGuiID dock_id, ImGuiCond cond); + void(*SetNextWindowClass)(const ImGuiWindowClass* window_class); + ImGuiID(*GetWindowDockID)(); + bool(*IsWindowDocked)(); + bool(*BeginDragDropSource)(ImGuiDragDropFlags flags); + bool(*SetDragDropPayload)(const char* type, const void* data, size_t sz, ImGuiCond cond); + void(*EndDragDropSource)(); + bool(*BeginDragDropTarget)(); + const ImGuiPayload*(*AcceptDragDropPayload)(const char* type, ImGuiDragDropFlags flags); + void(*EndDragDropTarget)(); + const ImGuiPayload*(*GetDragDropPayload)(); + void(*BeginDisabled)(bool disabled); + void(*EndDisabled)(); + void(*PushClipRect)(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + void(*PopClipRect)(); + void(*SetItemDefaultFocus)(); + void(*SetKeyboardFocusHere)(int offset); + void(*SetNextItemAllowOverlap)(); + bool(*IsItemHovered)(ImGuiHoveredFlags flags); + bool(*IsItemActive)(); + bool(*IsItemFocused)(); + bool(*IsItemClicked)(ImGuiMouseButton mouse_button); + bool(*IsItemVisible)(); + bool(*IsItemEdited)(); + bool(*IsItemActivated)(); + bool(*IsItemDeactivated)(); + bool(*IsItemDeactivatedAfterEdit)(); + bool(*IsItemToggledOpen)(); + bool(*IsAnyItemHovered)(); + bool(*IsAnyItemActive)(); + bool(*IsAnyItemFocused)(); + ImGuiID(*GetItemID)(); + ImVec2(*GetItemRectMin)(); + ImVec2(*GetItemRectMax)(); + ImVec2(*GetItemRectSize)(); + ImDrawList*(*GetBackgroundDrawList)(); + ImDrawList*(*GetForegroundDrawList)(); + ImDrawList*(*GetBackgroundDrawList2)(ImGuiViewport* viewport); + ImDrawList*(*GetForegroundDrawList2)(ImGuiViewport* viewport); + bool(*IsRectVisible)(const ImVec2& size); + bool(*IsRectVisible2)(const ImVec2& rect_min, const ImVec2& rect_max); + double(*GetTime)(); + int(*GetFrameCount)(); + ImDrawListSharedData*(*GetDrawListSharedData)(); + const char*(*GetStyleColorName)(ImGuiCol idx); + void(*SetStateStorage)(ImGuiStorage* storage); + ImGuiStorage*(*GetStateStorage)(); + bool(*BeginChildFrame)(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags); + void(*EndChildFrame)(); + ImVec2(*CalcTextSize)(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width); + ImVec4(*ColorConvertU32ToFloat4)(ImU32 in); + ImU32(*ColorConvertFloat4ToU32)(const ImVec4& in); + void(*ColorConvertRGBtoHSV)(float r, float g, float b, float& out_h, float& out_s, float& out_v); + void(*ColorConvertHSVtoRGB)(float h, float s, float v, float& out_r, float& out_g, float& out_b); + bool(*IsKeyDown)(ImGuiKey key); + bool(*IsKeyPressed)(ImGuiKey key, bool repeat); + bool(*IsKeyReleased)(ImGuiKey key); + int(*GetKeyPressedAmount)(ImGuiKey key, float repeat_delay, float rate); + const char*(*GetKeyName)(ImGuiKey key); + void(*SetNextFrameWantCaptureKeyboard)(bool want_capture_keyboard); + bool(*IsMouseDown)(ImGuiMouseButton button); + bool(*IsMouseClicked)(ImGuiMouseButton button, bool repeat); + bool(*IsMouseReleased)(ImGuiMouseButton button); + bool(*IsMouseDoubleClicked)(ImGuiMouseButton button); + int(*GetMouseClickedCount)(ImGuiMouseButton button); + bool(*IsMouseHoveringRect)(const ImVec2& r_min, const ImVec2& r_max, bool clip); + bool(*IsMousePosValid)(const ImVec2* mouse_pos); + bool(*IsAnyMouseDown)(); + ImVec2(*GetMousePos)(); + ImVec2(*GetMousePosOnOpeningCurrentPopup)(); + bool(*IsMouseDragging)(ImGuiMouseButton button, float lock_threshold); + ImVec2(*GetMouseDragDelta)(ImGuiMouseButton button, float lock_threshold); + void(*ResetMouseDragDelta)(ImGuiMouseButton button); + ImGuiMouseCursor(*GetMouseCursor)(); + void(*SetMouseCursor)(ImGuiMouseCursor cursor_type); + void(*SetNextFrameWantCaptureMouse)(bool want_capture_mouse); + const char*(*GetClipboardText)(); + void(*SetClipboardText)(const char* text); + void(*SetAllocatorFunctions)(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data); + void(*GetAllocatorFunctions)(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); + void*(*MemAlloc)(size_t size); + void(*MemFree)(void* ptr); + int(*ImGuiStorage_GetInt)(const ImGuiStorage *_this, ImGuiID key, int default_val); + void(*ImGuiStorage_SetInt)(ImGuiStorage *_this, ImGuiID key, int val); + bool(*ImGuiStorage_GetBool)(const ImGuiStorage *_this, ImGuiID key, bool default_val); + void(*ImGuiStorage_SetBool)(ImGuiStorage *_this, ImGuiID key, bool val); + float(*ImGuiStorage_GetFloat)(const ImGuiStorage *_this, ImGuiID key, float default_val); + void(*ImGuiStorage_SetFloat)(ImGuiStorage *_this, ImGuiID key, float val); + void*(*ImGuiStorage_GetVoidPtr)(const ImGuiStorage *_this, ImGuiID key); + void(*ImGuiStorage_SetVoidPtr)(ImGuiStorage *_this, ImGuiID key, void* val); + int*(*ImGuiStorage_GetIntRef)(ImGuiStorage *_this, ImGuiID key, int default_val); + bool*(*ImGuiStorage_GetBoolRef)(ImGuiStorage *_this, ImGuiID key, bool default_val); + float*(*ImGuiStorage_GetFloatRef)(ImGuiStorage *_this, ImGuiID key, float default_val); + void**(*ImGuiStorage_GetVoidPtrRef)(ImGuiStorage *_this, ImGuiID key, void* default_val); + void(*ImGuiStorage_SetAllInt)(ImGuiStorage *_this, int val); + void(*ImGuiStorage_BuildSortByKey)(ImGuiStorage *_this); + void(*ConstructImGuiListClipper)(ImGuiListClipper *_this); + void(*DestructImGuiListClipper)(ImGuiListClipper *_this); + void(*ImGuiListClipper_Begin)(ImGuiListClipper *_this, int items_count, float items_height); + void(*ImGuiListClipper_End)(ImGuiListClipper *_this); + bool(*ImGuiListClipper_Step)(ImGuiListClipper *_this); + void(*ImGuiListClipper_IncludeRangeByIndices)(ImGuiListClipper *_this, int item_begin, int item_end); + void(*ImDrawList_PushClipRect)(ImDrawList *_this, const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + void(*ImDrawList_PushClipRectFullScreen)(ImDrawList *_this); + void(*ImDrawList_PopClipRect)(ImDrawList *_this); + void(*ImDrawList_PushTextureID)(ImDrawList *_this, ImTextureID texture_id); + void(*ImDrawList_PopTextureID)(ImDrawList *_this); + void(*ImDrawList_AddLine)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness); + void(*ImDrawList_AddRect)(ImDrawList *_this, const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness); + void(*ImDrawList_AddRectFilled)(ImDrawList *_this, const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags); + void(*ImDrawList_AddRectFilledMultiColor)(ImDrawList *_this, const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + void(*ImDrawList_AddQuad)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness); + void(*ImDrawList_AddQuadFilled)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); + void(*ImDrawList_AddTriangle)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness); + void(*ImDrawList_AddTriangleFilled)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); + void(*ImDrawList_AddCircle)(ImDrawList *_this, const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness); + void(*ImDrawList_AddCircleFilled)(ImDrawList *_this, const ImVec2& center, float radius, ImU32 col, int num_segments); + void(*ImDrawList_AddNgon)(ImDrawList *_this, const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness); + void(*ImDrawList_AddNgonFilled)(ImDrawList *_this, const ImVec2& center, float radius, ImU32 col, int num_segments); + void(*ImDrawList_AddText)(ImDrawList *_this, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end); + void(*ImDrawList_AddText2)(ImDrawList *_this, const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect); + void(*ImDrawList_AddPolyline)(ImDrawList *_this, const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); + void(*ImDrawList_AddConvexPolyFilled)(ImDrawList *_this, const ImVec2* points, int num_points, ImU32 col); + void(*ImDrawList_AddBezierCubic)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments); + void(*ImDrawList_AddBezierQuadratic)(ImDrawList *_this, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments); + void(*ImDrawList_AddImage)(ImDrawList *_this, ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col); + void(*ImDrawList_AddImageQuad)(ImDrawList *_this, ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col); + void(*ImDrawList_AddImageRounded)(ImDrawList *_this, ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags); + void(*ImDrawList_PathArcTo)(ImDrawList *_this, const ImVec2& center, float radius, float a_min, float a_max, int num_segments); + void(*ImDrawList_PathArcToFast)(ImDrawList *_this, const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); + void(*ImDrawList_PathBezierCubicCurveTo)(ImDrawList *_this, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments); + void(*ImDrawList_PathBezierQuadraticCurveTo)(ImDrawList *_this, const ImVec2& p2, const ImVec2& p3, int num_segments); + void(*ImDrawList_PathRect)(ImDrawList *_this, const ImVec2& rect_min, const ImVec2& rect_max, float rounding, ImDrawFlags flags); + void(*ImDrawList_AddCallback)(ImDrawList *_this, ImDrawCallback callback, void* callback_data); + void(*ImDrawList_AddDrawCmd)(ImDrawList *_this); + ImDrawList*(*ImDrawList_CloneOutput)(const ImDrawList *_this); + void(*ImDrawList_PrimReserve)(ImDrawList *_this, int idx_count, int vtx_count); + void(*ImDrawList_PrimUnreserve)(ImDrawList *_this, int idx_count, int vtx_count); + void(*ImDrawList_PrimRect)(ImDrawList *_this, const ImVec2& a, const ImVec2& b, ImU32 col); + void(*ImDrawList_PrimRectUV)(ImDrawList *_this, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + void(*ImDrawList_PrimQuadUV)(ImDrawList *_this, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + void(*ConstructImFont)(ImFont *_this); + void(*DestructImFont)(ImFont *_this); + const ImFontGlyph*(*ImFont_FindGlyph)(const ImFont *_this, ImWchar c); + const ImFontGlyph*(*ImFont_FindGlyphNoFallback)(const ImFont *_this, ImWchar c); + ImVec2(*ImFont_CalcTextSizeA)(const ImFont *_this, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining); + const char*(*ImFont_CalcWordWrapPositionA)(const ImFont *_this, float scale, const char* text, const char* text_end, float wrap_width); + void(*ImFont_RenderChar)(const ImFont *_this, ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c); + void(*ImFont_RenderText)(const ImFont *_this, ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip); + +}; + +using imgui_function_table = imgui_function_table_18971; + +inline const imgui_function_table *&imgui_function_table_instance() +{ + static const imgui_function_table *instance = nullptr; + return instance; +} + +#ifndef RESHADE_API_LIBRARY_EXPORT + +namespace ImGui +{ + inline ImGuiIO& GetIO() { return imgui_function_table_instance()->GetIO(); } + inline ImGuiStyle& GetStyle() { return imgui_function_table_instance()->GetStyle(); } + inline const char* GetVersion() { return imgui_function_table_instance()->GetVersion(); } + inline bool Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { return imgui_function_table_instance()->Begin(name, p_open, flags); } + inline void End() { imgui_function_table_instance()->End(); } + inline bool BeginChild(const char* str_id, const ImVec2& size, bool border, ImGuiWindowFlags flags) { return imgui_function_table_instance()->BeginChild(str_id, size, border, flags); } + inline bool BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags flags) { return imgui_function_table_instance()->BeginChild2(id, size, border, flags); } + inline void EndChild() { imgui_function_table_instance()->EndChild(); } + inline bool IsWindowAppearing() { return imgui_function_table_instance()->IsWindowAppearing(); } + inline bool IsWindowCollapsed() { return imgui_function_table_instance()->IsWindowCollapsed(); } + inline bool IsWindowFocused(ImGuiFocusedFlags flags) { return imgui_function_table_instance()->IsWindowFocused(flags); } + inline bool IsWindowHovered(ImGuiHoveredFlags flags) { return imgui_function_table_instance()->IsWindowHovered(flags); } + inline ImDrawList* GetWindowDrawList() { return imgui_function_table_instance()->GetWindowDrawList(); } + inline float GetWindowDpiScale() { return imgui_function_table_instance()->GetWindowDpiScale(); } + inline ImVec2 GetWindowPos() { return imgui_function_table_instance()->GetWindowPos(); } + inline ImVec2 GetWindowSize() { return imgui_function_table_instance()->GetWindowSize(); } + inline float GetWindowWidth() { return imgui_function_table_instance()->GetWindowWidth(); } + inline float GetWindowHeight() { return imgui_function_table_instance()->GetWindowHeight(); } + inline void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) { imgui_function_table_instance()->SetNextWindowPos(pos, cond, pivot); } + inline void SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { imgui_function_table_instance()->SetNextWindowSize(size, cond); } + inline void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_data) { imgui_function_table_instance()->SetNextWindowSizeConstraints(size_min, size_max, custom_callback, custom_callback_data); } + inline void SetNextWindowContentSize(const ImVec2& size) { imgui_function_table_instance()->SetNextWindowContentSize(size); } + inline void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { imgui_function_table_instance()->SetNextWindowCollapsed(collapsed, cond); } + inline void SetNextWindowFocus() { imgui_function_table_instance()->SetNextWindowFocus(); } + inline void SetNextWindowScroll(const ImVec2& scroll) { imgui_function_table_instance()->SetNextWindowScroll(scroll); } + inline void SetNextWindowBgAlpha(float alpha) { imgui_function_table_instance()->SetNextWindowBgAlpha(alpha); } + inline void SetWindowPos(const ImVec2& pos, ImGuiCond cond) { imgui_function_table_instance()->SetWindowPos(pos, cond); } + inline void SetWindowSize(const ImVec2& size, ImGuiCond cond) { imgui_function_table_instance()->SetWindowSize(size, cond); } + inline void SetWindowCollapsed(bool collapsed, ImGuiCond cond) { imgui_function_table_instance()->SetWindowCollapsed(collapsed, cond); } + inline void SetWindowFocus() { imgui_function_table_instance()->SetWindowFocus(); } + inline void SetWindowFontScale(float scale) { imgui_function_table_instance()->SetWindowFontScale(scale); } + inline void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) { imgui_function_table_instance()->SetWindowPos2(name, pos, cond); } + inline void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) { imgui_function_table_instance()->SetWindowSize2(name, size, cond); } + inline void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) { imgui_function_table_instance()->SetWindowCollapsed2(name, collapsed, cond); } + inline void SetWindowFocus(const char* name) { imgui_function_table_instance()->SetWindowFocus2(name); } + inline ImVec2 GetContentRegionAvail() { return imgui_function_table_instance()->GetContentRegionAvail(); } + inline ImVec2 GetContentRegionMax() { return imgui_function_table_instance()->GetContentRegionMax(); } + inline ImVec2 GetWindowContentRegionMin() { return imgui_function_table_instance()->GetWindowContentRegionMin(); } + inline ImVec2 GetWindowContentRegionMax() { return imgui_function_table_instance()->GetWindowContentRegionMax(); } + inline float GetScrollX() { return imgui_function_table_instance()->GetScrollX(); } + inline float GetScrollY() { return imgui_function_table_instance()->GetScrollY(); } + inline void SetScrollX(float scroll_x) { imgui_function_table_instance()->SetScrollX(scroll_x); } + inline void SetScrollY(float scroll_y) { imgui_function_table_instance()->SetScrollY(scroll_y); } + inline float GetScrollMaxX() { return imgui_function_table_instance()->GetScrollMaxX(); } + inline float GetScrollMaxY() { return imgui_function_table_instance()->GetScrollMaxY(); } + inline void SetScrollHereX(float center_x_ratio) { imgui_function_table_instance()->SetScrollHereX(center_x_ratio); } + inline void SetScrollHereY(float center_y_ratio) { imgui_function_table_instance()->SetScrollHereY(center_y_ratio); } + inline void SetScrollFromPosX(float local_x, float center_x_ratio) { imgui_function_table_instance()->SetScrollFromPosX(local_x, center_x_ratio); } + inline void SetScrollFromPosY(float local_y, float center_y_ratio) { imgui_function_table_instance()->SetScrollFromPosY(local_y, center_y_ratio); } + inline void PushFont(ImFont* font) { imgui_function_table_instance()->PushFont(font); } + inline void PopFont() { imgui_function_table_instance()->PopFont(); } + inline void PushStyleColor(ImGuiCol idx, ImU32 col) { imgui_function_table_instance()->PushStyleColor(idx, col); } + inline void PushStyleColor(ImGuiCol idx, const ImVec4& col) { imgui_function_table_instance()->PushStyleColor2(idx, col); } + inline void PopStyleColor(int count) { imgui_function_table_instance()->PopStyleColor(count); } + inline void PushStyleVar(ImGuiStyleVar idx, float val) { imgui_function_table_instance()->PushStyleVar(idx, val); } + inline void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { imgui_function_table_instance()->PushStyleVar2(idx, val); } + inline void PopStyleVar(int count) { imgui_function_table_instance()->PopStyleVar(count); } + inline void PushTabStop(bool tab_stop) { imgui_function_table_instance()->PushTabStop(tab_stop); } + inline void PopTabStop() { imgui_function_table_instance()->PopTabStop(); } + inline void PushButtonRepeat(bool repeat) { imgui_function_table_instance()->PushButtonRepeat(repeat); } + inline void PopButtonRepeat() { imgui_function_table_instance()->PopButtonRepeat(); } + inline void PushItemWidth(float item_width) { imgui_function_table_instance()->PushItemWidth(item_width); } + inline void PopItemWidth() { imgui_function_table_instance()->PopItemWidth(); } + inline void SetNextItemWidth(float item_width) { imgui_function_table_instance()->SetNextItemWidth(item_width); } + inline float CalcItemWidth() { return imgui_function_table_instance()->CalcItemWidth(); } + inline void PushTextWrapPos(float wrap_local_pos_x) { imgui_function_table_instance()->PushTextWrapPos(wrap_local_pos_x); } + inline void PopTextWrapPos() { imgui_function_table_instance()->PopTextWrapPos(); } + inline ImFont* GetFont() { return imgui_function_table_instance()->GetFont(); } + inline float GetFontSize() { return imgui_function_table_instance()->GetFontSize(); } + inline ImVec2 GetFontTexUvWhitePixel() { return imgui_function_table_instance()->GetFontTexUvWhitePixel(); } + inline ImU32 GetColorU32(ImGuiCol idx, float alpha_mul) { return imgui_function_table_instance()->GetColorU32(idx, alpha_mul); } + inline ImU32 GetColorU32(const ImVec4& col) { return imgui_function_table_instance()->GetColorU322(col); } + inline ImU32 GetColorU32(ImU32 col) { return imgui_function_table_instance()->GetColorU323(col); } + inline const ImVec4& GetStyleColorVec4(ImGuiCol idx) { return imgui_function_table_instance()->GetStyleColorVec4(idx); } + inline void Separator() { imgui_function_table_instance()->Separator(); } + inline void SameLine(float offset_from_start_x, float spacing) { imgui_function_table_instance()->SameLine(offset_from_start_x, spacing); } + inline void NewLine() { imgui_function_table_instance()->NewLine(); } + inline void Spacing() { imgui_function_table_instance()->Spacing(); } + inline void Dummy(const ImVec2& size) { imgui_function_table_instance()->Dummy(size); } + inline void Indent(float indent_w) { imgui_function_table_instance()->Indent(indent_w); } + inline void Unindent(float indent_w) { imgui_function_table_instance()->Unindent(indent_w); } + inline void BeginGroup() { imgui_function_table_instance()->BeginGroup(); } + inline void EndGroup() { imgui_function_table_instance()->EndGroup(); } + inline ImVec2 GetCursorPos() { return imgui_function_table_instance()->GetCursorPos(); } + inline float GetCursorPosX() { return imgui_function_table_instance()->GetCursorPosX(); } + inline float GetCursorPosY() { return imgui_function_table_instance()->GetCursorPosY(); } + inline void SetCursorPos(const ImVec2& local_pos) { imgui_function_table_instance()->SetCursorPos(local_pos); } + inline void SetCursorPosX(float local_x) { imgui_function_table_instance()->SetCursorPosX(local_x); } + inline void SetCursorPosY(float local_y) { imgui_function_table_instance()->SetCursorPosY(local_y); } + inline ImVec2 GetCursorStartPos() { return imgui_function_table_instance()->GetCursorStartPos(); } + inline ImVec2 GetCursorScreenPos() { return imgui_function_table_instance()->GetCursorScreenPos(); } + inline void SetCursorScreenPos(const ImVec2& pos) { imgui_function_table_instance()->SetCursorScreenPos(pos); } + inline void AlignTextToFramePadding() { imgui_function_table_instance()->AlignTextToFramePadding(); } + inline float GetTextLineHeight() { return imgui_function_table_instance()->GetTextLineHeight(); } + inline float GetTextLineHeightWithSpacing() { return imgui_function_table_instance()->GetTextLineHeightWithSpacing(); } + inline float GetFrameHeight() { return imgui_function_table_instance()->GetFrameHeight(); } + inline float GetFrameHeightWithSpacing() { return imgui_function_table_instance()->GetFrameHeightWithSpacing(); } + inline void PushID(const char* str_id) { imgui_function_table_instance()->PushID(str_id); } + inline void PushID(const char* str_id_begin, const char* str_id_end) { imgui_function_table_instance()->PushID2(str_id_begin, str_id_end); } + inline void PushID(const void* ptr_id) { imgui_function_table_instance()->PushID3(ptr_id); } + inline void PushID(int int_id) { imgui_function_table_instance()->PushID4(int_id); } + inline void PopID() { imgui_function_table_instance()->PopID(); } + inline ImGuiID GetID(const char* str_id) { return imgui_function_table_instance()->GetID(str_id); } + inline ImGuiID GetID(const char* str_id_begin, const char* str_id_end) { return imgui_function_table_instance()->GetID2(str_id_begin, str_id_end); } + inline ImGuiID GetID(const void* ptr_id) { return imgui_function_table_instance()->GetID3(ptr_id); } + inline void TextUnformatted(const char* text, const char* text_end) { imgui_function_table_instance()->TextUnformatted(text, text_end); } + inline void Text(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->TextV(fmt, args); va_end(args); } + inline void TextV(const char* fmt, va_list args) { imgui_function_table_instance()->TextV(fmt, args); } + inline void TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->TextColoredV(col, fmt, args); va_end(args); } + inline void TextColoredV(const ImVec4& col, const char* fmt, va_list args) { imgui_function_table_instance()->TextColoredV(col, fmt, args); } + inline void TextDisabled(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->TextDisabledV(fmt, args); va_end(args); } + inline void TextDisabledV(const char* fmt, va_list args) { imgui_function_table_instance()->TextDisabledV(fmt, args); } + inline void TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->TextWrappedV(fmt, args); va_end(args); } + inline void TextWrappedV(const char* fmt, va_list args) { imgui_function_table_instance()->TextWrappedV(fmt, args); } + inline void LabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->LabelTextV(label, fmt, args); va_end(args); } + inline void LabelTextV(const char* label, const char* fmt, va_list args) { imgui_function_table_instance()->LabelTextV(label, fmt, args); } + inline void BulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->BulletTextV(fmt, args); va_end(args); } + inline void BulletTextV(const char* fmt, va_list args) { imgui_function_table_instance()->BulletTextV(fmt, args); } + inline void SeparatorText(const char* label) { imgui_function_table_instance()->SeparatorText(label); } + inline bool Button(const char* label, const ImVec2& size) { return imgui_function_table_instance()->Button(label, size); } + inline bool SmallButton(const char* label) { return imgui_function_table_instance()->SmallButton(label); } + inline bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags) { return imgui_function_table_instance()->InvisibleButton(str_id, size, flags); } + inline bool ArrowButton(const char* str_id, ImGuiDir dir) { return imgui_function_table_instance()->ArrowButton(str_id, dir); } + inline bool Checkbox(const char* label, bool* v) { return imgui_function_table_instance()->Checkbox(label, v); } + inline bool CheckboxFlags(const char* label, int* flags, int flags_value) { return imgui_function_table_instance()->CheckboxFlags(label, flags, flags_value); } + inline bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { return imgui_function_table_instance()->CheckboxFlags2(label, flags, flags_value); } + inline bool RadioButton(const char* label, bool active) { return imgui_function_table_instance()->RadioButton(label, active); } + inline bool RadioButton(const char* label, int* v, int v_button) { return imgui_function_table_instance()->RadioButton2(label, v, v_button); } + inline void ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) { imgui_function_table_instance()->ProgressBar(fraction, size_arg, overlay); } + inline void Bullet() { imgui_function_table_instance()->Bullet(); } + inline void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { imgui_function_table_instance()->Image(user_texture_id, size, uv0, uv1, tint_col, border_col); } + inline bool ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) { return imgui_function_table_instance()->ImageButton(str_id, user_texture_id, size, uv0, uv1, bg_col, tint_col); } + inline bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) { return imgui_function_table_instance()->BeginCombo(label, preview_value, flags); } + inline void EndCombo() { imgui_function_table_instance()->EndCombo(); } + inline bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items) { return imgui_function_table_instance()->Combo(label, current_item, items, items_count, popup_max_height_in_items); } + inline bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items) { return imgui_function_table_instance()->Combo2(label, current_item, items_separated_by_zeros, popup_max_height_in_items); } + inline bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items) { return imgui_function_table_instance()->Combo3(label, current_item, items_getter, data, items_count, popup_max_height_in_items); } + inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragFloat(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragFloat2(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragFloat3(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragFloat4(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragFloatRange2(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, flags); } + inline bool DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragInt(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragInt2(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragInt3(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragInt4(label, v, v_speed, v_min, v_max, format, flags); } + inline bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragIntRange2(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, flags); } + inline bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, flags); } + inline bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, flags); } + inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderFloat(label, v, v_min, v_max, format, flags); } + inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderFloat2(label, v, v_min, v_max, format, flags); } + inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderFloat3(label, v, v_min, v_max, format, flags); } + inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderFloat4(label, v, v_min, v_max, format, flags); } + inline bool SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderAngle(label, v_rad, v_degrees_min, v_degrees_max, format, flags); } + inline bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderInt(label, v, v_min, v_max, format, flags); } + inline bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderInt2(label, v, v_min, v_max, format, flags); } + inline bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderInt3(label, v, v_min, v_max, format, flags); } + inline bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderInt4(label, v, v_min, v_max, format, flags); } + inline bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderScalar(label, data_type, p_data, p_min, p_max, format, flags); } + inline bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->SliderScalarN(label, data_type, p_data, components, p_min, p_max, format, flags); } + inline bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->VSliderFloat(label, size, v, v_min, v_max, format, flags); } + inline bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->VSliderInt(label, size, v, v_min, v_max, format, flags); } + inline bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return imgui_function_table_instance()->VSliderScalar(label, size, data_type, p_data, p_min, p_max, format, flags); } + inline bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { return imgui_function_table_instance()->InputText(label, buf, buf_size, flags, callback, user_data); } + inline bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { return imgui_function_table_instance()->InputTextMultiline(label, buf, buf_size, size, flags, callback, user_data); } + inline bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { return imgui_function_table_instance()->InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data); } + inline bool InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputFloat(label, v, step, step_fast, format, flags); } + inline bool InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputFloat2(label, v, format, flags); } + inline bool InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputFloat3(label, v, format, flags); } + inline bool InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputFloat4(label, v, format, flags); } + inline bool InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputInt(label, v, step, step_fast, flags); } + inline bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputInt2(label, v, flags); } + inline bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputInt3(label, v, flags); } + inline bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputInt4(label, v, flags); } + inline bool InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputDouble(label, v, step, step_fast, format, flags); } + inline bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputScalar(label, data_type, p_data, p_step, p_step_fast, format, flags); } + inline bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) { return imgui_function_table_instance()->InputScalarN(label, data_type, p_data, components, p_step, p_step_fast, format, flags); } + inline bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) { return imgui_function_table_instance()->ColorEdit3(label, col, flags); } + inline bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) { return imgui_function_table_instance()->ColorEdit4(label, col, flags); } + inline bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) { return imgui_function_table_instance()->ColorPicker3(label, col, flags); } + inline bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { return imgui_function_table_instance()->ColorPicker4(label, col, flags, ref_col); } + inline bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size) { return imgui_function_table_instance()->ColorButton(desc_id, col, flags, size); } + inline void SetColorEditOptions(ImGuiColorEditFlags flags) { imgui_function_table_instance()->SetColorEditOptions(flags); } + inline bool TreeNode(const char* label) { return imgui_function_table_instance()->TreeNode(label); } + inline bool TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); return imgui_function_table_instance()->TreeNodeV(str_id, fmt, args); va_end(args); } + inline bool TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); return imgui_function_table_instance()->TreeNodeV2(ptr_id, fmt, args); va_end(args); } + inline bool TreeNodeV(const char* str_id, const char* fmt, va_list args) { return imgui_function_table_instance()->TreeNodeV(str_id, fmt, args); } + inline bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { return imgui_function_table_instance()->TreeNodeV2(ptr_id, fmt, args); } + inline bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { return imgui_function_table_instance()->TreeNodeEx(label, flags); } + inline bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); return imgui_function_table_instance()->TreeNodeExV(str_id, flags, fmt, args); va_end(args); } + inline bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); return imgui_function_table_instance()->TreeNodeExV2(ptr_id, flags, fmt, args); va_end(args); } + inline bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { return imgui_function_table_instance()->TreeNodeExV(str_id, flags, fmt, args); } + inline bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { return imgui_function_table_instance()->TreeNodeExV2(ptr_id, flags, fmt, args); } + inline void TreePush(const char* str_id) { imgui_function_table_instance()->TreePush(str_id); } + inline void TreePush(const void* ptr_id) { imgui_function_table_instance()->TreePush2(ptr_id); } + inline void TreePop() { imgui_function_table_instance()->TreePop(); } + inline float GetTreeNodeToLabelSpacing() { return imgui_function_table_instance()->GetTreeNodeToLabelSpacing(); } + inline bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { return imgui_function_table_instance()->CollapsingHeader(label, flags); } + inline bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags) { return imgui_function_table_instance()->CollapsingHeader2(label, p_visible, flags); } + inline void SetNextItemOpen(bool is_open, ImGuiCond cond) { imgui_function_table_instance()->SetNextItemOpen(is_open, cond); } + inline bool Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size) { return imgui_function_table_instance()->Selectable(label, selected, flags, size); } + inline bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size) { return imgui_function_table_instance()->Selectable2(label, p_selected, flags, size); } + inline bool BeginListBox(const char* label, const ImVec2& size) { return imgui_function_table_instance()->BeginListBox(label, size); } + inline void EndListBox() { imgui_function_table_instance()->EndListBox(); } + inline bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) { return imgui_function_table_instance()->ListBox(label, current_item, items, items_count, height_in_items); } + inline bool ListBox(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items) { return imgui_function_table_instance()->ListBox2(label, current_item, items_getter, data, items_count, height_in_items); } + inline void PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { imgui_function_table_instance()->PlotLines(label, values, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size, stride); } + inline void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { imgui_function_table_instance()->PlotLines2(label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } + inline void PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { imgui_function_table_instance()->PlotHistogram(label, values, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size, stride); } + inline void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { imgui_function_table_instance()->PlotHistogram2(label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } + inline void Value(const char* prefix, bool b) { imgui_function_table_instance()->Value(prefix, b); } + inline void Value(const char* prefix, int v) { imgui_function_table_instance()->Value2(prefix, v); } + inline void Value(const char* prefix, unsigned int v) { imgui_function_table_instance()->Value3(prefix, v); } + inline void Value(const char* prefix, float v, const char* float_format) { imgui_function_table_instance()->Value4(prefix, v, float_format); } + inline bool BeginMenuBar() { return imgui_function_table_instance()->BeginMenuBar(); } + inline void EndMenuBar() { imgui_function_table_instance()->EndMenuBar(); } + inline bool BeginMainMenuBar() { return imgui_function_table_instance()->BeginMainMenuBar(); } + inline void EndMainMenuBar() { imgui_function_table_instance()->EndMainMenuBar(); } + inline bool BeginMenu(const char* label, bool enabled) { return imgui_function_table_instance()->BeginMenu(label, enabled); } + inline void EndMenu() { imgui_function_table_instance()->EndMenu(); } + inline bool MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { return imgui_function_table_instance()->MenuItem(label, shortcut, selected, enabled); } + inline bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) { return imgui_function_table_instance()->MenuItem2(label, shortcut, p_selected, enabled); } + inline bool BeginTooltip() { return imgui_function_table_instance()->BeginTooltip(); } + inline void EndTooltip() { imgui_function_table_instance()->EndTooltip(); } + inline void SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->SetTooltipV(fmt, args); va_end(args); } + inline void SetTooltipV(const char* fmt, va_list args) { imgui_function_table_instance()->SetTooltipV(fmt, args); } + inline bool BeginItemTooltip() { return imgui_function_table_instance()->BeginItemTooltip(); } + inline void SetItemTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); imgui_function_table_instance()->SetItemTooltipV(fmt, args); va_end(args); } + inline void SetItemTooltipV(const char* fmt, va_list args) { imgui_function_table_instance()->SetItemTooltipV(fmt, args); } + inline bool BeginPopup(const char* str_id, ImGuiWindowFlags flags) { return imgui_function_table_instance()->BeginPopup(str_id, flags); } + inline bool BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { return imgui_function_table_instance()->BeginPopupModal(name, p_open, flags); } + inline void EndPopup() { imgui_function_table_instance()->EndPopup(); } + inline void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { imgui_function_table_instance()->OpenPopup(str_id, popup_flags); } + inline void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags) { imgui_function_table_instance()->OpenPopup2(id, popup_flags); } + inline void OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) { imgui_function_table_instance()->OpenPopupOnItemClick(str_id, popup_flags); } + inline void CloseCurrentPopup() { imgui_function_table_instance()->CloseCurrentPopup(); } + inline bool BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { return imgui_function_table_instance()->BeginPopupContextItem(str_id, popup_flags); } + inline bool BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) { return imgui_function_table_instance()->BeginPopupContextWindow(str_id, popup_flags); } + inline bool BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) { return imgui_function_table_instance()->BeginPopupContextVoid(str_id, popup_flags); } + inline bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags) { return imgui_function_table_instance()->IsPopupOpen(str_id, flags); } + inline bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) { return imgui_function_table_instance()->BeginTable(str_id, column, flags, outer_size, inner_width); } + inline void EndTable() { imgui_function_table_instance()->EndTable(); } + inline void TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) { imgui_function_table_instance()->TableNextRow(row_flags, min_row_height); } + inline bool TableNextColumn() { return imgui_function_table_instance()->TableNextColumn(); } + inline bool TableSetColumnIndex(int column_n) { return imgui_function_table_instance()->TableSetColumnIndex(column_n); } + inline void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id) { imgui_function_table_instance()->TableSetupColumn(label, flags, init_width_or_weight, user_id); } + inline void TableSetupScrollFreeze(int cols, int rows) { imgui_function_table_instance()->TableSetupScrollFreeze(cols, rows); } + inline void TableHeadersRow() { imgui_function_table_instance()->TableHeadersRow(); } + inline void TableHeader(const char* label) { imgui_function_table_instance()->TableHeader(label); } + inline ImGuiTableSortSpecs* TableGetSortSpecs() { return imgui_function_table_instance()->TableGetSortSpecs(); } + inline int TableGetColumnCount() { return imgui_function_table_instance()->TableGetColumnCount(); } + inline int TableGetColumnIndex() { return imgui_function_table_instance()->TableGetColumnIndex(); } + inline int TableGetRowIndex() { return imgui_function_table_instance()->TableGetRowIndex(); } + inline const char* TableGetColumnName(int column_n) { return imgui_function_table_instance()->TableGetColumnName(column_n); } + inline ImGuiTableColumnFlags TableGetColumnFlags(int column_n) { return imgui_function_table_instance()->TableGetColumnFlags(column_n); } + inline void TableSetColumnEnabled(int column_n, bool v) { imgui_function_table_instance()->TableSetColumnEnabled(column_n, v); } + inline void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n) { imgui_function_table_instance()->TableSetBgColor(target, color, column_n); } + inline void Columns(int count, const char* id, bool border) { imgui_function_table_instance()->Columns(count, id, border); } + inline void NextColumn() { imgui_function_table_instance()->NextColumn(); } + inline int GetColumnIndex() { return imgui_function_table_instance()->GetColumnIndex(); } + inline float GetColumnWidth(int column_index) { return imgui_function_table_instance()->GetColumnWidth(column_index); } + inline void SetColumnWidth(int column_index, float width) { imgui_function_table_instance()->SetColumnWidth(column_index, width); } + inline float GetColumnOffset(int column_index) { return imgui_function_table_instance()->GetColumnOffset(column_index); } + inline void SetColumnOffset(int column_index, float offset_x) { imgui_function_table_instance()->SetColumnOffset(column_index, offset_x); } + inline int GetColumnsCount() { return imgui_function_table_instance()->GetColumnsCount(); } + inline bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { return imgui_function_table_instance()->BeginTabBar(str_id, flags); } + inline void EndTabBar() { imgui_function_table_instance()->EndTabBar(); } + inline bool BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) { return imgui_function_table_instance()->BeginTabItem(label, p_open, flags); } + inline void EndTabItem() { imgui_function_table_instance()->EndTabItem(); } + inline bool TabItemButton(const char* label, ImGuiTabItemFlags flags) { return imgui_function_table_instance()->TabItemButton(label, flags); } + inline void SetTabItemClosed(const char* tab_or_docked_window_label) { imgui_function_table_instance()->SetTabItemClosed(tab_or_docked_window_label); } + inline ImGuiID DockSpace(ImGuiID id, const ImVec2& size, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class) { return imgui_function_table_instance()->DockSpace(id, size, flags, window_class); } + inline void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond) { imgui_function_table_instance()->SetNextWindowDockID(dock_id, cond); } + inline void SetNextWindowClass(const ImGuiWindowClass* window_class) { imgui_function_table_instance()->SetNextWindowClass(window_class); } + inline ImGuiID GetWindowDockID() { return imgui_function_table_instance()->GetWindowDockID(); } + inline bool IsWindowDocked() { return imgui_function_table_instance()->IsWindowDocked(); } + inline bool BeginDragDropSource(ImGuiDragDropFlags flags) { return imgui_function_table_instance()->BeginDragDropSource(flags); } + inline bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond) { return imgui_function_table_instance()->SetDragDropPayload(type, data, sz, cond); } + inline void EndDragDropSource() { imgui_function_table_instance()->EndDragDropSource(); } + inline bool BeginDragDropTarget() { return imgui_function_table_instance()->BeginDragDropTarget(); } + inline const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) { return imgui_function_table_instance()->AcceptDragDropPayload(type, flags); } + inline void EndDragDropTarget() { imgui_function_table_instance()->EndDragDropTarget(); } + inline const ImGuiPayload* GetDragDropPayload() { return imgui_function_table_instance()->GetDragDropPayload(); } + inline void BeginDisabled(bool disabled) { imgui_function_table_instance()->BeginDisabled(disabled); } + inline void EndDisabled() { imgui_function_table_instance()->EndDisabled(); } + inline void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { imgui_function_table_instance()->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); } + inline void PopClipRect() { imgui_function_table_instance()->PopClipRect(); } + inline void SetItemDefaultFocus() { imgui_function_table_instance()->SetItemDefaultFocus(); } + inline void SetKeyboardFocusHere(int offset) { imgui_function_table_instance()->SetKeyboardFocusHere(offset); } + inline void SetNextItemAllowOverlap() { imgui_function_table_instance()->SetNextItemAllowOverlap(); } + inline bool IsItemHovered(ImGuiHoveredFlags flags) { return imgui_function_table_instance()->IsItemHovered(flags); } + inline bool IsItemActive() { return imgui_function_table_instance()->IsItemActive(); } + inline bool IsItemFocused() { return imgui_function_table_instance()->IsItemFocused(); } + inline bool IsItemClicked(ImGuiMouseButton mouse_button) { return imgui_function_table_instance()->IsItemClicked(mouse_button); } + inline bool IsItemVisible() { return imgui_function_table_instance()->IsItemVisible(); } + inline bool IsItemEdited() { return imgui_function_table_instance()->IsItemEdited(); } + inline bool IsItemActivated() { return imgui_function_table_instance()->IsItemActivated(); } + inline bool IsItemDeactivated() { return imgui_function_table_instance()->IsItemDeactivated(); } + inline bool IsItemDeactivatedAfterEdit() { return imgui_function_table_instance()->IsItemDeactivatedAfterEdit(); } + inline bool IsItemToggledOpen() { return imgui_function_table_instance()->IsItemToggledOpen(); } + inline bool IsAnyItemHovered() { return imgui_function_table_instance()->IsAnyItemHovered(); } + inline bool IsAnyItemActive() { return imgui_function_table_instance()->IsAnyItemActive(); } + inline bool IsAnyItemFocused() { return imgui_function_table_instance()->IsAnyItemFocused(); } + inline ImGuiID GetItemID() { return imgui_function_table_instance()->GetItemID(); } + inline ImVec2 GetItemRectMin() { return imgui_function_table_instance()->GetItemRectMin(); } + inline ImVec2 GetItemRectMax() { return imgui_function_table_instance()->GetItemRectMax(); } + inline ImVec2 GetItemRectSize() { return imgui_function_table_instance()->GetItemRectSize(); } + inline ImDrawList* GetBackgroundDrawList() { return imgui_function_table_instance()->GetBackgroundDrawList(); } + inline ImDrawList* GetForegroundDrawList() { return imgui_function_table_instance()->GetForegroundDrawList(); } + inline ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport) { return imgui_function_table_instance()->GetBackgroundDrawList2(viewport); } + inline ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport) { return imgui_function_table_instance()->GetForegroundDrawList2(viewport); } + inline bool IsRectVisible(const ImVec2& size) { return imgui_function_table_instance()->IsRectVisible(size); } + inline bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { return imgui_function_table_instance()->IsRectVisible2(rect_min, rect_max); } + inline double GetTime() { return imgui_function_table_instance()->GetTime(); } + inline int GetFrameCount() { return imgui_function_table_instance()->GetFrameCount(); } + inline ImDrawListSharedData* GetDrawListSharedData() { return imgui_function_table_instance()->GetDrawListSharedData(); } + inline const char* GetStyleColorName(ImGuiCol idx) { return imgui_function_table_instance()->GetStyleColorName(idx); } + inline void SetStateStorage(ImGuiStorage* storage) { imgui_function_table_instance()->SetStateStorage(storage); } + inline ImGuiStorage* GetStateStorage() { return imgui_function_table_instance()->GetStateStorage(); } + inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags) { return imgui_function_table_instance()->BeginChildFrame(id, size, flags); } + inline void EndChildFrame() { imgui_function_table_instance()->EndChildFrame(); } + inline ImVec2 CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { return imgui_function_table_instance()->CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width); } + inline ImVec4 ColorConvertU32ToFloat4(ImU32 in) { return imgui_function_table_instance()->ColorConvertU32ToFloat4(in); } + inline ImU32 ColorConvertFloat4ToU32(const ImVec4& in) { return imgui_function_table_instance()->ColorConvertFloat4ToU32(in); } + inline void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { imgui_function_table_instance()->ColorConvertRGBtoHSV(r, g, b, out_h, out_s, out_v); } + inline void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { imgui_function_table_instance()->ColorConvertHSVtoRGB(h, s, v, out_r, out_g, out_b); } + inline bool IsKeyDown(ImGuiKey key) { return imgui_function_table_instance()->IsKeyDown(key); } + inline bool IsKeyPressed(ImGuiKey key, bool repeat) { return imgui_function_table_instance()->IsKeyPressed(key, repeat); } + inline bool IsKeyReleased(ImGuiKey key) { return imgui_function_table_instance()->IsKeyReleased(key); } + inline int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate) { return imgui_function_table_instance()->GetKeyPressedAmount(key, repeat_delay, rate); } + inline const char* GetKeyName(ImGuiKey key) { return imgui_function_table_instance()->GetKeyName(key); } + inline void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard) { imgui_function_table_instance()->SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } + inline bool IsMouseDown(ImGuiMouseButton button) { return imgui_function_table_instance()->IsMouseDown(button); } + inline bool IsMouseClicked(ImGuiMouseButton button, bool repeat) { return imgui_function_table_instance()->IsMouseClicked(button, repeat); } + inline bool IsMouseReleased(ImGuiMouseButton button) { return imgui_function_table_instance()->IsMouseReleased(button); } + inline bool IsMouseDoubleClicked(ImGuiMouseButton button) { return imgui_function_table_instance()->IsMouseDoubleClicked(button); } + inline int GetMouseClickedCount(ImGuiMouseButton button) { return imgui_function_table_instance()->GetMouseClickedCount(button); } + inline bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { return imgui_function_table_instance()->IsMouseHoveringRect(r_min, r_max, clip); } + inline bool IsMousePosValid(const ImVec2* mouse_pos) { return imgui_function_table_instance()->IsMousePosValid(mouse_pos); } + inline bool IsAnyMouseDown() { return imgui_function_table_instance()->IsAnyMouseDown(); } + inline ImVec2 GetMousePos() { return imgui_function_table_instance()->GetMousePos(); } + inline ImVec2 GetMousePosOnOpeningCurrentPopup() { return imgui_function_table_instance()->GetMousePosOnOpeningCurrentPopup(); } + inline bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold) { return imgui_function_table_instance()->IsMouseDragging(button, lock_threshold); } + inline ImVec2 GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) { return imgui_function_table_instance()->GetMouseDragDelta(button, lock_threshold); } + inline void ResetMouseDragDelta(ImGuiMouseButton button) { imgui_function_table_instance()->ResetMouseDragDelta(button); } + inline ImGuiMouseCursor GetMouseCursor() { return imgui_function_table_instance()->GetMouseCursor(); } + inline void SetMouseCursor(ImGuiMouseCursor cursor_type) { imgui_function_table_instance()->SetMouseCursor(cursor_type); } + inline void SetNextFrameWantCaptureMouse(bool want_capture_mouse) { imgui_function_table_instance()->SetNextFrameWantCaptureMouse(want_capture_mouse); } + inline const char* GetClipboardText() { return imgui_function_table_instance()->GetClipboardText(); } + inline void SetClipboardText(const char* text) { imgui_function_table_instance()->SetClipboardText(text); } + inline void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data) { imgui_function_table_instance()->SetAllocatorFunctions(alloc_func, free_func, user_data); } + inline void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data) { imgui_function_table_instance()->GetAllocatorFunctions(p_alloc_func, p_free_func, p_user_data); } + inline void* MemAlloc(size_t size) { return imgui_function_table_instance()->MemAlloc(size); } + inline void MemFree(void* ptr) { imgui_function_table_instance()->MemFree(ptr); } + +} + +inline int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { return imgui_function_table_instance()->ImGuiStorage_GetInt(this, key, default_val); } +inline void ImGuiStorage::SetInt(ImGuiID key, int val) { imgui_function_table_instance()->ImGuiStorage_SetInt(this, key, val); } +inline bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return imgui_function_table_instance()->ImGuiStorage_GetBool(this, key, default_val); } +inline void ImGuiStorage::SetBool(ImGuiID key, bool val) { imgui_function_table_instance()->ImGuiStorage_SetBool(this, key, val); } +inline float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { return imgui_function_table_instance()->ImGuiStorage_GetFloat(this, key, default_val); } +inline void ImGuiStorage::SetFloat(ImGuiID key, float val) { imgui_function_table_instance()->ImGuiStorage_SetFloat(this, key, val); } +inline void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { return imgui_function_table_instance()->ImGuiStorage_GetVoidPtr(this, key); } +inline void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { imgui_function_table_instance()->ImGuiStorage_SetVoidPtr(this, key, val); } +inline int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { return imgui_function_table_instance()->ImGuiStorage_GetIntRef(this, key, default_val); } +inline bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return imgui_function_table_instance()->ImGuiStorage_GetBoolRef(this, key, default_val); } +inline float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { return imgui_function_table_instance()->ImGuiStorage_GetFloatRef(this, key, default_val); } +inline void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { return imgui_function_table_instance()->ImGuiStorage_GetVoidPtrRef(this, key, default_val); } +inline void ImGuiStorage::SetAllInt(int val) { imgui_function_table_instance()->ImGuiStorage_SetAllInt(this, val); } +inline void ImGuiStorage::BuildSortByKey() { imgui_function_table_instance()->ImGuiStorage_BuildSortByKey(this); } +inline ImGuiListClipper::ImGuiListClipper() { imgui_function_table_instance()->ConstructImGuiListClipper(this); } +inline ImGuiListClipper::~ImGuiListClipper() { imgui_function_table_instance()->DestructImGuiListClipper(this); } +inline void ImGuiListClipper::Begin(int items_count, float items_height) { imgui_function_table_instance()->ImGuiListClipper_Begin(this, items_count, items_height); } +inline void ImGuiListClipper::End() { imgui_function_table_instance()->ImGuiListClipper_End(this); } +inline bool ImGuiListClipper::Step() { return imgui_function_table_instance()->ImGuiListClipper_Step(this); } +inline void ImGuiListClipper::IncludeRangeByIndices(int item_begin, int item_end) { imgui_function_table_instance()->ImGuiListClipper_IncludeRangeByIndices(this, item_begin, item_end); } +inline void ImDrawList::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { imgui_function_table_instance()->ImDrawList_PushClipRect(this, clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); } +inline void ImDrawList::PushClipRectFullScreen() { imgui_function_table_instance()->ImDrawList_PushClipRectFullScreen(this); } +inline void ImDrawList::PopClipRect() { imgui_function_table_instance()->ImDrawList_PopClipRect(this); } +inline void ImDrawList::PushTextureID(ImTextureID texture_id) { imgui_function_table_instance()->ImDrawList_PushTextureID(this, texture_id); } +inline void ImDrawList::PopTextureID() { imgui_function_table_instance()->ImDrawList_PopTextureID(this); } +inline void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) { imgui_function_table_instance()->ImDrawList_AddLine(this, p1, p2, col, thickness); } +inline void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness) { imgui_function_table_instance()->ImDrawList_AddRect(this, p_min, p_max, col, rounding, flags, thickness); } +inline void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags) { imgui_function_table_instance()->ImDrawList_AddRectFilled(this, p_min, p_max, col, rounding, flags); } +inline void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) { imgui_function_table_instance()->ImDrawList_AddRectFilledMultiColor(this, p_min, p_max, col_upr_left, col_upr_right, col_bot_right, col_bot_left); } +inline void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness) { imgui_function_table_instance()->ImDrawList_AddQuad(this, p1, p2, p3, p4, col, thickness); } +inline void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) { imgui_function_table_instance()->ImDrawList_AddQuadFilled(this, p1, p2, p3, p4, col); } +inline void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness) { imgui_function_table_instance()->ImDrawList_AddTriangle(this, p1, p2, p3, col, thickness); } +inline void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) { imgui_function_table_instance()->ImDrawList_AddTriangleFilled(this, p1, p2, p3, col); } +inline void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) { imgui_function_table_instance()->ImDrawList_AddCircle(this, center, radius, col, num_segments, thickness); } +inline void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) { imgui_function_table_instance()->ImDrawList_AddCircleFilled(this, center, radius, col, num_segments); } +inline void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) { imgui_function_table_instance()->ImDrawList_AddNgon(this, center, radius, col, num_segments, thickness); } +inline void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) { imgui_function_table_instance()->ImDrawList_AddNgonFilled(this, center, radius, col, num_segments); } +inline void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) { imgui_function_table_instance()->ImDrawList_AddText(this, pos, col, text_begin, text_end); } +inline void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) { imgui_function_table_instance()->ImDrawList_AddText2(this, font, font_size, pos, col, text_begin, text_end, wrap_width, cpu_fine_clip_rect); } +inline void ImDrawList::AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness) { imgui_function_table_instance()->ImDrawList_AddPolyline(this, points, num_points, col, flags, thickness); } +inline void ImDrawList::AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col) { imgui_function_table_instance()->ImDrawList_AddConvexPolyFilled(this, points, num_points, col); } +inline void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments) { imgui_function_table_instance()->ImDrawList_AddBezierCubic(this, p1, p2, p3, p4, col, thickness, num_segments); } +inline void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments) { imgui_function_table_instance()->ImDrawList_AddBezierQuadratic(this, p1, p2, p3, col, thickness, num_segments); } +inline void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) { imgui_function_table_instance()->ImDrawList_AddImage(this, user_texture_id, p_min, p_max, uv_min, uv_max, col); } +inline void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) { imgui_function_table_instance()->ImDrawList_AddImageQuad(this, user_texture_id, p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); } +inline void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) { imgui_function_table_instance()->ImDrawList_AddImageRounded(this, user_texture_id, p_min, p_max, uv_min, uv_max, col, rounding, flags); } +inline void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { imgui_function_table_instance()->ImDrawList_PathArcTo(this, center, radius, a_min, a_max, num_segments); } +inline void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12) { imgui_function_table_instance()->ImDrawList_PathArcToFast(this, center, radius, a_min_of_12, a_max_of_12); } +inline void ImDrawList::PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) { imgui_function_table_instance()->ImDrawList_PathBezierCubicCurveTo(this, p2, p3, p4, num_segments); } +inline void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments) { imgui_function_table_instance()->ImDrawList_PathBezierQuadraticCurveTo(this, p2, p3, num_segments); } +inline void ImDrawList::PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding, ImDrawFlags flags) { imgui_function_table_instance()->ImDrawList_PathRect(this, rect_min, rect_max, rounding, flags); } +inline void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { imgui_function_table_instance()->ImDrawList_AddCallback(this, callback, callback_data); } +inline void ImDrawList::AddDrawCmd() { imgui_function_table_instance()->ImDrawList_AddDrawCmd(this); } +inline ImDrawList* ImDrawList::CloneOutput() const { return imgui_function_table_instance()->ImDrawList_CloneOutput(this); } +inline void ImDrawList::PrimReserve(int idx_count, int vtx_count) { imgui_function_table_instance()->ImDrawList_PrimReserve(this, idx_count, vtx_count); } +inline void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) { imgui_function_table_instance()->ImDrawList_PrimUnreserve(this, idx_count, vtx_count); } +inline void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col) { imgui_function_table_instance()->ImDrawList_PrimRect(this, a, b, col); } +inline void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) { imgui_function_table_instance()->ImDrawList_PrimRectUV(this, a, b, uv_a, uv_b, col); } +inline void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) { imgui_function_table_instance()->ImDrawList_PrimQuadUV(this, a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); } +inline ImFont::ImFont() { imgui_function_table_instance()->ConstructImFont(this); } +inline ImFont::~ImFont() { imgui_function_table_instance()->DestructImFont(this); } +inline const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const { return imgui_function_table_instance()->ImFont_FindGlyph(this, c); } +inline const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const { return imgui_function_table_instance()->ImFont_FindGlyphNoFallback(this, c); } +inline ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const { return imgui_function_table_instance()->ImFont_CalcTextSizeA(this, size, max_width, wrap_width, text_begin, text_end, remaining); } +inline const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const { return imgui_function_table_instance()->ImFont_CalcWordWrapPositionA(this, scale, text, text_end, wrap_width); } +inline void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const { imgui_function_table_instance()->ImFont_RenderChar(this, draw_list, size, pos, col, c); } +inline void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const { imgui_function_table_instance()->ImFont_RenderText(this, draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); } + + +#endif + +#endif diff --git a/Plugin/src/Hooks.cpp b/Plugin/src/Hooks.cpp new file mode 100644 index 00000000..8e868bf3 --- /dev/null +++ b/Plugin/src/Hooks.cpp @@ -0,0 +1,620 @@ +#include "Hooks.h" +#include "Offsets.h" +#include "Utils.h" +#include "reshade/reshade.hpp" + +namespace Hooks +{ + RE::BufferDefinition* Patches::GetBufferFromString(std::string_view a_bufferName) + { + const auto& bufferArray = *Offsets::bufferArray; + for (const auto& bufferDefinition : bufferArray) { + if (bufferDefinition->bufferName == a_bufferName) { + return bufferDefinition; + } + } + + return nullptr; + } + + void Hooks::ToggleEnableHDRSubSettings(RE::SettingsDataModel* a_model, bool a_bDisplayModeHDREnable, bool a_bGameRenderingHDREnable, bool a_bSDRForcedOnHDR) + { + if (const auto peakBrightnessSetting = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_PeakBrightness))) { + peakBrightnessSetting->m_Enabled.SetValue(a_bGameRenderingHDREnable); + } + + if (const auto gamePaperWhiteSetting = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_GamePaperWhite))) { + gamePaperWhiteSetting->m_Enabled.SetValue(a_bDisplayModeHDREnable || a_bSDRForcedOnHDR); + } + + if (const auto uiPaperWhiteSetting = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_UIPaperWhite))) { + uiPaperWhiteSetting->m_Enabled.SetValue(a_bGameRenderingHDREnable); + } + + if (const auto extendGamut = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_ExtendGamut))) { + extendGamut->m_Enabled.SetValue(a_bGameRenderingHDREnable); + } + + if (const auto saturation = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_Saturation))) { + saturation->m_Enabled.SetValue(a_bGameRenderingHDREnable); + } + + if (const auto contrast = a_model->FindSettingById(static_cast(Settings::SettingID::kHDR_Contrast))) { + contrast->m_Enabled.SetValue(a_bGameRenderingHDREnable); + } + + if (const auto secondaryBrightnessSetting = a_model->FindSettingById(static_cast(Settings::SettingID::kSecondaryBrightness))) { + secondaryBrightnessSetting->m_Enabled.SetValue(!a_bGameRenderingHDREnable); + } + } + + void Hooks::CreateCheckboxSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Checkbox& a_setting, bool a_bEnabled) + { + auto& s = *(new (alloca(sizeof(RE::SubSettingsList::GeneralSetting))) RE::SubSettingsList::GeneralSetting()); + + s.m_Text.SetStringValue(a_setting.name.c_str()); + s.m_Description.SetStringValue(a_setting.description.c_str()); + s.m_ID.SetValue(static_cast(a_setting.id)); + s.m_Type.SetValue(RE::SubSettingsList::GeneralSetting::Type::Checkbox); + s.m_Category.SetValue(RE::SubSettingsList::GeneralSetting::Category::Display); + s.m_Enabled.SetValue(a_bEnabled); + s.m_CheckBoxData.m_ShuttleMap.GetData().m_Value.SetValue(a_setting.value.get_data()); + a_settingList->AddItem(s); + } + + void Hooks::CreateStepperSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Stepper& a_setting, bool a_bEnabled) + { + auto& s = *(new (alloca(sizeof(RE::SubSettingsList::GeneralSetting))) RE::SubSettingsList::GeneralSetting()); + + s.m_Text.SetStringValue(a_setting.name.c_str()); + s.m_Description.SetStringValue(a_setting.description.c_str()); + s.m_ID.SetValue(static_cast(a_setting.id)); + s.m_Type.SetValue(RE::SubSettingsList::GeneralSetting::Type::Stepper); + s.m_Category.SetValue(RE::SubSettingsList::GeneralSetting::Category::Display); + s.m_Enabled.SetValue(a_bEnabled); + for (auto i = 0; i < a_setting.GetNumOptions(); ++i) { + s.m_StepperData.m_ShuttleMap.GetData().m_DisplayValues.AddItem(a_setting.GetStepperText(i).c_str()); + } + s.m_StepperData.m_ShuttleMap.GetData().m_Value.SetValue(a_setting.GetCurrentStepFromValue()); + a_settingList->AddItem(s); + } + + void Hooks::CreateSliderSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Slider& a_setting, bool a_bEnabled) + { + auto& s = *(new (alloca(sizeof(RE::SubSettingsList::GeneralSetting))) RE::SubSettingsList::GeneralSetting()); + + s.m_Text.SetStringValue(a_setting.name.c_str()); + s.m_Description.SetStringValue(a_setting.description.c_str()); + s.m_ID.SetValue(static_cast(a_setting.id)); + s.m_Type.SetValue(RE::SubSettingsList::GeneralSetting::Type::Slider); + s.m_Category.SetValue(RE::SubSettingsList::GeneralSetting::Category::Display); + s.m_Enabled.SetValue(a_bEnabled); + s.m_SliderData.m_ShuttleMap.GetData().m_Value.SetValue(a_setting.GetSliderPercentage()); + s.m_SliderData.m_ShuttleMap.GetData().m_DisplayValue.SetStringValue(a_setting.GetSliderText().c_str()); + a_settingList->AddItem(s); + } + + void Hooks::CreateSeparator(RE::ArrayNestedUIValue* a_settingList, Settings::SettingID a_id) + { + auto& s = *(new (alloca(sizeof(RE::SubSettingsList::GeneralSetting))) RE::SubSettingsList::GeneralSetting()); + + s.m_Text.SetStringValue(""); + s.m_Description.SetStringValue(""); + s.m_ID.SetValue(static_cast(a_id)); + s.m_Type.SetValue(RE::SubSettingsList::GeneralSetting::Type::LargeStepper); + s.m_Category.SetValue(RE::SubSettingsList::GeneralSetting::Category::Display); + s.m_Enabled.SetValue(false); + a_settingList->AddItem(s); + } + + void Hooks::CreateSettings(RE::ArrayNestedUIValue* a_settingList) + { + const auto settings = Settings::Main::GetSingleton(); + + CreateSeparator(a_settingList, Settings::SettingID::kSTART); + + // We don't expose "DevSetting*" or "ForceSDROnHDR" to the game settings, they'd just confuse users + CreateStepperSetting(a_settingList, settings->DisplayMode, settings->IsHDRSupported() && !settings->IsSDRForcedOnHDR()); + CreateStepperSetting(a_settingList, settings->PeakBrightness, settings->IsGameRenderingSetToHDR()); + CreateStepperSetting(a_settingList, settings->GamePaperWhite, settings->IsDisplayModeSetToHDR() || settings->IsSDRForcedOnHDR()); + CreateStepperSetting(a_settingList, settings->UIPaperWhite, settings->IsGameRenderingSetToHDR()); + CreateSliderSetting(a_settingList, settings->ExtendGamut, settings->IsGameRenderingSetToHDR()); + CreateSliderSetting(a_settingList, settings->Saturation, settings->IsGameRenderingSetToHDR()); + CreateSliderSetting(a_settingList, settings->Contrast, settings->IsGameRenderingSetToHDR()); + CreateSliderSetting(a_settingList, settings->SecondaryBrightness, !settings->IsGameRenderingSetToHDR()); + CreateSliderSetting(a_settingList, settings->LUTCorrectionStrength, true); + CreateSliderSetting(a_settingList, settings->ColorGradingStrength, true); + CreateSliderSetting(a_settingList, settings->GammaCorrectionStrength, true); + CreateCheckboxSetting(a_settingList, settings->VanillaMenuLUTs, true); + CreateStepperSetting(a_settingList, settings->FilmGrainType, true); + CreateSliderSetting(a_settingList, settings->FilmGrainCap, settings->IsFilmGrainTypeImproved()); + CreateCheckboxSetting(a_settingList, settings->PostSharpen, true); + + CreateSeparator(a_settingList, Settings::SettingID::kEND); + } + + struct DescriptorAllocation + { + enum class Type : uint8_t + { + Sampler = 0, + CbvSrvUav = 1, + }; + + D3D12_CPU_DESCRIPTOR_HANDLE CpuHandleBase; + D3D12_GPU_DESCRIPTOR_HANDLE GpuHandleBase; + }; + + struct Dx12Resource // Setup at 00000001432E692F + { + char _pad0[0x78]; // 0 + int m_DescriptorArrayCount; // 78 Greater than 0 (msb bit) indicates array + union + { + D3D12_CPU_DESCRIPTOR_HANDLE m_CpuDescriptor; // 80 Possibly mip levels? No idea w.r.t. its purpose + D3D12_CPU_DESCRIPTOR_HANDLE* m_CpuDescriptorArray; // 80 + }; + D3D12_CPU_DESCRIPTOR_HANDLE m_CBVCpuDescriptor; // 88 Each handle is unioned with an array like above? + D3D12_CPU_DESCRIPTOR_HANDLE m_SRVCpuDescriptor; // 90 + D3D12_CPU_DESCRIPTOR_HANDLE m_UAVCpuDescriptor; // 98 + D3D12_CPU_DESCRIPTOR_HANDLE m_UnknownSecondaryUAVCpuDescriptor; // A0 Probably raytracing related + ID3D12Resource* m_Resource; // A8 + uint32_t m_TransitionState; // B0 Flags converted to D3D12_RESOURCE_STATES enum + }; + static_assert(offsetof(Dx12Resource, m_DescriptorArrayCount) == 0x78); + static_assert(offsetof(Dx12Resource, m_CBVCpuDescriptor) == 0x88); + static_assert(offsetof(Dx12Resource, m_Resource) == 0xA8); + + thread_local Dx12Resource *ScaleformCompositeRenderTarget; + + void Hooks::HookedScaleformCompositeSetRenderTarget(void* a1, void* a2, void** a_rtArray, void* a4, void* a5, void* a6, void* a7, void* a8, void* a9) + { + ScaleformCompositeRenderTarget = *reinterpret_cast(reinterpret_cast(a_rtArray[0]) + 0x48); + + // Ignore render target sets. They're going to be overwritten anyway. + //_ScaleformCompositeSetRenderTarget(a1, a2, a_rtArray, a4, a5, a6, a7, a8, a9); + } + + void Hooks::HookedScaleformCompositeDraw(void* a_arg1, void* a_arg2, uint32_t a_vertexCount) + { + auto creationRendererInstance = *reinterpret_cast(reinterpret_cast(a_arg1) + 0x0); + auto device = *reinterpret_cast(creationRendererInstance + 0x3A0); + + auto commandList = *reinterpret_cast(reinterpret_cast(a_arg1) + 0x10); + + auto unknown1 = *reinterpret_cast(reinterpret_cast(a_arg1) + 0x8); + auto descriptorManager = *reinterpret_cast(unknown1 + 0x18); + + auto getBoundShaderResource = [&](uint32_t a_index) { + const auto v1 = *reinterpret_cast(reinterpret_cast(a_arg2) + 0x30); + const auto v2 = *reinterpret_cast(v1 + 0x10) + 24 * *(uint32_t*)(*(uintptr_t*)v1 + (4 * a_index) + 0x20); + return *reinterpret_cast(v2 + 0x8); + }; + + using AllocateDescriptors_t = void (*)(void*, DescriptorAllocation&, uint32_t, DescriptorAllocation::Type, uint32_t&); + auto allocateDescriptors = reinterpret_cast(dku::Hook::IDToAbs(207691)); + + if (Hook_ApplyRenderPassRenderState1(a_arg1, a_arg2)) { + // Remove all render targets; we're treating this pixel shader as a compute shader. All RT writes end + // up discarded. + // + // The ScaleformComposite pass contains exactly one draw so we can safely unbind them without informing + // the game. Game code also happens to unbind RTs immediately after the hook. + commandList->OMSetRenderTargets(0, nullptr, false, nullptr); + + // Instead of creating copies and worrying about resource allocations, bind the original RT and SRV as + // UAVs that can be modified in-place. + DescriptorAllocation alloc; + uint32_t handleSizeIncrement; + allocateDescriptors(descriptorManager, alloc, 2, DescriptorAllocation::Type::CbvSrvUav, handleSizeIncrement); + + alloc.CpuHandleBase.ptr += (0 * handleSizeIncrement); + device->CopyDescriptorsSimple(1, alloc.CpuHandleBase, getBoundShaderResource(0)->m_CpuDescriptor, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + alloc.CpuHandleBase.ptr += (1 * handleSizeIncrement); + device->CopyDescriptorsSimple(1, alloc.CpuHandleBase, ScaleformCompositeRenderTarget->m_UAVCpuDescriptor, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = ScaleformCompositeRenderTarget->m_Resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + + commandList->ResourceBarrier(1, &barrier); + commandList->SetGraphicsRootDescriptorTable(1, alloc.GpuHandleBase); // Hardcoded in ScaleformComposite\RootSignature.hlsl + commandList->DrawInstanced(a_vertexCount, 1, 0, 0); + std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter); + commandList->ResourceBarrier(1, &barrier); + } + } + + void Hooks::UploadRootConstants(void* a1, void* a2) + { + const auto technique = *reinterpret_cast(reinterpret_cast(a2) + 0x8); + const auto techniqueId = *reinterpret_cast(technique + 0x78); + + auto uploadRootConstants = [&](const Settings::ShaderConstants& a_shaderConstants, uint32_t a_rootParameterIndex, bool a_bCompute) { + auto commandList = *reinterpret_cast(reinterpret_cast(a1) + 0x10); + + if (!a_bCompute) + commandList->SetGraphicsRoot32BitConstants(a_rootParameterIndex, Settings::shaderConstantsSize, &a_shaderConstants, 0); + else + commandList->SetComputeRoot32BitConstants(a_rootParameterIndex, Settings::shaderConstantsSize, &a_shaderConstants, 0); + }; + + // Note: The following switch statement may be called several thousand times per frame. Additionally, it'll be called from multiple + // threads concurrently. The individual cases are called at most once or twice per frame. Keep the amount of code here fairly light. + // + // RootParameterIndex is the index of our custom RootConstants() entry in the root signature. It's taken from the corresponding + // RootSignature.hlsl file stored next to each technique hlsl file. + switch (techniqueId) { + case 0xFF1A: + case 0x600FF1A: + case 0x700FF1A: + case 0x800FF1A: + case 0xE00FF1A: + case 0xF00FF1A: + { + Settings::ShaderConstants shaderConstants; + const auto settings = Settings::Main::GetSingleton(); + settings->GetShaderConstants(shaderConstants); + if (*settings->VanillaMenuLUTs.value && !Utils::ShouldCorrectLUTs()) { + shaderConstants.ColorGradingStrength = 1.f; + } + uploadRootConstants(shaderConstants, 14, false); // HDRComposite + break; + } + + case 0x400FF59: + case 0x2000FF59: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 2, false); // Copy + break; + } + + case 0xFF75: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 2, false); // FilmGrain + break; + } + + case 0xFF81: + { + Settings::ShaderConstants shaderConstants; + const auto settings = Settings::Main::GetSingleton(); + settings->GetShaderConstants(shaderConstants); + if (*settings->VanillaMenuLUTs.value && !Utils::ShouldCorrectLUTs()) { + shaderConstants.LUTCorrectionStrength = 0.f; + shaderConstants.ColorGradingStrength = 1.f; + } + uploadRootConstants(shaderConstants, 7, true); // ColorGradingMerge + break; + } + + //case 0xFF94: + case 0x100FF94: + case 0x300FF94: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 14, true); // ContrastAdaptiveSharpening + break; + } + + case 0xFF9A: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 14, false); // PostSharpen + break; + } + + case 0xFFAA: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 2, false); // ScaleformComposite + break; + } + + case 0xFFAB: + { + Settings::ShaderConstants shaderConstants; + Settings::Main::GetSingleton()->GetShaderConstants(shaderConstants); + uploadRootConstants(shaderConstants, 1, false); // BinkMovie + break; + } + } + } + + void Hooks::Hook_UnkFunc(uintptr_t a1, RE::BGSSwapChainObject* a_bgsSwapchainObject) + { + const auto settings = Settings::Main::GetSingleton(); + settings->InitCompatibility(a_bgsSwapchainObject); + + a_bgsSwapchainObject->swapChainInterface->SetColorSpace1(settings->GetDisplayModeColorSpaceType()); + + settings->RegisterReshadeOverlay(); + + return _UnkFunc(a1, a_bgsSwapchainObject); + } + + bool Hooks::Hook_TakeSnapshot(uintptr_t a1) + { + const auto settings = Settings::Main::GetSingleton(); + //if (settings->IsDisplayModeSetToHDR()) { + if (true) { // actually it's always going to be the case because we're always going to update the image space buffer format + auto hack = alloca(sizeof(RE::MessageBoxData)); + auto& message = *(new (hack) RE::MessageBoxData("Photo Mode", "Taking screenshots with Photo Mode is not supported with Starfield Luma. Use an external tool (e.g. Xbox Game Bar) to take a screenshot.", nullptr, 0)); + Offsets::ShowMessageBox(*Offsets::MessageMenuManagerPtr, message, false); + + // hack to refresh the UI visibility after the snapshot + Offsets::PhotoMode_ToggleUI(a1 + 0x8); + Offsets::PhotoMode_ToggleUI(a1 + 0x8); + + return true; + } + + return _TakeSnapshot(a1); + } + + void Hooks::Hook_RecreateSwapchain(void* a1, RE::BGSSwapChainObject* a_bgsSwapChainObject, uint32_t a_width, uint32_t a_height, uint8_t a5) + { + _RecreateSwapchain(a1, a_bgsSwapChainObject, a_width, a_height, a5); + + const auto settings = Settings::Main::GetSingleton(); + a_bgsSwapChainObject->swapChainInterface->SetColorSpace1(settings->GetDisplayModeColorSpaceType()); + } + + void Hooks::Hook_CreateMonitorSetting(void* a1, void* a2) + { + _CreateMonitorSetting(a1, a2); + + // insert our settings after + auto* settingList = reinterpret_cast*>(reinterpret_cast(a1) - 0x28); + CreateSettings(settingList); + } + + void Hooks::Hook_SettingsDataModelCheckboxChanged(void* a_arg1, RE::SettingsDataModel::UpdateEventData& a_eventData) + { + const auto settings = Settings::Main::GetSingleton(); + + auto HandleSetting = [&](Settings::Checkbox& a_setting) { + const auto prevValue = a_setting.value.get_data(); + const auto newValue = a_eventData.m_Value.Bool; + if (prevValue != newValue) { + *a_setting.value = newValue; + settings->Save(); + return true; + } + return false; + }; + + switch (a_eventData.m_SettingID) { + case static_cast(Settings::SettingID::kForceSDROnHDR): + { + const bool wasDisplayModeHDR = settings->IsDisplayModeSetToHDR(); + const bool wasSDRForcedOnHDR = settings->IsSDRForcedOnHDR(); + const bool wasGameRenderingHDR = settings->IsGameRenderingSetToHDR(); + if (HandleSetting(settings->ForceSDROnHDR)) { + const bool isDisplayModeHDR = settings->IsDisplayModeSetToHDR(); + const bool isSDRForcedOnHDR = settings->IsSDRForcedOnHDR(); + const bool isGameRenderingHDR = settings->IsGameRenderingSetToHDR(); + // We probably don't need all these checks, but we are being extra sure + if (wasDisplayModeHDR != isDisplayModeHDR || wasSDRForcedOnHDR != isSDRForcedOnHDR || wasGameRenderingHDR != isGameRenderingHDR) { + ToggleEnableHDRSubSettings(a_eventData.m_Model, isDisplayModeHDR, isGameRenderingHDR, isSDRForcedOnHDR); + } + if (const auto displayModeSetting = a_eventData.m_Model->FindSettingById(static_cast(Settings::SettingID::kDisplayMode))) { + displayModeSetting->m_Enabled.SetValue(settings->IsHDRSupported() && !settings->IsSDRForcedOnHDR()); + } + settings->OnDisplayModeChanged(); + } + } + break; + case static_cast(Settings::SettingID::kVanillaMenuLUTs): + HandleSetting(settings->VanillaMenuLUTs); + break; + case static_cast(Settings::SettingID::kPostSharpen): + HandleSetting(settings->PostSharpen); + break; + } + + _SettingsDataModelCheckboxChanged(a_arg1, a_eventData); + } + + void Hooks::Hook_SettingsDataModelStepperChanged(void* a_arg1, RE::SettingsDataModel::UpdateEventData& a_eventData) + { + const auto settings = Settings::Main::GetSingleton(); + + auto HandleSetting = [&](Settings::Stepper& a_setting) { + const auto prevValue = a_setting.value.get_data(); + const auto newValue = a_setting.GetValueFromStepper(a_eventData.m_Value.Int); + if (prevValue != newValue) { + *a_setting.value = newValue; + settings->Save(); + return true; + } + return false; + }; + + switch (a_eventData.m_SettingID) { + case static_cast(Settings::SettingID::kDisplayMode): + { + const bool wasDisplayModeHDR = settings->IsDisplayModeSetToHDR(); + const bool wasSDRForcedOnHDR = settings->IsSDRForcedOnHDR(); + const bool wasGameRenderingHDR = settings->IsGameRenderingSetToHDR(); + if (HandleSetting(settings->DisplayMode)) { + const bool isDisplayModeHDR = settings->IsDisplayModeSetToHDR(); + const bool isSDRForcedOnHDR = settings->IsSDRForcedOnHDR(); + const bool isGameRenderingHDR = settings->IsGameRenderingSetToHDR(); + // We probably don't need all these checks, but we are being extra sure + if (wasDisplayModeHDR != isDisplayModeHDR || wasSDRForcedOnHDR != isSDRForcedOnHDR || wasGameRenderingHDR != isGameRenderingHDR) { + ToggleEnableHDRSubSettings(a_eventData.m_Model, isDisplayModeHDR, isGameRenderingHDR, isSDRForcedOnHDR); + } + if (const auto displayModeSetting = a_eventData.m_Model->FindSettingById(static_cast(Settings::SettingID::kDisplayMode))) { + displayModeSetting->m_Enabled.SetValue(settings->IsHDRSupported() && !settings->IsSDRForcedOnHDR()); + } + settings->OnDisplayModeChanged(); + } + } + break; + case static_cast(Settings::SettingID::kHDR_PeakBrightness): + HandleSetting(settings->PeakBrightness); + break; + case static_cast(Settings::SettingID::kHDR_GamePaperWhite): + HandleSetting(settings->GamePaperWhite); + break; + case static_cast(Settings::SettingID::kHDR_UIPaperWhite): + HandleSetting(settings->UIPaperWhite); + break; + case static_cast(Settings::SettingID::kFilmGrainType): + HandleSetting(settings->FilmGrainType); + if (const auto filmGrainCap = a_eventData.m_Model->FindSettingById(static_cast(Settings::SettingID::kFilmGrainCap))) { + filmGrainCap->m_Enabled.SetValue(settings->IsFilmGrainTypeImproved()); + } + break; + } + + _SettingsDataModelStepperChanged(a_arg1, a_eventData); + } + + bool Hooks::OnSettingsDataModelSliderChanged(RE::SettingsDataModel::UpdateEventData& a_eventData) + { + const auto settings = Settings::Main::GetSingleton(); + + auto HandleSetting = [&](Settings::Slider& a_setting) { + const auto prevValue = a_setting.value.get_data(); + const auto newValue = a_setting.GetValueFromSlider(a_eventData.m_Value.Float); + + if (prevValue != newValue) { + *a_setting.value = newValue; + settings->Save(); + } + + // Skip _SettingsDataModelSliderChanged and queue the update callback ourselves. Why, you ask? Bethesda had the + // brilliant idea to hardcode slider option text values. + struct + { + int v1; // 0 + float v2; // 4 + const char* v3; // 8 + unsigned int v4 = 0; // 10 + unsigned short v5 = 1024; // 14 + } const callbackData = { + .v1 = a_eventData.m_SettingID, + .v2 = a_eventData.m_Value.Float, + .v3 = a_setting.GetSliderText().c_str(), + }; + + const auto modelData = *reinterpret_cast(reinterpret_cast(a_eventData.m_Model) + 0x8); + const auto func = reinterpret_cast(dku::Hook::IDToAbs(135746)); + + if (modelData) { + func(modelData, &callbackData); + } + }; + + switch (a_eventData.m_SettingID) { + case static_cast(Settings::SettingID::kHDR_ExtendGamut): + HandleSetting(settings->ExtendGamut); + return true; + case static_cast(Settings::SettingID::kHDR_Saturation): + HandleSetting(settings->Saturation); + return true; + case static_cast(Settings::SettingID::kHDR_Contrast): + HandleSetting(settings->Contrast); + return true; + case static_cast(Settings::SettingID::kLUTCorrectionStrength): + HandleSetting(settings->LUTCorrectionStrength); + return true; + case static_cast(Settings::SettingID::kColorGradingStrength): + HandleSetting(settings->ColorGradingStrength); + return true; + case static_cast(Settings::SettingID::kGammaCorrectionStrength): + HandleSetting(settings->GammaCorrectionStrength); + return true; + case static_cast(Settings::SettingID::kSecondaryBrightness): + HandleSetting(settings->SecondaryBrightness); + return true; + case static_cast(Settings::SettingID::kFilmGrainCap): + HandleSetting(settings->FilmGrainCap); + return true; + } + + return false; + } + + void Hooks::Hook_SettingsDataModelSliderChanged1(RE::SettingsDataModel::UpdateEventData& a_eventData) + { + if (!OnSettingsDataModelSliderChanged(a_eventData)) { + _SettingsDataModelSliderChanged1(a_eventData); + } + } + + void Hooks::Hook_SettingsDataModelSliderChanged2(RE::SettingsDataModel::UpdateEventData& a_eventData) + { + if (!OnSettingsDataModelSliderChanged(a_eventData)) { + _SettingsDataModelSliderChanged2(a_eventData); + } + } + + bool Hooks::Hook_ApplyRenderPassRenderState1(void* a_arg1, void* a_arg2) + { + const bool result = _ApplyRenderPassRenderState1(a_arg1, a_arg2); + + if (result) { + UploadRootConstants(a_arg1, a_arg2); + } + + return result; + } + + bool Hooks::Hook_ApplyRenderPassRenderState2(void* a_arg1, void* a_arg2) + { + const bool result = _ApplyRenderPassRenderState2(a_arg1, a_arg2); + + if (result) { + UploadRootConstants(a_arg1, a_arg2); + } + + return result; + } + + void Hooks::Hook_EndOfFrame(void* a1, void* a2, const char* a3) + { + Settings::Main::GetSingleton()->SetAtEndOfFrame(true); + _EndOfFrame(a1, a2, a3); + } + + void Hooks::Hook_PostEndOfFrame(void* a1) + { + _PostEndOfFrame(a1); + Settings::Main::GetSingleton()->SetAtEndOfFrame(false); + + // Hack to refresh the HDR official game graphics settings menu settings when the main or pause menu is first opened, + // otherwise if moving the game between SDR and HDR screens, it could end up staying grayed out, or not graying out. + // Note that toggling between windowed and borderless also automatically refreshes this as it re-creates the swapchain. + static bool wasInPauseMenu = false; + if (!wasInPauseMenu && (Utils::IsInPauseMenu() || Utils::IsInMainMenu())) { + Settings::Main::GetSingleton()->RefreshHDRDisplaySupportState(); + wasInPauseMenu = true; + } else if (wasInPauseMenu && !(Utils::IsInPauseMenu() || Utils::IsInMainMenu())) { + wasInPauseMenu = false; + } + } + + void Install() + { +#ifndef NDEBUG + Utils::LogBuffers(); +#endif + Hooks::Hook(); + Patches::Patch(); + } +} diff --git a/Plugin/src/Hooks.h b/Plugin/src/Hooks.h new file mode 100644 index 00000000..3b6a886b --- /dev/null +++ b/Plugin/src/Hooks.h @@ -0,0 +1,113 @@ +#pragma once +#include "Settings.h" +#include "Utils.h" +#include "RE/Buffers.h" +#include "RE/SettingsDataModel.h" + +namespace Hooks +{ + class Patches + { + public: + static void Patch() + { + const auto settings = Settings::Main::GetSingleton(); + + auto newFormat = settings->GetDisplayModeFormat(); + Utils::SetBufferFormat(RE::Buffers::FrameBuffer, newFormat); + + for (const auto& renderTargetName : settings->RenderTargetsToUpgrade.get_collection()) { + if (const auto buffer = GetBufferFromString(renderTargetName)) { + Utils::SetBufferFormat(buffer, RE::BS_DXGI_FORMAT::BS_DXGI_FORMAT_R16G16B16A16_FLOAT); + } + } + + Utils::LogBuffers(); + } + + private: + static RE::BufferDefinition* GetBufferFromString(std::string_view a_bufferName); + }; + + class Hooks + { + public: + static void Hook() + { + // set color space and save swapchain object pointer + _UnkFunc = dku::Hook::write_call<5>(dku::Hook::IDToAbs(204384, 0x3EA), Hook_UnkFunc); + + // disable photo mode screenshots with HDR + const auto takeSnapshotVtbl = dku::Hook::IDToAbs(415473); + auto _Hook_TakeSnapshot = dku::Hook::AddVMTHook(&takeSnapshotVtbl, 1, FUNC_INFO(Hook_TakeSnapshot)); + _TakeSnapshot = reinterpret_cast>(_Hook_TakeSnapshot->OldAddress); + _Hook_TakeSnapshot->Enable(); + + // Settings UI + _CreateMonitorSetting = dku::Hook::write_call<5>(dku::Hook::IDToAbs(136113, 0x62F), Hook_CreateMonitorSetting); + _SettingsDataModelCheckboxChanged = dku::Hook::write_call<5>(dku::Hook::IDToAbs(136121, 0x3A), Hook_SettingsDataModelCheckboxChanged); + _SettingsDataModelStepperChanged = dku::Hook::write_call<5>(dku::Hook::IDToAbs(136131, 0x37), Hook_SettingsDataModelStepperChanged); + _SettingsDataModelSliderChanged1 = dku::Hook::write_branch<5>(dku::Hook::IDToAbs(135739, 0xA3), Hook_SettingsDataModelSliderChanged1); + _SettingsDataModelSliderChanged2 = dku::Hook::write_branch<5>(dku::Hook::IDToAbs(135956, 0x4), Hook_SettingsDataModelSliderChanged2); + + _RecreateSwapchain = dku::Hook::write_call<5>(dku::Hook::IDToAbs(203027, 0x89), Hook_RecreateSwapchain); + + _ApplyRenderPassRenderState1 = dku::Hook::write_call<5>(dku::Hook::IDToAbs(204409, 0x18), Hook_ApplyRenderPassRenderState1); // CmdDraw + _ApplyRenderPassRenderState2 = dku::Hook::write_call<5>(dku::Hook::IDToAbs(204408, 0x20), Hook_ApplyRenderPassRenderState2); // CmdDispatch + + _EndOfFrame = dku::Hook::write_call<5>(dku::Hook::IDToAbs(205436, 0x3F7), Hook_EndOfFrame); + _PostEndOfFrame = dku::Hook::write_call<5>(dku::Hook::IDToAbs(205436, 0x7CB), Hook_PostEndOfFrame); + + dku::Hook::write_call<5>(dku::Hook::IDToAbs(208157, 0x174), HookedScaleformCompositeSetRenderTarget); + dku::Hook::write_call<5>(dku::Hook::IDToAbs(208157, 0x249), HookedScaleformCompositeDraw); + } + + private: + static void ToggleEnableHDRSubSettings(RE::SettingsDataModel* a_model, bool a_bDisplayModeHDREnable, bool a_bGameRenderingHDREnable, bool a_bSDRForcedOnHDR); + static void CreateCheckboxSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Checkbox& a_setting, bool a_bEnabled); + static void CreateStepperSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Stepper& a_setting, bool a_bEnabled); + static void CreateSliderSetting(RE::ArrayNestedUIValue* a_settingList, Settings::Slider& a_setting, bool a_bEnabled); + static void CreateSeparator(RE::ArrayNestedUIValue* a_settingList, Settings::SettingID a_id); + static void CreateSettings(RE::ArrayNestedUIValue* a_settingList); + + static void UploadRootConstants(void* a1, void* a2); + + static void HookedScaleformCompositeSetRenderTarget(void* a1, void* a2, void** a_rtArray, void* a4, void* a5, void* a6, void* a7, void* a8, void* a9); + static void HookedScaleformCompositeDraw(void* a_arg1, void* a_arg2, uint32_t a_vertexCount); + + static void Hook_UnkFunc(uintptr_t a1, RE::BGSSwapChainObject* a_bgsSwapchainObject); + static inline std::add_pointer_t _UnkFunc; + + static bool Hook_TakeSnapshot(uintptr_t a1); + static inline std::add_pointer_t _TakeSnapshot; + + static void Hook_RecreateSwapchain(void* a1, RE::BGSSwapChainObject* a_bgsSwapChainObject, uint32_t a_width, uint32_t a_height, uint8_t a5); + static inline std::add_pointer_t _RecreateSwapchain; + + static void Hook_CreateMonitorSetting(void* a1, void* a2); + static inline std::add_pointer_t _CreateMonitorSetting; + static void Hook_SettingsDataModelCheckboxChanged(void* a_arg1, RE::SettingsDataModel::UpdateEventData& a_eventData); + static inline std::add_pointer_t _SettingsDataModelCheckboxChanged; + static void Hook_SettingsDataModelStepperChanged(void* a_arg1, RE::SettingsDataModel::UpdateEventData& a_eventData); + static inline std::add_pointer_t _SettingsDataModelStepperChanged; + + static bool OnSettingsDataModelSliderChanged(RE::SettingsDataModel::UpdateEventData& a_eventData); + static void Hook_SettingsDataModelSliderChanged1(RE::SettingsDataModel::UpdateEventData& a_eventData); + static void Hook_SettingsDataModelSliderChanged2(RE::SettingsDataModel::UpdateEventData& a_eventData); + static inline std::add_pointer_t _SettingsDataModelSliderChanged1; + static inline std::add_pointer_t _SettingsDataModelSliderChanged2; + + static bool Hook_ApplyRenderPassRenderState1(void* a_arg1, void* a_arg2); + static bool Hook_ApplyRenderPassRenderState2(void* a_arg1, void* a_arg2); + static inline std::add_pointer_t _ApplyRenderPassRenderState1; + static inline std::add_pointer_t _ApplyRenderPassRenderState2; + + static void Hook_EndOfFrame(void* a1, void* a2, const char* a3); + static inline std::add_pointer_t _EndOfFrame; + + static void Hook_PostEndOfFrame(void* a1); + static inline std::add_pointer_t _PostEndOfFrame; + }; + + void Install(); +} diff --git a/Plugin/src/Offsets.h b/Plugin/src/Offsets.h new file mode 100644 index 00000000..4ae29432 --- /dev/null +++ b/Plugin/src/Offsets.h @@ -0,0 +1,56 @@ +#pragma once +#include "RE/BSFixedString.h" +#include "RE/Buffers.h" +#include "RE/MessageBoxData.h" + +#include "sfse/GameUI.h" + +class Offsets +{ +public: + using BufferArray = std::array; + static inline BufferArray* bufferArray = nullptr; + + using tGetDXGIFormat = DXGI_FORMAT (*)(RE::BS_DXGI_FORMAT a_bgsFormat); + static inline tGetDXGIFormat GetDXGIFormat = nullptr; + + static inline void** MessageMenuManagerPtr = nullptr; + using tShowMessageBox = void (*)(void* a_messageMenuManager, const RE::MessageBoxData& a_messageBoxData, bool a3); + static inline tShowMessageBox ShowMessageBox = nullptr; + + using tPhotoMode_ToggleUI = bool (*)(uintptr_t a1); + static inline tPhotoMode_ToggleUI PhotoMode_ToggleUI = nullptr; + + using tUI_IsMenuOpen = bool (*)(UI* a_ui, const RE::BSFixedString& a_menuName); + static inline UI** uiPtr = nullptr; + static inline tUI_IsMenuOpen UI_IsMenuOpen = nullptr; + + static inline float* g_deltaTimeRealTime = nullptr; + static inline uint32_t* g_durationOfApplicationRunTimeMS = nullptr; + + //test + static inline uintptr_t* unkToggleVsyncArg1Ptr = nullptr; + using tToggleVsync = void (*)(void* a1, bool a_bEnable); + static inline tToggleVsync ToggleVsync = nullptr; + static inline bool* bEnableVsync = nullptr; + + static void Initialize() + { + bufferArray = reinterpret_cast(dku::Hook::IDToAbs(477165)); + GetDXGIFormat = reinterpret_cast(dku::Hook::IDToAbs(204483)); + + ToggleVsync = reinterpret_cast(dku::Hook::IDToAbs(184653)); + unkToggleVsyncArg1Ptr = reinterpret_cast(dku::Hook::IDToAbs(878340)); + bEnableVsync = reinterpret_cast(dku::Hook::IDToAbs(875798)); + + MessageMenuManagerPtr = reinterpret_cast(dku::Hook::IDToAbs(878772)); + ShowMessageBox = reinterpret_cast(dku::Hook::IDToAbs(167094)); + PhotoMode_ToggleUI = reinterpret_cast(dku::Hook::IDToAbs(139734)); + + uiPtr = reinterpret_cast(dku::Hook::IDToAbs(878339)); + UI_IsMenuOpen = reinterpret_cast(dku::Hook::IDToAbs(187049)); + + g_deltaTimeRealTime = reinterpret_cast(dku::Hook::IDToAbs(871870)); + g_durationOfApplicationRunTimeMS = reinterpret_cast(dku::Hook::IDToAbs(871872)); + } +}; diff --git a/Plugin/src/PCH.h b/Plugin/src/PCH.h new file mode 100644 index 00000000..4b6cf642 --- /dev/null +++ b/Plugin/src/PCH.h @@ -0,0 +1,121 @@ +#pragma once + +// c +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// cxx +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// winnt +#include + +#undef min +#undef max + +using namespace std::literals; + +#define DLLEXPORT extern "C" [[maybe_unused]] __declspec(dllexport) +#define SFSEAPI __cdecl +#define PLUGIN_MODE + +// Plugin +#include "Plugin.h" + +// DKUtil +#include "DKUtil/Hook.hpp" +#include "DKUtil/Logger.hpp" + +// reshade addon api +#include "imgui.h" +#include "reshade/reshade_api.hpp" diff --git a/Plugin/src/RE/BSFixedString.h b/Plugin/src/RE/BSFixedString.h new file mode 100644 index 00000000..14a6ce85 --- /dev/null +++ b/Plugin/src/RE/BSFixedString.h @@ -0,0 +1,78 @@ +#pragma once + +namespace RE +{ + class BSFixedString + { + private: + void* m_EntryPoolData = nullptr; + + public: + BSFixedString() = default; + + BSFixedString(const char* String) + { + auto addr = dku::Hook::IDToAbs(198219); + auto func = reinterpret_cast(addr); + func(this, String); + } + + BSFixedString(const BSFixedString& Other) = delete; + + ~BSFixedString() + { + auto addr = dku::Hook::IDToAbs(36754); + auto func = reinterpret_cast(addr); + func(this); + } + + BSFixedString& operator=(const BSFixedString& Other) = delete; + + bool operator==(const BSFixedString& Other) const + { + return m_EntryPoolData == Other.m_EntryPoolData; + } + + bool operator!=(const BSFixedString& Other) const + { + return m_EntryPoolData != Other.m_EntryPoolData; + } + }; + + class BSFixedStringCS + { + private: + void* m_EntryPoolData = nullptr; + + public: + BSFixedStringCS() = default; + + BSFixedStringCS(const char* String) + { + auto addr = dku::Hook::IDToAbs(198219); + auto func = reinterpret_cast(addr); + func(this, String); + } + + BSFixedStringCS(const BSFixedStringCS& Other) = delete; + + ~BSFixedStringCS() + { + auto addr = dku::Hook::IDToAbs(33964); + auto func = reinterpret_cast(addr); + func(this); + } + + BSFixedStringCS& operator=(const BSFixedStringCS& Other) = delete; + + bool operator==(const BSFixedStringCS& Other) const + { + return m_EntryPoolData == Other.m_EntryPoolData; + } + + bool operator!=(const BSFixedStringCS& Other) const + { + return m_EntryPoolData != Other.m_EntryPoolData; + } + }; +} diff --git a/Plugin/src/RE/Buffers.h b/Plugin/src/RE/Buffers.h new file mode 100644 index 00000000..cdd72385 --- /dev/null +++ b/Plugin/src/RE/Buffers.h @@ -0,0 +1,389 @@ +#pragma once +#include +#include + +namespace RE +{ + enum class BS_DXGI_FORMAT + { + BS_DXGI_FORMAT_UNKNOWN_0 = 0, + BS_DXGI_FORMAT_R8_UNORM = 1, + BS_DXGI_FORMAT_R8_SNORM = 2, + BS_DXGI_FORMAT_R8_UINT, + BS_DXGI_FORMAT_R8_SINT, + BS_DXGI_FORMAT_UNKNOWN_5, + BS_DXGI_FORMAT_UNKNOWN_6, + BS_DXGI_FORMAT_B4G4R4A4_UNORM, + BS_DXGI_FORMAT_UNKNOWN_8, + BS_DXGI_FORMAT_UNKNOWN_9, + BS_DXGI_FORMAT_B5G6R5_UNORM_10, + BS_DXGI_FORMAT_B5G6R5_UNORM_11, + BS_DXGI_FORMAT_UNKNOWN_12, + BS_DXGI_FORMAT_B5G5R5A1_UNORM, + BS_DXGI_FORMAT_R8G8_UNORM, + BS_DXGI_FORMAT_R8G8_SNORM, + BS_DXGI_FORMAT_UNKNOWN_16, + BS_DXGI_FORMAT_UNKNOWN_17, + BS_DXGI_FORMAT_R8G8_UINT, + BS_DXGI_FORMAT_R8G8_SINT, + BS_DXGI_FORMAT_UNKNOWN_20, + BS_DXGI_FORMAT_R16_UNORM, + BS_DXGI_FORMAT_R16_SNORM, + BS_DXGI_FORMAT_R16_UINT, + BS_DXGI_FORMAT_R16_SINT, + BS_DXGI_FORMAT_R16_FLOAT, + BS_DXGI_FORMAT_UNKNOWN_26, + BS_DXGI_FORMAT_UNKNOWN_27, + BS_DXGI_FORMAT_UNKNOWN_28, + BS_DXGI_FORMAT_UNKNOWN_29, + BS_DXGI_FORMAT_UNKNOWN_30, + BS_DXGI_FORMAT_UNKNOWN_31, + BS_DXGI_FORMAT_UNKNOWN_32, + BS_DXGI_FORMAT_UNKNOWN_33, + BS_DXGI_FORMAT_UNKNOWN_34, + BS_DXGI_FORMAT_UNKNOWN_35, + BS_DXGI_FORMAT_R8G8B8A8_UNORM, + BS_DXGI_FORMAT_R8G8B8A8_SNORM, + BS_DXGI_FORMAT_R8G8B8A8_UINT, + BS_DXGI_FORMAT_R8G8B8A8_SINT, + BS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + BS_DXGI_FORMAT_B8G8R8A8_UNORM, + BS_DXGI_FORMAT_UNKNOWN_42, + BS_DXGI_FORMAT_UNKNOWN_43, + BS_DXGI_FORMAT_UNKNOWN_44, + BS_DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + BS_DXGI_FORMAT_UNKNOWN_46, + BS_DXGI_FORMAT_B8G8R8X8_UNORM, + BS_DXGI_FORMAT_R16G16_UNORM, + BS_DXGI_FORMAT_UNKNOWN_49, + BS_DXGI_FORMAT_R16G16_SNORM, + BS_DXGI_FORMAT_UNKNOWN_51, + BS_DXGI_FORMAT_R16G16_UINT, + BS_DXGI_FORMAT_R16G16_SINT, + BS_DXGI_FORMAT_R16G16_FLOAT, + BS_DXGI_FORMAT_R32_UINT, + BS_DXGI_FORMAT_R32_SINT, + BS_DXGI_FORMAT_R32_FLOAT, + BS_DXGI_FORMAT_UNKNOWN_58, + BS_DXGI_FORMAT_UNKNOWN_59, + BS_DXGI_FORMAT_UNKNOWN_60, + BS_DXGI_FORMAT_UNKNOWN_61, + BS_DXGI_FORMAT_R10G10B10A2_UNORM, + BS_DXGI_FORMAT_R10G10B10A2_UINT, + BS_DXGI_FORMAT_UNKNOWN_64, + BS_DXGI_FORMAT_UNKNOWN_65, + BS_DXGI_FORMAT_R11G11B10_FLOAT, + BS_DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + BS_DXGI_FORMAT_UNKNOWN_68, + BS_DXGI_FORMAT_UNKNOWN_69, + BS_DXGI_FORMAT_UNKNOWN_70, + BS_DXGI_FORMAT_UNKNOWN_71, + BS_DXGI_FORMAT_UNKNOWN_72, + BS_DXGI_FORMAT_R16G16B16A16_UNORM, + BS_DXGI_FORMAT_R16G16B16A16_SNORM, + BS_DXGI_FORMAT_R16G16B16A16_UINT, + BS_DXGI_FORMAT_R16G16B16A16_SINT, + BS_DXGI_FORMAT_R16G16B16A16_FLOAT, + BS_DXGI_FORMAT_R32G32_UINT, + BS_DXGI_FORMAT_R32G32_SINT, + BS_DXGI_FORMAT_R32G32_FLOAT, + BS_DXGI_FORMAT_R32G32B32_UINT, + BS_DXGI_FORMAT_R32G32B32_SINT, + BS_DXGI_FORMAT_R32G32B32_FLOAT, + BS_DXGI_FORMAT_R32G32B32A32_UINT, + BS_DXGI_FORMAT_R32G32B32A32_SINT, + BS_DXGI_FORMAT_R32G32B32A32_FLOAT, + BS_DXGI_FORMAT_UNKNOWN_87, + BS_DXGI_FORMAT_UNKNOWN_88, + BS_DXGI_FORMAT_UNKNOWN_89, + BS_DXGI_FORMAT_UNKNOWN_90, + BS_DXGI_FORMAT_UNKNOWN_91, + BS_DXGI_FORMAT_UNKNOWN_92, + BS_DXGI_FORMAT_UNKNOWN_93, + BS_DXGI_FORMAT_UNKNOWN_94, + BS_DXGI_FORMAT_UNKNOWN_95, + BS_DXGI_FORMAT_UNKNOWN_96, + BS_DXGI_FORMAT_UNKNOWN_97, + BS_DXGI_FORMAT_UNKNOWN_98, + BS_DXGI_FORMAT_D16_UNORM, + BS_DXGI_FORMAT_D24_UNORM_S8_UINT, + BS_DXGI_FORMAT_D32_FLOAT, + BS_DXGI_FORMAT_D24_UNORM_S8_UINT_102, + BS_DXGI_FORMAT_D24_UNORM_S8_UINT_103, + BS_DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + BS_DXGI_FORMAT_BC1_UNORM_105, + BS_DXGI_FORMAT_BC1_UNORM_SRGB_106, + BS_DXGI_FORMAT_BC1_UNORM_107, + BS_DXGI_FORMAT_BC1_UNORM_SRGB_108, + BS_DXGI_FORMAT_BC2_UNORM, + BS_DXGI_FORMAT_BC2_UNORM_SRGB, + BS_DXGI_FORMAT_BC3_UNORM, + BS_DXGI_FORMAT_BC3_UNORM_SRGB, + BS_DXGI_FORMAT_BC4_UNORM, + BS_DXGI_FORMAT_BC4_SNORM, + BS_DXGI_FORMAT_BC5_UNORM, + BS_DXGI_FORMAT_BC5_SNORM, + BS_DXGI_FORMAT_BC6H_UF16, + BS_DXGI_FORMAT_BC6H_SF16, + BS_DXGI_FORMAT_BC7_UNORM, + BS_DXGI_FORMAT_BC7_UNORM_SRGB + }; + + enum class Buffers + { + SF_ColorBuffer = 0, + SF_StencilBuffer = 1, + DepthBuffer, + PostUpscaleDepthBuffer, + TileDepthBoundsVS, + PreviousDepthBufferDesc, + DepthBufferDebug, + TopDownDepthSector, + ShadowMap, + TerrainShadowMap, + TerrainShadowMapBias, + ShadowMaskDesc, + ShadowMaskArrayDesc, + ScaleformStencilBuffer, + ScaleformToTextureStencilBuffer, + Scaleform3DStencilBuffer, + GBuffer_AlbedoMisc, + GBuffer_Normal_EmissiveIntensity, + GBuffer_AO_Rough_Metal, + GBuffer_MV, + GBuffer_Mask, + GBuffer_Optional, + LightingBufferY, + LightingBufferUV, + ContactShadowsBuffer, + ContactShadowsSwapBuffer, + RayTracedLightingDiffuseBuffer, + IndirectLightingDiffuseBuffer, + IndirectLightingSpecularBuffer, + ColorBuffer01, + ColorBufferUAV, + NativeResolutionColorBuffer01, + DistortionValueBuffer, + DistortionBlurStrengthBuffer, + DistortionColorBuffer, + ImageSpaceBuffer, + HDRImagespaceBuffer, + ImageSpaceBufferR10G10B10A2, + ImageSpaceBufferB10G11R11, + ImageSpaceBufferE5B9G9R9, + ImageSpaceBufferR16G16B16A16, + ImageSpaceBufferR32G32B32A32, + ImageSpaceHalfResBuffer, + ScaleformCompositeBuffer, + ColorGradingLUT, + LumaLowResPreUpscale, + LumaLowResPostUpscale, + BloomPyramidPreUpscale, + BloomPyramidPostUpscale, + HDRLum, + HDRSingleValueAverageLum, + HDRBloom, + HDRBloomDS1, + HDRBloomDS2, + HDRBloomDS3, + HDRBloomDS4, + HDRBloomDS5, + HDRBloomDS6, + SAOCameraZ, + SAORawAO, + SAOFinalAO, + FrameBuffer, + NullRenderTarget, + VisualizationBuffer, + HeightClipmap, + BlurHeightClipmap, + ShoreClipmap, + ShoreFlood, + SplatClipmap, + NormalClipmap, + VErrorClipmap, + MaterialIndexMap, + ProcGenDensityMap, + DownsampleOutputPrevFrame, + DownsampleOutput, + SobelOutput, + SpaceGlareBlur, + CGenTestTexture3D, + DownsampleMipChainOutput, + BlurredMipChainOutput, + RefractionPrevFrame, + DoFHTileMask, + DoFCoCTarget, + DoFColorTarget, + DoFTAAHistoryTarget, + TAA_idTech7HistoryColorTarget, + TAA_idTech7HistoryDataTarget, + RT_HighlightMask, + RT_ColorGradeMask, + SeparableSSSBufferY, + SeparableSSSBufferUV, + SHLUTAngle_High, + SHLUTAngle_Mid, + SHLUTAngle_Low, + SHLUTAngleProbe, + EnvBRDF, + BinkYPlane, + BinkcRcBPlane, + DebugMotionVectorColorBufferCopy, + AlphaBuffer, + VRSMask, + VRSMaskHistory, + VRSMaskCompute, + MaxTileVelocityBuffer, + VelocityDepthBuffer, + RefractionMaskCoarse, + ReflectionProbeSHAtlas, + FSR2ReactiveMask, + FSR2TandCMask, + FSR2_PREPARED_INPUT_COLOR, + FSR2_RECONSTRUCTED_PREVIOUS_NEAREST_DEPTH, + FSR2_INTERNAL_DILATED_MOTION_VECTORS, + FSR2_DILATED_DEPTH, + FSR2_RESAMPLED_LUMA_HISTORY, + FSR2_DEPTH_CLIP, + FSR2_AUTO_EXPOSURE, + FSR2_DILATED_REACTIVE_MASKS, + FSR2_INTERNAL_UPSCALED_COLOR_W, + MBOITMoments4, + MBOITOpticalDepth, + MBOITMoments4HalfRes, + MBOITOpticalDepthHalfRes, + MBOITTransparentAccumulation, + MBOITTransparentAccumulationHalfRes, + MBOITForwardHalfResTarget, + ForwardHalfResTarget, + ForwardHalfResDepth, + ForwardHalfResOverdraw, + BlurHeightFieldStaging, + BlurHeightField, + SkyOcclusionSH, + TopDownDepthArray, + FilteredHeightfield, + DownsampledHeightfield, + ProbeRayTrace, + ProbeDistanceAtlas, + ProbeIrradianceAtlas, + ProbeStateMaxDistanceAtlas, + CascadeProbeRayTrace, + CascadeProbeDistanceAtlas, + CascadeProbeIrradianceAtlas, + CascadeProbeStateMaxDistanceAtlas, + CascadeProbeScrollSpace, + ThinDepthBuffer, + ThinGBuffer_Albedo, + ThinGBuffer_Normal, + ThinGBuffer_Optional, + ThinDepthBufferArray, + ThinGBuffer_AlbedoArray, + ThinGBuffer_NormalArray, + ThinGBuffer_OptionalArray, + ReflectionCubemapArray, + ReflectionCubemapCaptureArray, + ReflectionCubemapForSHArray, + ReflectionCubemapDepthArray, + SkyCubemapAtmosScatteringOutput, + SkyCubemap, + SkyCubemapThinDepthBuffer, + SkyCubemapThinGBuffer_Albedo, + SkyCubemapThinGBuffer_Normal, + SkyCubemapThinGBuffer_Optional, + CelestialBodyThinGBuffer_Albedo, + CelestialBodyThinGBuffer_Normal, + CelestialBodyThinGBuffer_Optional, + CelestialBodyDepthBuffer, + NetDensityToAtmTop, + SingleScattering, + ScatterRadiance, + InscatterOrder, + HighOrderScatter, + EpipolarSliceEndpoints, + EpipolarCoordinates, + EpipolarRawDepth, + EpipolarExtinction, + EpipolarInscattering, + EpipolarInterpolationSource, + EpipolarInitialScatteredLight, + EpipolarSliceUVDirAndOrigin, + MinMaxShadowMap, + AtmosphericScatteringOutput, + PrecomputedTransmittance, + FogMap, + MaterialVolume, + ScatteringVolume, + ScatteringVolumeHistoryTarget, + DistantScattering, + DistantScatteringHistoryTarget, + DistantScatteringComposite, + PerlinNoise3D, + PerlinNoise2D, + VolumeDepthDownsample, + FaceCustomizationDiffuse, + FaceCustomizationDiffuseLinear, + FaceCustomizationNormals, + FaceCustomizationAO, + FaceCustomizationRoughness, + WaterDisplacementTarget, + ImageProcessColorTarget, + ImageProcessR8Target, + TextureReadbackInput_All, + ParticleLightingAtlas, + CloudsHalfResTarget, + CloudCardsOpacity, + ImageCaptureHDR_OutputImage + }; + + struct BufferDefinition + { + BS_DXGI_FORMAT format; + uint32_t unk04; + const char* bufferName; + uint16_t unk10; + uint16_t unk12; + uint32_t unk14; + uint16_t unk18; + uint16_t unk1A; + uint32_t unk1C; + uint16_t unk20; + uint16_t unk22; + uint32_t unk24; + uint16_t unk28; + uint16_t unk2A; + uint32_t unk2C; + uint32_t unk30; + float unk34; + float unk38; + float unk3C; + uint32_t unk40; + uint32_t unk44; + uint32_t unk48; + uint32_t unk4C; + }; + static_assert(sizeof(BufferDefinition) == 0x50); + + struct BGSSwapChainObject + { + HWND hwnd; + uint64_t unk08; + uint32_t unk10; + uint32_t bufferCount; + uint32_t width; + uint32_t height; + uint32_t unk20; + uint32_t sampleQuality; + BS_DXGI_FORMAT format; + uint64_t unk30; + uint64_t unk38; + uint64_t unk40; + uint64_t unk48; + IDXGISwapChain3* swapChainInterface; + uint64_t unk58; + ID3D12Resource** renderTargets; + uint64_t unk68; + HANDLE handle; + }; +} diff --git a/Plugin/src/RE/MessageBoxData.h b/Plugin/src/RE/MessageBoxData.h new file mode 100644 index 00000000..11beca13 --- /dev/null +++ b/Plugin/src/RE/MessageBoxData.h @@ -0,0 +1,40 @@ +#pragma once + +namespace RE +{ + class MessageBoxData + { + public: + MessageBoxData() = default; + + MessageBoxData(const char* a_messageTitle, const char* a_messageText, void* a4, int32_t a5) + { + auto addr = dku::Hook::IDToAbs(81979); + auto func = reinterpret_cast(addr); + func(this, a_messageTitle, a_messageText, a4, a5); + } + + MessageBoxData(const MessageBoxData& Other) = delete; + + ~MessageBoxData() + { + auto addr = dku::Hook::IDToAbs(82034); + auto func = reinterpret_cast(addr); + func(this); + } + + MessageBoxData& operator=(const MessageBoxData& Other) = delete; + + // members + uint64_t unk00; + uint64_t unk08; + uint64_t unk10; + uint64_t unk18; + uint64_t unk20; + uint64_t unk28; + uint64_t unk30; + int32_t unk38; + }; + static_assert(sizeof(MessageBoxData) == 0x40); + +} diff --git a/Plugin/src/RE/SettingsDataModel.h b/Plugin/src/RE/SettingsDataModel.h new file mode 100644 index 00000000..ecf6893f --- /dev/null +++ b/Plugin/src/RE/SettingsDataModel.h @@ -0,0 +1,136 @@ +#pragma once + +#include "UIDataShuttle.h" +#include "UI.h" + +namespace RE +{ + class SubSettingsList + { + public: + class GeneralSetting + { + public: + struct Type + { + enum + { + Slider = 0, + Stepper = 1, + LargeStepper = 2, + Checkbox = 3, + }; + }; + + struct Category + { + enum + { + Gameplay = 0, + Display = 1, + Interface = 2, + Controls = 3, + ControlMappings = 4, + Audio = 5, + Accessibility = 6, + }; + }; + + struct SliderData + { + TUIValue m_Value; // 0 + StringUIValue m_DisplayValue; // 20 + char _pad40[0x8]; // 40 + }; + + struct StepperData + { + TUIValue m_Value; // 0 + ArrayUIValue, 0> m_DisplayValues; // 20 + char _pad98[0x8]; // 98 + }; + + struct CheckBoxData + { + TUIValue m_Value; // 0 + char _pad20[0x8]; // 20 + }; + + StringUIValue m_Text; // 00 + StringUIValue m_Description; // 20 + TUIValue m_ID; // 40 + TUIValue m_Type; // 60 + TUIValue m_Category; // 80 + TUIValue m_Enabled; // A0 + NestedUIValue m_SliderData; // C0 + NestedUIValue m_StepperData; // 158 + NestedUIValue m_CheckBoxData; // 248 + char _pad2C0[0x8]; // 2D0 + + GeneralSetting() + { + auto addr = dku::Hook::IDToAbs(135831); + auto func = reinterpret_cast(addr); + func(*this); + } + + ~GeneralSetting() + { + auto addr = dku::Hook::IDToAbs(135898); + auto func = reinterpret_cast(addr); + func(*this); + } + }; + + ArrayNestedUIValue m_Settings; // 0 + char _pad78[0x8]; // 78 + }; + + class SettingsDataModel + { + public: + class UpdateEventData + { + public: + SettingsDataModel* m_Model; + union + { + bool Bool; + int Int; + float Float; + } m_Value; + int m_SettingID; + }; + + char _pad0[0x190 + 0x20]; // 0 + TUIDataShuttleContainerMap m_SubSettingsMap; // 1B0 + + SubSettingsList::GeneralSetting* FindSettingById(int Id) + { + // This is supposed to be held under a lock but I don't care enough right now + for (auto& item : m_SubSettingsMap.GetData().m_Settings.Items()) + { + if (item.m_ShuttleMap.GetData().m_ID.m_Value == Id) + return &item.m_ShuttleMap.GetData(); + } + + return nullptr; + } + }; + + // Sanity checks + static_assert(sizeof(NestedUIValue) == 0x98); + static_assert(sizeof(NestedUIValue) == 0xF0); + static_assert(sizeof(NestedUIValue) == 0x78); + + static_assert(sizeof(TUIDataShuttleContainerMap) == 0x70); + static_assert(sizeof(TUIDataShuttleContainerMap) == 0xC8); + static_assert(sizeof(TUIDataShuttleContainerMap) == 0x50); + + static_assert(sizeof(ArrayUIValue, 0>) == 0x78); + + static_assert(sizeof(NestedUIValue) == 0x318); + static_assert(sizeof(ArrayNestedUIValue) == 0x78); + + static_assert(sizeof(TUIDataShuttleContainerMap) == 0xA8); +} diff --git a/Plugin/src/RE/UI.h b/Plugin/src/RE/UI.h new file mode 100644 index 00000000..bcc8d661 --- /dev/null +++ b/Plugin/src/RE/UI.h @@ -0,0 +1,170 @@ +#pragma once + +#include "BSFixedString.h" +#include "UIDataShuttle.h" + +namespace RE +{ + class __declspec(novtable) IUIValue + { + public: + IUIValue() = default; + virtual ~IUIValue() = default; // 00 + virtual void IUIValue_01() = 0; // 01 + virtual void IUIValue_02() = 0; // 02 + virtual void IUIValue_03() = 0; // 03 + virtual void IUIValue_04() = 0; // 04 + virtual void IUIValue_05() = 0; // 05 + virtual void IUIValue_06() = 0; // 06 + virtual void IUIValue_07() = 0; // 07 + virtual bool GetNeedsUpdate(); // 08 + virtual void SetNeedsUpdateAndNotifyShuttle(bool NeedsUpdate); // 09 + virtual void SetNeedsUpdate(); // 0A + virtual void IUIValue_0B() = 0; // 0B + + UIDataShuttle* m_DataShuttle = nullptr; // 08 + bool m_NeedsUpdate = true; // 10 + + void TriggerParentUpdate() + { + if (m_DataShuttle && m_DataShuttle->UIDataShuttle_06()) + m_DataShuttle->UIDataShuttle_02(*this); + } + }; + static_assert(sizeof(IUIValue) == 0x18); + + class __declspec(novtable) IArrayUIValue + { + public: + }; + static_assert(sizeof(IArrayUIValue) == 0x1); + + template + class __declspec(novtable) TUIValue : public IUIValue + { + public: + TUIValue() = default; + virtual ~TUIValue() override = default; // 00 + virtual void IUIValue_01() override; // 01 + virtual void IUIValue_02() override; // 02 + virtual void IUIValue_03() override; // 03 + virtual void IUIValue_04() override; // 04 + virtual void IUIValue_05() override; // 05 + virtual void IUIValue_06() override; // 06 + virtual void IUIValue_07() override; // 07 + virtual void IUIValue_0B() override; // 0B + + T m_Value = {}; // 18 + + TUIValue& SetValue(const T& Value) + { + TriggerParentUpdate(); + + if (m_Value != Value) { + m_Value = Value; + SetNeedsUpdateAndNotifyShuttle(true); + } + + return *this; + } + }; + static_assert(sizeof(TUIValue) == 0x20); + static_assert(sizeof(TUIValue) == 0x20); + + class __declspec(novtable) StringUIValue : public TUIValue + { + public: + StringUIValue() = default; + virtual ~StringUIValue() override = default; // 00 + virtual void StringUIValue_0C(); // 0C + virtual void SetStringValue(const char* Value); // 0D + }; + static_assert(sizeof(StringUIValue) == 0x20); + + template + class __declspec(novtable) NestedUIValue : public IUIValue, public UIDataShuttle + { + public: + NestedUIValue() = default; + virtual ~NestedUIValue() override = default; // 00 + + // IUIValue + virtual void IUIValue_01() override; // 01 + virtual void IUIValue_02() override; // 02 + virtual void IUIValue_03() override; // 03 + virtual void IUIValue_04() override; // 04 + virtual void IUIValue_05() override; // 05 + virtual void IUIValue_06() override; // 06 + virtual void IUIValue_07() override; // 07 + virtual void SetNeedsUpdateAndNotifyShuttle(bool NeedsUpdate) override; // 09 + virtual void SetNeedsUpdate() override; // 0A + virtual void IUIValue_0B() override; // 0B + + // UIDataShuttle + virtual void UIDataShuttle_01() override; // 01 + virtual void UIDataShuttle_02(IUIValue& UIValue) override; // 02 + virtual void UIDataShuttle_03() override; // 03 + virtual void UIDataShuttle_04() override; // 04 + virtual void UIDataShuttle_05() override; // 05 + virtual bool UIDataShuttle_06() override; // 06 + virtual bool UIDataShuttle_07() override; // 07 + + TUIDataShuttleContainerMap m_ShuttleMap; // 28 + }; + + template + class __declspec(novtable) ArrayUIValue : public IUIValue, public UIDataShuttle, public IArrayUIValue + { + public: + ArrayUIValue() = default; + virtual ~ArrayUIValue() override = default; // 00 + + // IUIValue + virtual void IUIValue_01() override; // 01 + virtual void IUIValue_02() override; // 02 + virtual void IUIValue_03() override; // 03 + virtual void IUIValue_04() override; // 04 + virtual void IUIValue_05() override; // 05 + virtual void IUIValue_06() override; // 06 + virtual void IUIValue_07() override; // 07 + virtual void SetNeedsUpdateAndNotifyShuttle(bool NeedsUpdate) override; // 09 + virtual void SetNeedsUpdate() override; // 0A + virtual void IUIValue_0B() override; // 0B + + // UIDataShuttle + virtual void UIDataShuttle_01() override; // 01 + virtual void UIDataShuttle_02(IUIValue& UIValue) override; // 02 + virtual void UIDataShuttle_03() override; // 03 + virtual void UIDataShuttle_04() override; // 04 + virtual void UIDataShuttle_05() override; // 05 + virtual bool UIDataShuttle_06() override; // 06 + virtual bool UIDataShuttle_07() override; // 07 + + TUIDataShuttleContainerArray m_ShuttleArray; // 28 + + void AddItem(const BSFixedStringCS& Item) + { + auto addr = dku::Hook::IDToAbs(134612); + auto func = reinterpret_cast*, const BSFixedStringCS&)>(addr); + func(this, Item); + } + + [[nodiscard]] auto Items() const noexcept + { + return m_ShuttleArray.Items(); + } + }; + + template + class __declspec(novtable) ArrayNestedUIValue : public ArrayUIValue, Count> + { + public: + void AddItem(T& Item) + { + // Seems like they have a helper function to apply NestedUIValue<> to the type + auto addr = dku::Hook::IDToAbs(135760); + auto func = reinterpret_cast>*, T&)>(addr); + func(&__super::m_ShuttleArray, Item); + } + }; +} diff --git a/Plugin/src/RE/UIDataShuttle.h b/Plugin/src/RE/UIDataShuttle.h new file mode 100644 index 00000000..a790653c --- /dev/null +++ b/Plugin/src/RE/UIDataShuttle.h @@ -0,0 +1,93 @@ +#pragma once + +#include + +namespace RE +{ + class IUIValue; + + class __declspec(novtable) UIDataShuttle + { + public: + UIDataShuttle() = default; + virtual ~UIDataShuttle() = default; // 00 + virtual void UIDataShuttle_01() = 0; // 01 + virtual void UIDataShuttle_02(IUIValue& UIValue) = 0; // 02 + virtual void UIDataShuttle_03() = 0; // 03 + virtual void UIDataShuttle_04() = 0; // 04 + virtual void UIDataShuttle_05() = 0; // 05 + virtual bool UIDataShuttle_06() = 0; // 06 + virtual bool UIDataShuttle_07() = 0; // 07 + + char _pad0[0x8]; // 08 + }; + static_assert(sizeof(UIDataShuttle) == 0x10); + + class __declspec(novtable) UIDataShuttleContainer + { + public: + UIDataShuttleContainer() = default; + virtual void UIDataShuttleContainer_00(); // 00 + virtual void UIDataShuttleContainer_01(); // 01 + virtual void UIDataShuttleContainer_02() = 0; // 02 + virtual void UIDataShuttleContainer_03() = 0; // 03 + virtual void UIDataShuttleContainer_04() = 0; // 04 + virtual void UIDataShuttleContainer_05(); // 05 + virtual void UIDataShuttleContainer_06(); // 06 + virtual void UIDataShuttleContainer_07(); // 07 + virtual void UIDataShuttleContainer_08() = 0; // 08 + virtual ~UIDataShuttleContainer() = default; // 09 + + char _pad0[0x8]; // 08 + }; + static_assert(sizeof(UIDataShuttleContainer) == 0x10); + + template + class __declspec(novtable) TUIDataShuttleContainerArray : public UIDataShuttleContainer + { + public: + TUIDataShuttleContainerArray() = default; + virtual void UIDataShuttleContainer_00() override; // 00 + virtual void UIDataShuttleContainer_01() override; // 01 + virtual void UIDataShuttleContainer_02() override; // 02 + virtual void UIDataShuttleContainer_03() override; // 03 + virtual void UIDataShuttleContainer_04() override; // 04 + virtual void UIDataShuttleContainer_05() override; // 05 + virtual void UIDataShuttleContainer_06() override; // 06 + virtual void UIDataShuttleContainer_07() override; // 07 + virtual void UIDataShuttleContainer_08() override; // 08 + virtual ~TUIDataShuttleContainerArray() override = default; // 09 + + T* m_ArrayBegin; // 10 + T* m_ArrayEnd; // 18 + char _pad20[0x30]; // 20 + + [[nodiscard]] auto Items() const noexcept + { + return std::span{ m_ArrayBegin, m_ArrayEnd }; + } + }; + //static_assert(sizeof(TUIDataShuttleContainerArray>) == 0x50); + + template + class __declspec(novtable) TUIDataShuttleContainerMap : public UIDataShuttleContainer + { + public: + TUIDataShuttleContainerMap() = default; + virtual void UIDataShuttleContainer_00() override; // 00 + virtual void UIDataShuttleContainer_02() override; // 02 + virtual void UIDataShuttleContainer_03() override; // 03 + virtual void UIDataShuttleContainer_04() override; // 04 + virtual void UIDataShuttleContainer_05() override; // 05 + virtual void UIDataShuttleContainer_06() override; // 06 + virtual void UIDataShuttleContainer_07() override; // 07 + virtual void UIDataShuttleContainer_08() override; // 08 + virtual ~TUIDataShuttleContainerMap() override = default; // 09 + virtual void TUIDataShuttleContainerMap_0A(); // 0A Identical to GetData(). Const version? + virtual T& GetData(); // 0A + + char _pad10[0x18]; // 10 + T m_Data; // 28 + }; + //static_assert((sizeof(TUIDataShuttleContainerMap>) - sizeof(TUIValue)) == 0x28); +} \ No newline at end of file diff --git a/Plugin/src/Settings.cpp b/Plugin/src/Settings.cpp new file mode 100644 index 00000000..5d7d10bb --- /dev/null +++ b/Plugin/src/Settings.cpp @@ -0,0 +1,359 @@ +#include "Settings.h" + +#include "Utils.h" + +namespace Settings +{ + std::string EnumStepper::GetStepperText(int32_t a_value) const + { + if (optionNames.size() > a_value) { + return optionNames[a_value]; + } + + return "Invalid"; + } + + std::string ValueStepper::GetStepperText(int32_t a_value) const + { + return std::to_string(GetValueFromStepper(a_value)); + } + + float Slider::GetSliderPercentage() const + { + return (value.get_data() - sliderMin) / (sliderMax - sliderMin); + } + + std::string Slider::GetSliderText() const + { + return std::format("{}{}", value.get_data(), suffix); + } + + float Slider::GetValueFromSlider(float a_percentage) const + { + return std::roundf(a_percentage * (sliderMax - sliderMin) + sliderMin); + } + + void Slider::SetValueFromSlider(float a_percentage) + { + *value = GetValueFromSlider(a_percentage); + } + + bool Main::InitCompatibility(RE::BGSSwapChainObject* a_swapChainObject) + { + // NOTE: this is called every time the game switches between windowed and borderless. + // It's not called again when we replace swapchain color space or format ourselves. + + swapChainObject = a_swapChainObject; + + // check for old NativeHDR being present + auto isModuleLoaded = [&](LPCWSTR a_moduleName) { + HMODULE hModule = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, a_moduleName, &hModule); + return hModule != nullptr; + }; + + constexpr std::array moduleNames = { L"NativeHDR.dll", L"NativeHDR.asi", L"NativeAutoHDR.dll", L"NativeAutoHDR.asi" }; + + for (auto& moduleName : moduleNames) { + if (isModuleLoaded(moduleName)) { + ERROR("An old version of the Native(Auto)HDR plugin is loaded. Please remove it while using Luma. It is a successor to the previous mod.") + return false; + } + } + + // check hdr support + RefreshHDRDisplaySupportState(); + + // enable hdr if off and display mode suggests it should be on + RefreshHDRDisplayEnableState(); + + // change display mode setting if it's hdr and hdr is not supported + if (!bIsHDRSupported && IsGameRenderingSetToHDR()) { + *DisplayMode.value = 0; + // No need to save, the user might have moved the game to an SDR display temporarily + } + + // autodetect peak brightness (only works reliably if HDR is enabled) + if (bIsHDREnabled && PeakBrightnessAutoDetected.get_data() == false) { + float detectedMaxLuminance; + if (Utils::GetHDRMaxLuminance(swapChainObject->swapChainInterface, detectedMaxLuminance)) { + *PeakBrightnessAutoDetected = true; + *PeakBrightness.value = std::max(detectedMaxLuminance, 80.f); + Save(); + } + } + + return true; + } + + void Main::RefreshHDRDisplaySupportState() + { + bIsHDRSupported = Utils::IsHDRSupported(swapChainObject->hwnd); + bIsHDREnabled = Utils::IsHDREnabled(swapChainObject->hwnd); + } + + void Main::RefreshHDRDisplayEnableState() + { + if (bIsHDRSupported && !bIsHDREnabled && IsGameRenderingSetToHDR()) { + bIsHDREnabled = Utils::SetHDREnabled(swapChainObject->hwnd); + } + // TODO: it would be nice to also force the "DisplayMode" to 0 here, and re-detect the peak brightness if "PeakBrightnessAutoDetected" was false, + // but it seems like it would run into thread safety problems + } + + bool Main::IsSDRForcedOnHDR() const + { + // The game will tonemap to SDR if this is true + return ForceSDROnHDR.value.get_data(); + } + + bool Main::IsDisplayModeSetToHDR() const + { + return DisplayMode.value.get_data() > 0; + } + + bool Main::IsGameRenderingSetToHDR() const + { + // The game will tonemap to SDR if this is false + return IsDisplayModeSetToHDR() && !IsSDRForcedOnHDR(); + } + + bool Main::IsFilmGrainTypeImproved() const { + return FilmGrainType.value.get_data() == 1; + } + + RE::BS_DXGI_FORMAT Main::GetDisplayModeFormat() const + { + if (IsSDRForcedOnHDR()) + return RE::BS_DXGI_FORMAT::BS_DXGI_FORMAT_R16G16B16A16_FLOAT; + switch (DisplayMode.value.get_data()) { + case 0: + case 1: + default: + return RE::BS_DXGI_FORMAT::BS_DXGI_FORMAT_R10G10B10A2_UNORM; + case 2: + return RE::BS_DXGI_FORMAT::BS_DXGI_FORMAT_R16G16B16A16_FLOAT; + } + } + + DXGI_COLOR_SPACE_TYPE Main::GetDisplayModeColorSpaceType() const + { + if (IsSDRForcedOnHDR()) + return DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; + switch (DisplayMode.value.get_data()) { + case 0: + default: + return DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + case 1: + return DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; + case 2: + return DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; + } + } + + void Main::OnDisplayModeChanged() + { + RefreshHDRDisplaySupportState(); + RefreshHDRDisplayEnableState(); + + const RE::BS_DXGI_FORMAT newFormat = GetDisplayModeFormat(); + Utils::SetBufferFormat(RE::Buffers::FrameBuffer, newFormat); + + swapChainObject->format = newFormat; + + // toggle vsync to force a swapchain recreation + Offsets::ToggleVsync(reinterpret_cast(*Offsets::unkToggleVsyncArg1Ptr + 0x8), *Offsets::bEnableVsync); + } + + void Main::GetShaderConstants(ShaderConstants& a_outShaderConstants) const + { + a_outShaderConstants.DisplayMode = IsSDRForcedOnHDR() ? -1 : static_cast(DisplayMode.value.get_data()); + a_outShaderConstants.PeakBrightness = static_cast(PeakBrightness.value.get_data()); + a_outShaderConstants.GamePaperWhite = static_cast(GamePaperWhite.value.get_data()); + a_outShaderConstants.UIPaperWhite = static_cast(UIPaperWhite.value.get_data()); + a_outShaderConstants.ExtendGamut = static_cast(ExtendGamut.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.Saturation = static_cast(Saturation.value.get_data() * 0.02f); // 0-100 to 0-2 + a_outShaderConstants.Contrast = static_cast(Contrast.value.get_data() * 0.02f); // 0-100 to 0-2 + a_outShaderConstants.LUTCorrectionStrength = static_cast(LUTCorrectionStrength.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.ColorGradingStrength = static_cast(ColorGradingStrength.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.GammaCorrectionStrength = static_cast(GammaCorrectionStrength.value.get_data() * 0.01f); // 0-100 to 0-1 + // There is no reason this wouldn't work in HDR, but for now it's disabled + a_outShaderConstants.SDRSecondaryBrightness = IsGameRenderingSetToHDR() ? 1.f : static_cast((SecondaryBrightness.value.get_data()) * 0.02f); // 0-100 to 0-2 + a_outShaderConstants.FilmGrainType = static_cast(FilmGrainType.value.get_data()); + a_outShaderConstants.FilmGrainCap = static_cast(FilmGrainCap.value.get_data()); + a_outShaderConstants.PostSharpen = static_cast(PostSharpen.value.get_data()); + a_outShaderConstants.bIsAtEndOfFrame = static_cast(bIsAtEndOfFrame.load()); + a_outShaderConstants.RuntimeMS = *Offsets::g_durationOfApplicationRunTimeMS; + a_outShaderConstants.DevSetting01 = static_cast(DevSetting01.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.DevSetting02 = static_cast(DevSetting02.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.DevSetting03 = static_cast(DevSetting03.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.DevSetting04 = static_cast(DevSetting04.value.get_data() * 0.01f); // 0-100 to 0-1 + a_outShaderConstants.DevSetting05 = static_cast(DevSetting05.value.get_data() * 0.01f); // 0-100 to 0-1 + } + + void Main::RegisterReshadeOverlay() + { + if (!bReshadeSettingsOverlayRegistered) { + HMODULE hModule = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(Main::GetSingleton()), &hModule); + if (hModule) { + if (reshade::register_addon(hModule)) { + reshade::register_overlay("Starfield Luma Settings", DrawReshadeSettings); + bReshadeSettingsOverlayRegistered = true; + } + } + } + } + + void Main::Load() noexcept + { + static std::once_flag ConfigInit; + std::call_once(ConfigInit, [&]() { + config.Bind(DisplayMode.value, DisplayMode.defaultValue); + config.Bind(ForceSDROnHDR.value, ForceSDROnHDR.defaultValue); + config.Bind(PeakBrightness.value, PeakBrightness.defaultValue); + config.Bind(GamePaperWhite.value, GamePaperWhite.defaultValue); + config.Bind(UIPaperWhite.value, UIPaperWhite.defaultValue); + config.Bind(ExtendGamut.value, ExtendGamut.defaultValue); + config.Bind(Saturation.value, Saturation.defaultValue); + config.Bind(Contrast.value, Contrast.defaultValue); + config.Bind(SecondaryBrightness.value, SecondaryBrightness.defaultValue); + config.Bind(LUTCorrectionStrength.value, LUTCorrectionStrength.defaultValue); + config.Bind(ColorGradingStrength.value, ColorGradingStrength.defaultValue); + config.Bind(GammaCorrectionStrength.value, GammaCorrectionStrength.defaultValue); + config.Bind(VanillaMenuLUTs.value, VanillaMenuLUTs.defaultValue); + config.Bind(FilmGrainType.value, FilmGrainType.defaultValue); + config.Bind(FilmGrainCap.value, FilmGrainCap.defaultValue); + config.Bind(PostSharpen.value, PostSharpen.defaultValue); + config.Bind(DevSetting01.value, DevSetting01.defaultValue); + config.Bind(DevSetting02.value, DevSetting02.defaultValue); + config.Bind(DevSetting03.value, DevSetting03.defaultValue); + config.Bind(DevSetting04.value, DevSetting04.defaultValue); + config.Bind(DevSetting05.value, DevSetting05.defaultValue); + config.Bind(RenderTargetsToUpgrade, + "ImageSpaceBuffer", + "ScaleformCompositeBuffer", + "SF_ColorBuffer", + "HDRImagespaceBuffer", + "ImageSpaceHalfResBuffer", + "ImageProcessColorTarget", + "ImageSpaceBufferB10G11R11", + "ImageSpaceBufferE5B9G9R9", + "TAA_idTech7HistoryColorTarget", + "EnvBRDF", + "ImageSpaceBufferR10G10B10A2" + //"NativeResolutionColorBuffer01", // issues on AMD + //"ColorBuffer01" + ); + config.Bind(PeakBrightnessAutoDetected, false); + }); + + config.Load(); + + INFO("Config loaded"sv) + } + + void Main::Save() noexcept + { + config.Generate(); + config.Write(); + } + + void Main::DrawReshadeSettings(reshade::api::effect_runtime*) + { + const auto settings = Settings::Main::GetSingleton(); + settings->DrawReshadeSettings(); + } + + bool Main::DrawReshadeCheckbox(Checkbox& a_checkbox) + { + bool tempValue = *a_checkbox.value; + if (ImGui::Checkbox(a_checkbox.name.c_str(), &tempValue)) { + *a_checkbox.value = tempValue; + Save(); + return true; + } + return false; + } + + bool Main::DrawReshadeEnumStepper(EnumStepper& a_stepper) + { + int tempValue = *a_stepper.value; + if (ImGui::SliderInt(a_stepper.name.c_str(), &tempValue, 0, a_stepper.GetNumOptions() - 1, a_stepper.GetStepperText(tempValue).c_str(), ImGuiSliderFlags_NoInput)) { + *a_stepper.value = tempValue; + Save(); + return true; + } + return false; + } + + bool Main::DrawReshadeValueStepper(ValueStepper& a_stepper) + { + int tempValue = *a_stepper.value; + if (ImGui::SliderInt(a_stepper.name.c_str(), &tempValue, a_stepper.minValue, a_stepper.maxValue, std::to_string(tempValue).c_str())) { + *a_stepper.value = tempValue; + Save(); + return true; + } + return false; + } + + bool Main::DrawReshadeSlider(Slider& a_slider) + { + float tempValue = *a_slider.value; + if (ImGui::SliderFloat(a_slider.name.c_str(), &tempValue, a_slider.sliderMin, a_slider.sliderMax, "%.0f")) { + *a_slider.value = tempValue; + Save(); + return true; + } + return false; + } + + void Main::DrawReshadeSettings() + { + const bool isSDRForcedOnHDR = IsSDRForcedOnHDR(); + const bool isGameRenderingSetToHDR = IsGameRenderingSetToHDR(); +#if DEVELOPMENT + if (IsHDRSupported()) { + // TODO: fix, these can often crash, Maybe we could find a way to push this change to the game main or rendering thread (they probably have a func for it), + // or simply delay the application in our code until we get another call from the thread where this can be called (e.g. settings changed callbacks). + if (DrawReshadeEnumStepper(DisplayMode)) { + OnDisplayModeChanged(); + } + if (DrawReshadeCheckbox(ForceSDROnHDR)) { + OnDisplayModeChanged(); + } + } +#endif + + if (isGameRenderingSetToHDR) { + DrawReshadeValueStepper(PeakBrightness); + DrawReshadeValueStepper(GamePaperWhite); + DrawReshadeValueStepper(UIPaperWhite); + DrawReshadeSlider(ExtendGamut); + DrawReshadeSlider(Saturation); + DrawReshadeSlider(Contrast); + } + else { + if (isSDRForcedOnHDR) { + DrawReshadeValueStepper(GamePaperWhite); + } + DrawReshadeSlider(SecondaryBrightness); + } + DrawReshadeSlider(GammaCorrectionStrength); + DrawReshadeSlider(LUTCorrectionStrength); + DrawReshadeSlider(ColorGradingStrength); + DrawReshadeCheckbox(VanillaMenuLUTs); + DrawReshadeEnumStepper(FilmGrainType); + DrawReshadeSlider(FilmGrainCap); + DrawReshadeCheckbox(PostSharpen); + +#if DEVELOPMENT + DrawReshadeSlider(DevSetting01); + DrawReshadeSlider(DevSetting02); + DrawReshadeSlider(DevSetting03); + DrawReshadeSlider(DevSetting04); + DrawReshadeSlider(DevSetting05); +#endif + } +} diff --git a/Plugin/src/Settings.h b/Plugin/src/Settings.h new file mode 100644 index 00000000..4c2d86b2 --- /dev/null +++ b/Plugin/src/Settings.h @@ -0,0 +1,352 @@ +#pragma once +#include "Offsets.h" +#include "DKUtil/Config.hpp" +#include "RE/Buffers.h" +#include "reshade/reshade.hpp" + +#include + +// TODO: set to false in release builds (use the build configuation to automatically define it) +#define DEVELOPMENT 0 + +namespace Settings +{ + using namespace DKUtil::Alias; + + enum class SettingID : unsigned int + { + kSTART = 600, + + kDisplayMode, + kForceSDROnHDR, + kHDR_PeakBrightness, + kHDR_GamePaperWhite, + kHDR_UIPaperWhite, + kHDR_ExtendGamut, + kHDR_Contrast, + kHDR_Saturation, + kLUTCorrectionStrength, + kColorGradingStrength, + kGammaCorrectionStrength, + kSecondaryBrightness, + kVanillaMenuLUTs, + kFilmGrainType, + kFilmGrainCap, + kPostSharpen, + + kEND, + + kDevSetting01, + kDevSetting02, + kDevSetting03, + kDevSetting04, + kDevSetting05, + }; + + struct Setting + { + SettingID id; + std::string name; + std::string description; + }; + + struct Checkbox : Setting + { + Boolean value; + bool defaultValue; + }; + + struct Stepper : Setting + { + Integer value; + int32_t defaultValue; + + Stepper(SettingID a_id, const std::string& a_name, const std::string& a_description, const std::string& a_key, const std::string& a_section, int32_t a_defaultValue) : + Setting{ a_id, a_name, a_description }, value{ a_key, a_section }, defaultValue(a_defaultValue) {} + + virtual ~Stepper() = default; + + virtual std::string GetStepperText(int32_t a_value) const = 0; + virtual int32_t GetNumOptions() const = 0; + virtual int32_t GetValueFromStepper(int32_t a_value) const = 0; + virtual int32_t GetCurrentStepFromValue() const = 0; + virtual void SetValueFromStepper(int32_t a_value) = 0; + }; + + struct EnumStepper : Stepper + { + std::vector optionNames; + + EnumStepper(SettingID a_id, const std::string& a_name, const std::string& a_description, const std::string& a_key, const std::string& a_section, int32_t a_defaultValue, const std::vector& a_optionNames) : + Stepper{ a_id, a_name, a_description, a_key, a_section, a_defaultValue }, optionNames(a_optionNames) {} + + std::string GetStepperText(int32_t a_value) const override; + int32_t GetNumOptions() const override{ return optionNames.size(); } + int32_t GetValueFromStepper(int32_t a_value) const override { return a_value; } + int32_t GetCurrentStepFromValue() const override { return value.get_data(); } + void SetValueFromStepper(int32_t a_value) override { *value = a_value; } + }; + + struct ValueStepper : Stepper + { + int32_t minValue; + int32_t maxValue; + int32_t stepSize; + + ValueStepper(SettingID a_id, const std::string& a_name, const std::string& a_description, const std::string& a_key, const std::string& a_section, int32_t a_defaultValue, int32_t a_minValue, int32_t a_maxValue, int32_t a_stepSize) : + Stepper{ a_id, a_name, a_description, a_key, a_section, a_defaultValue }, minValue(a_minValue), maxValue(a_maxValue), stepSize(a_stepSize) {} + + std::string GetStepperText(int32_t a_value) const override; + int32_t GetNumOptions() const override { return (maxValue - minValue) / stepSize + 1; } + int32_t GetValueFromStepper(int32_t a_value) const override { return a_value * stepSize + minValue; } + int32_t GetCurrentStepFromValue() const override { return (value.get_data() - minValue) / stepSize; } + void SetValueFromStepper(int32_t a_value) override { *value = GetValueFromStepper(a_value); } + }; + + struct Slider : Setting + { + Double value; + float defaultValue; + float sliderMin; + float sliderMax; + std::string suffix = ""; + + float GetSliderPercentage() const; + std::string GetSliderText() const; + float GetValueFromSlider(float a_percentage) const; + void SetValueFromSlider(float a_percentage); + }; + + // Has to match StructHdrDllPluginConstants in HLSL. + // Bools are set as uint to avoid padding inconsistencies between c++ and hlsl. + struct ShaderConstants + { + int32_t DisplayMode; + float PeakBrightness; + float GamePaperWhite; + float UIPaperWhite; + float ExtendGamut; + float Saturation; + float Contrast; + float LUTCorrectionStrength; + float ColorGradingStrength; + float GammaCorrectionStrength; + float SDRSecondaryBrightness; + uint32_t FilmGrainType; + float FilmGrainCap; + uint32_t PostSharpen; + uint32_t bIsAtEndOfFrame; + uint32_t RuntimeMS; + float DevSetting01; + float DevSetting02; + float DevSetting03; + float DevSetting04; + float DevSetting05; + }; + static inline uint32_t shaderConstantsSize = 19; + + class Main : public DKUtil::model::Singleton
+ { + public: + EnumStepper DisplayMode { + SettingID::kDisplayMode, + "Display Mode", + "Sets the game's display mode between SDR (Gamma 2.2 Rec.709), HDR10 BT.2020 PQ, or HDR scRGB.\n\nHDR scRGB offers the highest quality but is not compatible with technologies like DLSS Frame Generation.", + "DisplayMode", "Main", + 0, + { "SDR", "HDR10", "HDR scRGB" } + }; + Checkbox ForceSDROnHDR{ + SettingID::kForceSDROnHDR, + "Force SDR on scRGB HDR", + "When enabled, the game will still tonemap to SDR but output on an HDR scRGB swapchain.", + { "ForceSDROnHDR", "Dev" }, + false + }; + ValueStepper PeakBrightness{ + SettingID::kHDR_PeakBrightness, + "Peak Brightness", + "Sets the peak brightness in HDR modes, this should match your display peak brightness.\nThis will not influence the game average brightness.", + "PeakBrightness", "HDR", + 1000, + 80, + 10000, + 10 + }; + ValueStepper GamePaperWhite{ + SettingID::kHDR_GamePaperWhite, + "Game Paper White", + "Sets the game paper white brightness in HDR modes.\nThis influences the average brightness of the image without affecting the peak brightness.\nDefault is 200.", + "GamePaperWhite", "HDR", + 200, /*ITU reference default is 203 but we don't want to confuse users*/ + 80, + 500, + 10 + }; + ValueStepper UIPaperWhite{ + SettingID::kHDR_UIPaperWhite, + "UI Paper White", + "Sets the UI paper white brightness in HDR modes.\nDefault is 200.", + "UIPaperWhite", "HDR", + 200, /*ITU reference default is 203 but we don't want to confuse users*/ + 80, + 500, + 10 + }; + Slider ExtendGamut{ + SettingID::kHDR_ExtendGamut, + "Extend Gamut", + "Shifts bright saturated colors from SDR to HDR, essentially acting as a \"smart\" saturation. Neutral at 0\%.", + { "Saturation", "HDR" }, + 50.f, + 0.f, + 100.f, + "%" + }; + Slider Saturation{ + SettingID::kHDR_Saturation, + "Saturation", + "Sets the saturation strength in HDR modes. Neutral default at 50\%.", + { "Saturation", "HDR" }, + 50.f, + 0.f, + 100.f, + "%" + }; + Slider Contrast{ + SettingID::kHDR_Contrast, + "Contrast", + "Sets the contrast strength in HDR modes. Neutral default at 50\%.", + { "Contrast", "HDR" }, + 50.f, + 0.f, + 100.f, + "%" + }; + Slider SecondaryBrightness{ + SettingID::kSecondaryBrightness, + "Brightness", + "Modulates the brightness in SDR modes. Neutral default at 50\%.", + { "SecondaryBrightness", "Main" }, + 50.f, + 0.f, + 100.f, + "%" + }; + Slider LUTCorrectionStrength{ + SettingID::kLUTCorrectionStrength, + "LUT Correction Strength", + "Sets the LUT correction (normalization) strength. This removes the fogginess from the game vanilla LUTs.", + { "LUTCorrectionStrength", "Main" }, + 100.f, + 0.f, + 100.f, + "%" + }; + Slider ColorGradingStrength{ + SettingID::kColorGradingStrength, + "Color Grading Strength", + "Sets the color grading strength - how much the LUTs influence the final image.", + { "ColorGradingStrength", "Main" }, + 100.f, + 0.f, + 100.f, + "%" + }; + Slider GammaCorrectionStrength{ + SettingID::kGammaCorrectionStrength, + "Gamma Correction Strength", + "Sets the gamma correction strength. The game used the sRGB gamma formula but was calibrated on gamma 2.2 displays. Only applies if \"Color Grading\" is enabled. 100\% should be closer to the original look.", + { "GammaCorrectionStrength", "Main" }, + 100.f, + 0.f, + 100.f, + "%" + }; + Checkbox VanillaMenuLUTs{ + SettingID::kVanillaMenuLUTs, + "Vanilla Menu LUTs", + "When enabled, menu LUTs will be unaffected by the \"LUT Correction Strength\" and \"Color Grading Strength\" settings.", + { "VanillaMenuLUTs", "Main" }, + true + }; + EnumStepper FilmGrainType{ + SettingID::kFilmGrainType, + "Film Grain Type", + "Sets the film grain type. Luma offers an improved version, we suggest setting the strength to 50\% for it.", + "FilmGrainType", "Main", + 1, + { "Vanilla", "Improved" } + }; + Slider FilmGrainCap{ + SettingID::kFilmGrainCap, + "Film Grain Cap", + "Sets a framerate cap on the improved film grain. Set to 0 for uncapped framerate.", + { "FilmGrainCap", "Main" }, + 24.f, + 0.f, + 100.f, + "fps" + }; + Checkbox PostSharpen{ + SettingID::kPostSharpen, + "Post Sharpening", + "Toggles the game default post sharpen pass. By default this was running after other sharpening or upscaling methods, and was always forced on.", + { "PostSharpen", "Main" }, + true + }; + Slider DevSetting01{ SettingID::kDevSetting01, "DevSetting01", "Development setting", { "DevSetting01", "Dev" }, 0.f, 0.f, 100.f }; + Slider DevSetting02{ SettingID::kDevSetting02, "DevSetting02", "Development setting", { "DevSetting02", "Dev" }, 0.f, 0.f, 100.f }; + Slider DevSetting03{ SettingID::kDevSetting03, "DevSetting03", "Development setting", { "DevSetting03", "Dev" }, 0.f, 0.f, 100.f }; + Slider DevSetting04{ SettingID::kDevSetting04, "DevSetting04", "Development setting", { "DevSetting04", "Dev" }, 50.f, 0.f, 100.f }; + Slider DevSetting05{ SettingID::kDevSetting05, "DevSetting05", "Development setting", { "DevSetting05", "Dev" }, 50.f, 0.f, 100.f }; + String RenderTargetsToUpgrade{ "RenderTargetsToUpgrade", "RenderTargets" }; + + Boolean PeakBrightnessAutoDetected { "PeakBrightnessAutoDetected", "HDR" }; + + bool InitCompatibility(RE::BGSSwapChainObject* a_swapChainObject); + void RefreshHDRDisplaySupportState(); + void RefreshHDRDisplayEnableState(); + + bool IsHDRSupported() const { return bIsHDRSupported; } + bool IsSDRForcedOnHDR() const; + bool IsDisplayModeSetToHDR() const; + bool IsGameRenderingSetToHDR() const; + bool IsFilmGrainTypeImproved() const; + + + void SetAtEndOfFrame(bool a_bIsAtEndOfFrame) { bIsAtEndOfFrame.store(a_bIsAtEndOfFrame); } + + RE::BS_DXGI_FORMAT GetDisplayModeFormat() const; + DXGI_COLOR_SPACE_TYPE GetDisplayModeColorSpaceType() const; + + void OnDisplayModeChanged(); + + void GetShaderConstants(ShaderConstants& a_outShaderConstants) const; + + void RegisterReshadeOverlay(); + + void Load() noexcept; + void Save() noexcept; + + static void DrawReshadeSettings(reshade::api::effect_runtime*); + + private: + TomlConfig config = COMPILE_PROXY("Luma.toml"sv); + std::atomic_bool bIsAtEndOfFrame = false; + std::atomic_bool bIsHDRSupported = false; + std::atomic_bool bIsHDREnabled = false; + + RE::BGSSwapChainObject* swapChainObject = nullptr; + + bool bReshadeSettingsOverlayRegistered = false; + + bool DrawReshadeCheckbox(Checkbox& a_checkbox); + bool DrawReshadeEnumStepper(EnumStepper& a_stepper); + bool DrawReshadeValueStepper(ValueStepper& a_stepper); + bool DrawReshadeSlider(Slider& a_slider); + void DrawReshadeSettings(); + }; + + +} diff --git a/Plugin/src/Utils.cpp b/Plugin/src/Utils.cpp new file mode 100644 index 00000000..2929a211 --- /dev/null +++ b/Plugin/src/Utils.cpp @@ -0,0 +1,345 @@ +#include "Utils.h" + +#include "Offsets.h" + +namespace Utils +{ + std::unordered_map GetDXGIFormatNameMap() + { + std::unordered_map formatNames; + + formatNames[DXGI_FORMAT_UNKNOWN] = "DXGI_FORMAT_UNKNOWN"; + formatNames[DXGI_FORMAT_R32G32B32A32_TYPELESS] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; + formatNames[DXGI_FORMAT_R32G32B32A32_FLOAT] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; + formatNames[DXGI_FORMAT_R32G32B32A32_UINT] = "DXGI_FORMAT_R32G32B32A32_UINT"; + formatNames[DXGI_FORMAT_R32G32B32A32_SINT] = "DXGI_FORMAT_R32G32B32A32_SINT"; + formatNames[DXGI_FORMAT_R32G32B32_TYPELESS] = "DXGI_FORMAT_R32G32B32_TYPELESS"; + formatNames[DXGI_FORMAT_R32G32B32_FLOAT] = "DXGI_FORMAT_R32G32B32_FLOAT"; + formatNames[DXGI_FORMAT_R32G32B32_UINT] = "DXGI_FORMAT_R32G32B32_UINT"; + formatNames[DXGI_FORMAT_R32G32B32_SINT] = "DXGI_FORMAT_R32G32B32_SINT"; + formatNames[DXGI_FORMAT_R16G16B16A16_TYPELESS] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; + formatNames[DXGI_FORMAT_R16G16B16A16_FLOAT] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; + formatNames[DXGI_FORMAT_R16G16B16A16_UNORM] = "DXGI_FORMAT_R16G16B16A16_UNORM"; + formatNames[DXGI_FORMAT_R16G16B16A16_UINT] = "DXGI_FORMAT_R16G16B16A16_UINT"; + formatNames[DXGI_FORMAT_R16G16B16A16_SNORM] = "DXGI_FORMAT_R16G16B16A16_SNORM"; + formatNames[DXGI_FORMAT_R16G16B16A16_SINT] = "DXGI_FORMAT_R16G16B16A16_SINT"; + formatNames[DXGI_FORMAT_R32G32_TYPELESS] = "DXGI_FORMAT_R32G32_TYPELESS"; + formatNames[DXGI_FORMAT_R32G32_FLOAT] = "DXGI_FORMAT_R32G32_FLOAT"; + formatNames[DXGI_FORMAT_R32G32_UINT] = "DXGI_FORMAT_R32G32_UINT"; + formatNames[DXGI_FORMAT_R32G32_SINT] = "DXGI_FORMAT_R32G32_SINT"; + formatNames[DXGI_FORMAT_R32G8X24_TYPELESS] = "DXGI_FORMAT_R32G8X24_TYPELESS"; + formatNames[DXGI_FORMAT_D32_FLOAT_S8X24_UINT] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; + formatNames[DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; + formatNames[DXGI_FORMAT_X32_TYPELESS_G8X24_UINT] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; + formatNames[DXGI_FORMAT_R10G10B10A2_TYPELESS] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; + formatNames[DXGI_FORMAT_R10G10B10A2_UNORM] = "DXGI_FORMAT_R10G10B10A2_UNORM"; + formatNames[DXGI_FORMAT_R10G10B10A2_UINT] = "DXGI_FORMAT_R10G10B10A2_UINT"; + formatNames[DXGI_FORMAT_R11G11B10_FLOAT] = "DXGI_FORMAT_R11G11B10_FLOAT"; + formatNames[DXGI_FORMAT_R8G8B8A8_TYPELESS] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; + formatNames[DXGI_FORMAT_R8G8B8A8_UNORM] = "DXGI_FORMAT_R8G8B8A8_UNORM"; + formatNames[DXGI_FORMAT_R8G8B8A8_UNORM_SRGB] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; + formatNames[DXGI_FORMAT_R8G8B8A8_UINT] = "DXGI_FORMAT_R8G8B8A8_UINT"; + formatNames[DXGI_FORMAT_R8G8B8A8_SNORM] = "DXGI_FORMAT_R8G8B8A8_SNORM"; + formatNames[DXGI_FORMAT_R8G8B8A8_SINT] = "DXGI_FORMAT_R8G8B8A8_SINT"; + formatNames[DXGI_FORMAT_R16G16_TYPELESS] = "DXGI_FORMAT_R16G16_TYPELESS"; + formatNames[DXGI_FORMAT_R16G16_FLOAT] = "DXGI_FORMAT_R16G16_FLOAT"; + formatNames[DXGI_FORMAT_R16G16_UNORM] = "DXGI_FORMAT_R16G16_UNORM"; + formatNames[DXGI_FORMAT_R16G16_UINT] = "DXGI_FORMAT_R16G16_UINT"; + formatNames[DXGI_FORMAT_R16G16_SNORM] = "DXGI_FORMAT_R16G16_SNORM"; + formatNames[DXGI_FORMAT_R16G16_SINT] = "DXGI_FORMAT_R16G16_SINT"; + formatNames[DXGI_FORMAT_R32_TYPELESS] = "DXGI_FORMAT_R32_TYPELESS"; + formatNames[DXGI_FORMAT_D32_FLOAT] = "DXGI_FORMAT_D32_FLOAT"; + formatNames[DXGI_FORMAT_R32_FLOAT] = "DXGI_FORMAT_R32_FLOAT"; + formatNames[DXGI_FORMAT_R32_UINT] = "DXGI_FORMAT_R32_UINT"; + formatNames[DXGI_FORMAT_R32_SINT] = "DXGI_FORMAT_R32_SINT"; + formatNames[DXGI_FORMAT_R24G8_TYPELESS] = "DXGI_FORMAT_R24G8_TYPELESS"; + formatNames[DXGI_FORMAT_D24_UNORM_S8_UINT] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; + formatNames[DXGI_FORMAT_R24_UNORM_X8_TYPELESS] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; + formatNames[DXGI_FORMAT_X24_TYPELESS_G8_UINT] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; + formatNames[DXGI_FORMAT_R8G8_TYPELESS] = "DXGI_FORMAT_R8G8_TYPELESS"; + formatNames[DXGI_FORMAT_R8G8_UNORM] = "DXGI_FORMAT_R8G8_UNORM"; + formatNames[DXGI_FORMAT_R8G8_UINT] = "DXGI_FORMAT_R8G8_UINT"; + formatNames[DXGI_FORMAT_R8G8_SNORM] = "DXGI_FORMAT_R8G8_SNORM"; + formatNames[DXGI_FORMAT_R8G8_SINT] = "DXGI_FORMAT_R8G8_SINT"; + formatNames[DXGI_FORMAT_R16_TYPELESS] = "DXGI_FORMAT_R16_TYPELESS"; + formatNames[DXGI_FORMAT_R16_FLOAT] = "DXGI_FORMAT_R16_FLOAT"; + formatNames[DXGI_FORMAT_D16_UNORM] = "DXGI_FORMAT_D16_UNORM"; + formatNames[DXGI_FORMAT_R16_UNORM] = "DXGI_FORMAT_R16_UNORM"; + formatNames[DXGI_FORMAT_R16_UINT] = "DXGI_FORMAT_R16_UINT"; + formatNames[DXGI_FORMAT_R16_SNORM] = "DXGI_FORMAT_R16_SNORM"; + formatNames[DXGI_FORMAT_R16_SINT] = "DXGI_FORMAT_R16_SINT"; + formatNames[DXGI_FORMAT_R8_TYPELESS] = "DXGI_FORMAT_R8_TYPELESS"; + formatNames[DXGI_FORMAT_R8_UNORM] = "DXGI_FORMAT_R8_UNORM"; + formatNames[DXGI_FORMAT_R8_UINT] = "DXGI_FORMAT_R8_UINT"; + formatNames[DXGI_FORMAT_R8_SNORM] = "DXGI_FORMAT_R8_SNORM"; + formatNames[DXGI_FORMAT_R8_SINT] = "DXGI_FORMAT_R8_SINT"; + formatNames[DXGI_FORMAT_A8_UNORM] = "DXGI_FORMAT_A8_UNORM"; + formatNames[DXGI_FORMAT_R1_UNORM] = "DXGI_FORMAT_R1_UNORM"; + formatNames[DXGI_FORMAT_R9G9B9E5_SHAREDEXP] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; + formatNames[DXGI_FORMAT_R8G8_B8G8_UNORM] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; + formatNames[DXGI_FORMAT_G8R8_G8B8_UNORM] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; + formatNames[DXGI_FORMAT_BC1_TYPELESS] = "DXGI_FORMAT_BC1_TYPELESS"; + formatNames[DXGI_FORMAT_BC1_UNORM] = "DXGI_FORMAT_BC1_UNORM"; + formatNames[DXGI_FORMAT_BC1_UNORM_SRGB] = "DXGI_FORMAT_BC1_UNORM_SRGB"; + formatNames[DXGI_FORMAT_BC2_TYPELESS] = "DXGI_FORMAT_BC2_TYPELESS"; + formatNames[DXGI_FORMAT_BC2_UNORM] = "DXGI_FORMAT_BC2_UNORM"; + formatNames[DXGI_FORMAT_BC2_UNORM_SRGB] = "DXGI_FORMAT_BC2_UNORM_SRGB"; + formatNames[DXGI_FORMAT_BC3_TYPELESS] = "DXGI_FORMAT_BC3_TYPELESS"; + formatNames[DXGI_FORMAT_BC3_UNORM] = "DXGI_FORMAT_BC3_UNORM"; + formatNames[DXGI_FORMAT_BC3_UNORM_SRGB] = "DXGI_FORMAT_BC3_UNORM_SRGB"; + formatNames[DXGI_FORMAT_BC4_TYPELESS] = "DXGI_FORMAT_BC4_TYPELESS"; + formatNames[DXGI_FORMAT_BC4_UNORM] = "DXGI_FORMAT_BC4_UNORM"; + formatNames[DXGI_FORMAT_BC4_SNORM] = "DXGI_FORMAT_BC4_SNORM"; + formatNames[DXGI_FORMAT_BC5_TYPELESS] = "DXGI_FORMAT_BC5_TYPELESS"; + formatNames[DXGI_FORMAT_BC5_UNORM] = "DXGI_FORMAT_BC5_UNORM"; + formatNames[DXGI_FORMAT_BC5_SNORM] = "DXGI_FORMAT_BC5_SNORM"; + formatNames[DXGI_FORMAT_B5G6R5_UNORM] = "DXGI_FORMAT_B5G6R5_UNORM"; + formatNames[DXGI_FORMAT_B5G5R5A1_UNORM] = "DXGI_FORMAT_B5G5R5A1_UNORM"; + formatNames[DXGI_FORMAT_B8G8R8A8_UNORM] = "DXGI_FORMAT_B8G8R8A8_UNORM"; + formatNames[DXGI_FORMAT_B8G8R8X8_UNORM] = "DXGI_FORMAT_B8G8R8X8_UNORM"; + formatNames[DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; + formatNames[DXGI_FORMAT_B8G8R8A8_TYPELESS] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; + formatNames[DXGI_FORMAT_B8G8R8A8_UNORM_SRGB] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; + formatNames[DXGI_FORMAT_B8G8R8X8_TYPELESS] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; + formatNames[DXGI_FORMAT_B8G8R8X8_UNORM_SRGB] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; + formatNames[DXGI_FORMAT_BC6H_TYPELESS] = "DXGI_FORMAT_BC6H_TYPELESS"; + formatNames[DXGI_FORMAT_BC6H_UF16] = "DXGI_FORMAT_BC6H_UF16"; + formatNames[DXGI_FORMAT_BC6H_SF16] = "DXGI_FORMAT_BC6H_SF16"; + formatNames[DXGI_FORMAT_BC7_TYPELESS] = "DXGI_FORMAT_BC7_TYPELESS"; + formatNames[DXGI_FORMAT_BC7_UNORM] = "DXGI_FORMAT_BC7_UNORM"; + formatNames[DXGI_FORMAT_BC7_UNORM_SRGB] = "DXGI_FORMAT_BC7_UNORM_SRGB"; + formatNames[DXGI_FORMAT_AYUV] = "DXGI_FORMAT_AYUV"; + formatNames[DXGI_FORMAT_Y410] = "DXGI_FORMAT_Y410"; + formatNames[DXGI_FORMAT_Y416] = "DXGI_FORMAT_Y416"; + formatNames[DXGI_FORMAT_NV12] = "DXGI_FORMAT_NV12"; + formatNames[DXGI_FORMAT_P010] = "DXGI_FORMAT_P010"; + formatNames[DXGI_FORMAT_P016] = "DXGI_FORMAT_P016"; + formatNames[DXGI_FORMAT_420_OPAQUE] = "DXGI_FORMAT_420_OPAQUE"; + formatNames[DXGI_FORMAT_YUY2] = "DXGI_FORMAT_YUY2"; + formatNames[DXGI_FORMAT_Y210] = "DXGI_FORMAT_Y210"; + formatNames[DXGI_FORMAT_Y216] = "DXGI_FORMAT_Y216"; + formatNames[DXGI_FORMAT_NV11] = "DXGI_FORMAT_NV11"; + formatNames[DXGI_FORMAT_AI44] = "DXGI_FORMAT_AI44"; + formatNames[DXGI_FORMAT_IA44] = "DXGI_FORMAT_IA44"; + formatNames[DXGI_FORMAT_P8] = "DXGI_FORMAT_P8"; + formatNames[DXGI_FORMAT_A8P8] = "DXGI_FORMAT_A8P8"; + formatNames[DXGI_FORMAT_B4G4R4A4_UNORM] = "DXGI_FORMAT_B4G4R4A4_UNORM"; + formatNames[DXGI_FORMAT_P208] = "DXGI_FORMAT_P208"; + formatNames[DXGI_FORMAT_V208] = "DXGI_FORMAT_V208"; + formatNames[DXGI_FORMAT_V408] = "DXGI_FORMAT_V408"; + formatNames[DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; + formatNames[DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; + + return formatNames; + } + + void LogFormats() + { + auto formatNames = GetDXGIFormatNameMap(); + + for (int i = 0; i < 128; ++i) { + const auto format = Offsets::GetDXGIFormat(static_cast(i)); + INFO("{} - {}", i, formatNames[format]) + } + } + + void LogBuffers() + { + INFO("===LOGGING BUFFERS===") + + std::string logString = "Index, Buffer name, DXGI_FORMAT\n"; + + auto formatNames = GetDXGIFormatNameMap(); + for (int i = 0; i < Offsets::bufferArray->size(); ++i) { + const auto& bufferDefinition = (*Offsets::bufferArray)[i]; + const auto dxgiFormat = Offsets::GetDXGIFormat(bufferDefinition->format); + logString.append(fmt::format("{:3}, {}, {}\n", i, bufferDefinition->bufferName, formatNames[dxgiFormat])); + } + + INFO(logString) + INFO("===END LOGGING BUFFERS===") + } + + void SetBufferFormat(RE::BufferDefinition* a_buffer, RE::BS_DXGI_FORMAT a_format) + { + if (!a_buffer) { + return; + } + + auto formatNames = Utils::GetDXGIFormatNameMap(); + INFO("{} - changing from format {} to {}", a_buffer->bufferName, formatNames[Offsets::GetDXGIFormat(a_buffer->format)], formatNames[Offsets::GetDXGIFormat(a_format)]) + a_buffer->format = a_format; + } + + void SetBufferFormat(RE::Buffers a_buffer, RE::BS_DXGI_FORMAT a_format) + { + const auto buffer = (*Offsets::bufferArray)[static_cast(a_buffer)]; + SetBufferFormat(buffer, a_format); + } + + RE::BS_DXGI_FORMAT GetBufferFormat(RE::Buffers a_buffer) + { + const auto buffer = (*Offsets::bufferArray)[static_cast(a_buffer)]; + return buffer->format; + } + + bool ShouldCorrectLUTs() + { + const auto ui = *Offsets::uiPtr; + // make sure we do indeed correct luts in these menus, even though DataMenu is in the menu stack + if (Offsets::UI_IsMenuOpen(ui, "GalaxyStarMapMenu")) { + return true; + } + if (Offsets::UI_IsMenuOpen(ui, "SpaceshipEditorMenu")) { + return true; + } + + // don't correct luts while we're in menus that have a LUT + if (Offsets::UI_IsMenuOpen(ui, "DataMenu")) { + return false; + } + if (Offsets::UI_IsMenuOpen(ui, "InventoryMenu")) { + return false; + } + if (Offsets::UI_IsMenuOpen(ui, "ContainerMenu")) { + return false; + } + if (Offsets::UI_IsMenuOpen(ui, "BarterMenu")) { + return false; + } + + return true; + } + + bool IsInPauseMenu() + { + const auto ui = *Offsets::uiPtr; + if (Offsets::UI_IsMenuOpen(ui, "PauseMenu")) { + return true; + } + return false; + } + + bool IsInMainMenu() + { + const auto ui = *Offsets::uiPtr; + if (Offsets::UI_IsMenuOpen(ui, "MainMenu")) { + return true; + } + return false; + } + + // Only works if HDR is enaged on the monitor that contains the swapchain + bool GetHDRMaxLuminance(IDXGISwapChain3* a_swapChainInterface, float& a_outMaxLuminance) + { + IDXGIOutput* output = nullptr; + if (FAILED(a_swapChainInterface->GetContainingOutput(&output))) { + return false; + } + + IDXGIOutput6* output6 = nullptr; + if (FAILED(output->QueryInterface(&output6))) { + return false; + } + + DXGI_OUTPUT_DESC1 desc1; + if (FAILED(output6->GetDesc1(&desc1))) { + return false; + } + + a_outMaxLuminance = desc1.MaxLuminance; + return true; + } + + bool GetDisplayConfigPathInfo(HWND a_hwnd, DISPLAYCONFIG_PATH_INFO& a_outPathInfo) + { + uint32_t pathCount, modeCount; + if (ERROR_SUCCESS != GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &pathCount, &modeCount)) { + return false; + } + + std::vector paths(pathCount); + std::vector modes(modeCount); + if (ERROR_SUCCESS != QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &pathCount, paths.data(), &modeCount, modes.data(), nullptr)) { + return false; + } + + const HMONITOR monitorFromWindow = MonitorFromWindow(a_hwnd, MONITOR_DEFAULTTONULL); + for (auto& pathInfo : paths) { + if (pathInfo.flags & DISPLAYCONFIG_PATH_ACTIVE && pathInfo.sourceInfo.statusFlags & DISPLAYCONFIG_SOURCE_IN_USE) { + const bool bVirtual = pathInfo.flags & DISPLAYCONFIG_PATH_SUPPORT_VIRTUAL_MODE; + const DISPLAYCONFIG_SOURCE_MODE& sourceMode = modes[bVirtual ? pathInfo.sourceInfo.sourceModeInfoIdx : pathInfo.sourceInfo.modeInfoIdx].sourceMode; + + RECT rect { sourceMode.position.x, sourceMode.position.y, sourceMode.position.x + sourceMode.width, sourceMode.position.y + sourceMode.height }; + if (!IsRectEmpty(&rect)) { + const HMONITOR monitorFromMode = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL); + if (monitorFromMode != nullptr && monitorFromMode == monitorFromWindow) { + a_outPathInfo = pathInfo; + return true; + } + } + } + } + + return false; + } + + bool GetColorInfo(HWND a_hwnd, DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO& a_outColorInfo) + { + DISPLAYCONFIG_PATH_INFO pathInfo{}; + if (GetDisplayConfigPathInfo(a_hwnd, pathInfo)) { + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO colorInfo{}; + colorInfo.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO; + colorInfo.header.size = sizeof(colorInfo); + colorInfo.header.adapterId = pathInfo.targetInfo.adapterId; + colorInfo.header.id = pathInfo.targetInfo.id; + auto result = DisplayConfigGetDeviceInfo(&colorInfo.header); + if (result == ERROR_SUCCESS) { + a_outColorInfo = colorInfo; + return true; + } + } + + return false; + } + + bool IsHDRSupported(HWND a_hwnd) + { + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO colorInfo{}; + if (GetColorInfo(a_hwnd, colorInfo)) { + return colorInfo.advancedColorSupported; + } + + return false; + } + + bool IsHDREnabled(HWND a_hwnd) + { + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO colorInfo{}; + if (GetColorInfo(a_hwnd, colorInfo)) { + return colorInfo.advancedColorEnabled; + } + + return false; + } + + bool SetHDREnabled(HWND a_hwnd) + { + DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO colorInfo{}; + if (GetColorInfo(a_hwnd, colorInfo)) { + if (colorInfo.advancedColorSupported && !colorInfo.advancedColorEnabled) { + DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE setColorState{}; + setColorState.header.type = DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE; + setColorState.header.size = sizeof(setColorState); + setColorState.header.adapterId = colorInfo.header.adapterId; + setColorState.header.id = colorInfo.header.id; + setColorState.enableAdvancedColor = true; + return ERROR_SUCCESS == DisplayConfigSetDeviceInfo(&setColorState.header); + } + + return colorInfo.advancedColorEnabled; + } + + return false; + } +} diff --git a/Plugin/src/Utils.h b/Plugin/src/Utils.h new file mode 100644 index 00000000..9f9bb065 --- /dev/null +++ b/Plugin/src/Utils.h @@ -0,0 +1,27 @@ +#pragma once +#include "RE/Buffers.h" + +namespace Utils +{ + std::unordered_map GetDXGIFormatNameMap(); + + void LogFormats(); + + void LogBuffers(); + + void SetBufferFormat(RE::BufferDefinition* a_buffer, RE::BS_DXGI_FORMAT a_format); + void SetBufferFormat(RE::Buffers a_buffer, RE::BS_DXGI_FORMAT a_format); + RE::BS_DXGI_FORMAT GetBufferFormat(RE::Buffers a_buffer); + + bool ShouldCorrectLUTs(); + bool IsInPauseMenu(); + bool IsInMainMenu(); + + bool GetHDRMaxLuminance(IDXGISwapChain3* a_swapChainInterface, float& a_outMaxLuminance); + bool GetDisplayConfigPathInfo(HWND a_hwnd, DISPLAYCONFIG_PATH_INFO& a_outPathInfo); + bool GetColorInfo(HWND a_hwnd, DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO& a_outColorInfo); + bool IsHDRSupported(HWND a_hwnd); + bool IsHDREnabled(HWND a_hwnd); + bool SetHDREnabled(HWND a_hwnd); + +} diff --git a/Plugin/src/main.cpp b/Plugin/src/main.cpp new file mode 100644 index 00000000..2ed0c6dd --- /dev/null +++ b/Plugin/src/main.cpp @@ -0,0 +1,95 @@ +#include "SFSE/Stub.h" + +#include "Hooks.h" +#include "Offsets.h" +#include "Settings.h" + +DLLEXPORT constinit auto SFSEPlugin_Version = []() noexcept { + SFSE::PluginVersionData data{}; + + data.PluginVersion(Plugin::Version); + data.PluginName(Plugin::NAME); + data.AuthorName(Plugin::AUTHOR); + + // Address Library v1 (https://www.nexusmods.com/starfield/mods/3256) + data.UsesAddressLibrary(true); + // Version independent signature scanning + //data.UsesSigScanning(true); + + // Uses version specific structure definitions + data.IsLayoutDependent(true); + //data.HasNoStructUse(true); + + data.CompatibleVersions({ RUNTIME_VERSION_1_7_33 }); + + return data; +}(); + +/** +// for preload plugins +void SFSEPlugin_Preload(SFSE::LoadInterface* a_sfse); +/**/ + +static inline bool bIsLoaded = false; + +void LoadPlugin(bool a_bIsSFSE) +{ + dku::Logger::Init(Plugin::NAME, std::to_string(Plugin::Version)); + INFO("{} v{} loaded", Plugin::NAME, Plugin::Version) + + // do stuff + Settings::Main::GetSingleton()->Load(); + + if (a_bIsSFSE) { + SFSE::AllocTrampoline(1 << 8); + } else { + dku::Hook::Trampoline::AllocTrampoline(1 << 8); + } + + Offsets::Initialize(); + Hooks::Install(); + + bIsLoaded = true; +} + +DLLEXPORT bool SFSEAPI SFSEPlugin_Load(SFSEInterface* a_sfse) +{ +#ifndef NDEBUG + while (!IsDebuggerPresent()) { + Sleep(100); + } +#endif + + if (bIsLoaded) { + return true; + } + + SFSE::Init(a_sfse); + + LoadPlugin(true); + + return true; +} + +BOOL APIENTRY DllMain(HMODULE a_hModule, DWORD a_ul_reason_for_call, LPVOID a_lpReserved) +{ + switch (a_ul_reason_for_call) { + case DLL_PROCESS_ATTACH: +#ifndef NDEBUG + while (!IsDebuggerPresent()) { + Sleep(100); + } +#endif + if (bIsLoaded) { + return TRUE; + } + + LoadPlugin(false); + break; + case DLL_PROCESS_DETACH: + reshade::unregister_addon(a_hModule); + break; + } + + return TRUE; +} diff --git a/Plugin/vcpkg.json b/Plugin/vcpkg.json new file mode 100644 index 00000000..e9040f26 --- /dev/null +++ b/Plugin/vcpkg.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "name": "luma", + "version-string": "1.0.0", + "description": "Native code plugin that adds native HDR support and other visual improvements to Starfield", + "dependencies": [ + "spdlog", + "nlohmann-json", + "simpleini", + "tomlplusplus", + "xbyak" + ], + "builtin-baseline": "a7d99a5c3cd1456af023051d025a5643a2d6e79c" +} \ No newline at end of file diff --git a/build-msvc.bat b/build-msvc.bat new file mode 100644 index 00000000..1361d48b --- /dev/null +++ b/build-msvc.bat @@ -0,0 +1,5 @@ +echo off +rd /s /q "%~dp0/build" +cmake -B "%~dp0/build" -S "%~dp0/Plugin" --preset=build-release-msvc-msvc +cmake --build "%~dp0/build" +pause > NUL \ No newline at end of file diff --git a/extern/DKUtil b/extern/DKUtil new file mode 160000 index 00000000..ca04ebd2 --- /dev/null +++ b/extern/DKUtil @@ -0,0 +1 @@ +Subproject commit ca04ebd21839c3a5f223046623903e4537dbb203 diff --git a/extern/SFSE b/extern/SFSE new file mode 160000 index 00000000..d7bf4614 --- /dev/null +++ b/extern/SFSE @@ -0,0 +1 @@ +Subproject commit d7bf4614772a2e557cf3731469f34949dbc9b81f diff --git a/make-sln-msvc.bat b/make-sln-msvc.bat new file mode 100644 index 00000000..e0e8341f --- /dev/null +++ b/make-sln-msvc.bat @@ -0,0 +1,4 @@ +echo off +rd /s /q "%~dp0/build" +cmake -B "%~dp0/build" -S "%~dp0/Plugin" --preset=build-debug-msvc-msvc +pause > NUL \ No newline at end of file diff --git a/shaders/BinkMovie/BinkMovie_FFAB_ps.hlsl b/shaders/BinkMovie/BinkMovie_FFAB_ps.hlsl deleted file mode 100644 index 0c0c8f0d..00000000 --- a/shaders/BinkMovie/BinkMovie_FFAB_ps.hlsl +++ /dev/null @@ -1,65 +0,0 @@ -#define ENABLE_HDR 1 -#define HDR_GAME_PAPER_WHITE 2.5f -#define HDR_USE_GAMMA_2_2 1 - -Texture2D _8 : register(t0, space8); -Texture2D _9 : register(t1, space8); -Texture2D _10 : register(t2, space8); -SamplerState _13 : register(s0, space8); - -struct PSInputs -{ - float4 pos : SV_Position; - float2 TEXCOORD : TEXCOORD0; -}; - -float gamma_sRGB_to_linear(float channel) -{ - [flatten] - if (channel <= 0.04045f) - { - channel = channel / 12.92f; - } - else - { - channel = pow((channel + 0.055f) / 1.055f, 2.4f); - } - return channel; -} - -float3 gamma_sRGB_to_linear(float3 Color) -{ - return float3(gamma_sRGB_to_linear(Color.r), - gamma_sRGB_to_linear(Color.g), - gamma_sRGB_to_linear(Color.b)); -} - -float4 PS(PSInputs inputs) : SV_Target -{ - float Y = _8.Sample(_13, inputs.TEXCOORD.xy).x * 1.16412353515625f; - float Cb = _9.Sample(_13, inputs.TEXCOORD.xy).x; - float Cr = _10.Sample(_13, inputs.TEXCOORD.xy).x; - float3 color; - //TODO: fix matrices??? Could these videos be meant for both SDR and HDR? - color.x = (Y - 0.870655059814453125f) + (Cb * 1.595794677734375f); - color.y = ((Y + 0.529705047607421875f) - (Cb * 0.8134765625f)) - (Cr * 0.391448974609375f); - color.z = (Y - 1.081668853759765625f) + (Cr * 2.017822265625f); - - // Clamp for safety of pow as the above matrix produces negative values, - // this breaks the UI pass if we are using R16G16B16A16F textures, - // as UI blending produces invalid pixels if it's blended with an invalid color. - color = max(color, 0.f); - -#if ENABLE_HDR -#if HDR_USE_GAMMA_2_2 - color = pow(color, 2.2f); -#else - color = gamma_sRGB_to_linear(color); -#endif - //TODO: AutoHDR on movies??? - - color *= HDR_GAME_PAPER_WHITE; -#endif // ENABLE_HDR - - return float4(color, 1.0f); -} \ No newline at end of file diff --git a/shaders/BinkMovie/BinkMovie_ps.hlsl b/shaders/BinkMovie/BinkMovie_ps.hlsl new file mode 100644 index 00000000..3ec0dfcf --- /dev/null +++ b/shaders/BinkMovie/BinkMovie_ps.hlsl @@ -0,0 +1,87 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +Texture2D TexY : register(t0, space8); +Texture2D TexCb : register(t2, space8); +Texture2D TexCr : register(t1, space8); + +SamplerState Sampler0 : register(s0, space8); + +struct PSInputs +{ + float4 pos : SV_Position; + float2 TEXCOORD : TEXCOORD0; +}; + +//TODO: expose to user? At least the on/off bool, and maybe the shoulder pow and max nits, but it's probably better to simply pick a default that looks nice on most movies. +static const bool BinkVideosAutoHDR = true; +static const float BinkVideosAutoHDRMaxOutputNits = 750.f; +// The higher it is, the "later" highlights start +static const float BinkVideosAutoHDRShoulderPow = 2.75f; // A somewhat conservative value + +// AutoHDR pass to generate some HDR brightess out of an SDR signal (it has no effect if HDR is not engaged). +// This is hue conserving and only really affects highlights. +// https://github.com/Filoppi/PumboAutoHDR +float3 PumboAutoHDR(float3 Color, float MaxOutputNits, float PaperWhite) +{ + const float SDRRatio = Luminance(Color); + // Limit AutoHDR brightness, it won't look good beyond a certain level. + // The paper white multiplier is applied later so we account for that. + const float AutoHDRMaxWhite = max(min(MaxOutputNits, BinkVideosAutoHDRMaxOutputNits) / PaperWhite, WhiteNits_sRGB) / WhiteNits_sRGB; + const float AutoHDRShoulderRatio = 1.f - max(1.f - SDRRatio, 0.f); + const float AutoHDRExtraRatio = pow(AutoHDRShoulderRatio, BinkVideosAutoHDRShoulderPow) * (AutoHDRMaxWhite - 1.f); + const float AutoHDRTotalRatio = SDRRatio + AutoHDRExtraRatio; + return Color * (AutoHDRTotalRatio / SDRRatio); +} + +[RootSignature(ShaderRootSignature)] +float4 PS(PSInputs inputs) : SV_Target +{ + float Y = TexY.Sample(Sampler0, inputs.TEXCOORD.xy).x; + float Cb = TexCb.Sample(Sampler0, inputs.TEXCOORD.xy).x; + float Cr = TexCr.Sample(Sampler0, inputs.TEXCOORD.xy).x; + + float3 color; + // usually in YCbCr the ranges are (in float): + // Y: 0.0-1.0 + // Cb: -0.5-0.5 + // Cr: -0.5-0.5 + // but since this is a digital signal (in unsinged 8bit: 0-255) it's now: + // Y: 0.0-1.0 + // Cb: 0.0-1.0 + // Cr: 0.0-1.0 + // the formula adjusts for that but was for BT.601 limited range while the video is definitely BT.709 full range + // matrix paramters have been adjusted for BT.709 full range + color.r = Y - 0.790487825870513916015625f + (Cr * 1.5748f); + color.g = Y + 0.329009473323822021484375f - (Cb * 0.18732427060604095458984375f) - (Cr * 0.46812427043914794921875f); + color.b = Y - 0.931438446044921875f + (Cb * 1.8556f); + + // Clamp for safety as YCbCr<->RGB is not 100% accurate in float and can produce negative/invalid colors, + // this breaks the UI pass if we are using R16G16B16A16F textures, + // as UI blending produces invalid pixels if it's blended with an invalid color. + // Also this is need for the gamma pow. + color = max(color, 0.f); + +#if !SDR_LINEAR_INTERMEDIARY + if (HdrDllPluginConstants.DisplayMode > 0) +#endif // SDR_LINEAR_INTERMEDIARY + { +#if SDR_USE_GAMMA_2_2 + color = pow(color, 2.2f); +#else + color = gamma_sRGB_to_linear(color); +#endif // SDR_USE_GAMMA_2_2 + + if (HdrDllPluginConstants.DisplayMode > 0) + { + const float paperWhite = HdrDllPluginConstants.HDRGamePaperWhiteNits / WhiteNits_sRGB; + if (BinkVideosAutoHDR) + color = PumboAutoHDR(color, HdrDllPluginConstants.HDRPeakBrightnessNits, paperWhite); + + color *= paperWhite; // Use the game brightness, not the UI one, as these are usually videos that are seamless with gameplay + } + } + + return float4(color, 1.0f); +} diff --git a/shaders/BinkMovie/RootSignature.hlsl b/shaders/BinkMovie/RootSignature.hlsl new file mode 100644 index 00000000..0b9b3508 --- /dev/null +++ b/shaders/BinkMovie/RootSignature.hlsl @@ -0,0 +1,13 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8), " \ + "SRV(t1, space=8), " \ + "SRV(t2, space=8) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=8) " diff --git a/shaders/ColorGradingMerge/ColorGradingMerge_FF81_cs.hlsl b/shaders/ColorGradingMerge/ColorGradingMerge_FF81_cs.hlsl deleted file mode 100644 index aa707e41..00000000 --- a/shaders/ColorGradingMerge/ColorGradingMerge_FF81_cs.hlsl +++ /dev/null @@ -1,148 +0,0 @@ -// Also in "tonemap" shaders. -// This currently shifts colors too much, even if it's mathematically correct. -#define FIX_LUT_GAMMA_MAPPING 1 -#define LUT_SIZE 16.f - -static float additionalNeutralLUTPercentage = 0.5f; -static float LUTLuminancePreservationPercentage = 0.5f; - -struct PushConstantWrapper_ColorGradingMerge -{ - float LUT1Percentage; - float LUT2Percentage; - float LUT3Percentage; - float LUT4Percentage; - float neutralLUTPercentage; -}; - -cbuffer PushConstantWrapper_ColorGradingMerge : register(b0, space0) -{ - PushConstantWrapper_ColorGradingMerge PcwColorGradingMerge : packoffset(c0); -}; - -Texture2D LUT1 : register(t0, space8); -Texture2D LUT2 : register(t1, space8); -Texture2D LUT3 : register(t2, space8); -Texture2D LUT4 : register(t3, space8); -RWTexture3D outMixedLUT : register(u0, space8); - -static uint3 gl_GlobalInvocationID; -struct SPIRV_Cross_Input -{ - uint3 gl_GlobalInvocationID : SV_DispatchThreadID; -}; - -float gamma_linear_to_sRGB(float channel) -{ - [flatten] - if (channel <= 0.0031308f) - { - channel = channel * 12.92f; - } - else - { - channel = 1.055f * pow(channel, 1.0f / 2.4f) - 0.055f; - } - return channel; -} - -float3 gamma_linear_to_sRGB(float3 Color) -{ - return float3(gamma_linear_to_sRGB(Color.r), - gamma_linear_to_sRGB(Color.g), - gamma_linear_to_sRGB(Color.b)); -} - -float gamma_sRGB_to_linear(float channel) -{ - [flatten] - if (channel <= 0.04045f) - { - channel = channel / 12.92f; - } - else - { - channel = pow((channel + 0.055f) / 1.055f, 2.4f); - } - return channel; -} - -float3 gamma_sRGB_to_linear(float3 Color) -{ - return float3(gamma_sRGB_to_linear(Color.r), - gamma_sRGB_to_linear(Color.g), - gamma_sRGB_to_linear(Color.b)); -} - -float Luminance(float3 color) -{ - // Fixed from "wrong" values: 0.2125 0.7154 0.0721f - return dot(color, float3(0.2126f, 0.7152f, 0.0722f)); -} - -void CS() -{ - const uint3 outUVW = uint3(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y, gl_GlobalInvocationID.z); // In pixels - const uint inU = (gl_GlobalInvocationID.z << 4u) + gl_GlobalInvocationID.x; - const int3 inUVW = int3(inU, gl_GlobalInvocationID.y, 0u); // In pixels - const float UVWScale = 1.f / (LUT_SIZE - 1.f); // Was "0.066666670143604278564453125", pixel coordinates 0-15 for a resolution of 16, which is half of LUTs size of 16x16x16 - - float3 neutralLUTColor = float3(outUVW) * UVWScale; // The neutral LUT is automatically generated by the coordinates, but it's baked with sRGB gamma - neutralLUTColor = gamma_sRGB_to_linear(neutralLUTColor); - - float3 LUT1Color = LUT1.Load(inUVW); - float3 LUT2Color = LUT2.Load(inUVW); - float3 LUT3Color = LUT3.Load(inUVW); - float3 LUT4Color = LUT4.Load(inUVW); - LUT1Color = gamma_sRGB_to_linear(LUT1Color); - LUT2Color = gamma_sRGB_to_linear(LUT2Color); - LUT3Color = gamma_sRGB_to_linear(LUT3Color); - LUT4Color = gamma_sRGB_to_linear(LUT4Color); - - float neutralLUTLuminance = Luminance(neutralLUTColor); - float LUT1Luminance = Luminance(LUT1Color); - float LUT2Luminance = Luminance(LUT2Color); - float LUT3Luminance = Luminance(LUT3Color); - float LUT4Luminance = Luminance(LUT4Color); - - if (LUT1Luminance != 0.f) - LUT1Color *= lerp(1.f, neutralLUTLuminance / LUT1Luminance, LUTLuminancePreservationPercentage); - if (LUT2Luminance != 0.f) - LUT2Color *= lerp(1.f, neutralLUTLuminance / LUT2Luminance, LUTLuminancePreservationPercentage); - if (LUT3Luminance != 0.f) - LUT3Color *= lerp(1.f, neutralLUTLuminance / LUT3Luminance, LUTLuminancePreservationPercentage); - if (LUT4Luminance != 0.f) - LUT4Color *= lerp(1.f, neutralLUTLuminance / LUT4Luminance, LUTLuminancePreservationPercentage); - -#if !FIX_LUT_GAMMA_MAPPING && 0 // Disabled as it's still preferable to do LUT blends in linear space - neutralLUTColor = gamma_linear_to_sRGB(neutralLUTColor); - LUT1Color = gamma_linear_to_sRGB(LUT1Color); - LUT2Color = gamma_linear_to_sRGB(LUT2Color); - LUT3Color = gamma_linear_to_sRGB(LUT3Color); - LUT4Color = gamma_linear_to_sRGB(LUT4Color); -#endif // FIX_LUT_GAMMA_MAPPING - - PushConstantWrapper_ColorGradingMerge adjustedPcwColorGradingMerge = PcwColorGradingMerge; - adjustedPcwColorGradingMerge.neutralLUTPercentage = lerp(adjustedPcwColorGradingMerge.neutralLUTPercentage, 1.f, additionalNeutralLUTPercentage); - adjustedPcwColorGradingMerge.LUT1Percentage = lerp(adjustedPcwColorGradingMerge.LUT1Percentage, 0.f, additionalNeutralLUTPercentage); - adjustedPcwColorGradingMerge.LUT2Percentage = lerp(adjustedPcwColorGradingMerge.LUT2Percentage, 0.f, additionalNeutralLUTPercentage); - adjustedPcwColorGradingMerge.LUT3Percentage = lerp(adjustedPcwColorGradingMerge.LUT3Percentage, 0.f, additionalNeutralLUTPercentage); - adjustedPcwColorGradingMerge.LUT4Percentage = lerp(adjustedPcwColorGradingMerge.LUT4Percentage, 0.f, additionalNeutralLUTPercentage); - - float3 mixedLUT = (adjustedPcwColorGradingMerge.neutralLUTPercentage * neutralLUTColor) - + (adjustedPcwColorGradingMerge.LUT1Percentage * LUT1Color) - + (adjustedPcwColorGradingMerge.LUT2Percentage * LUT2Color) - + (adjustedPcwColorGradingMerge.LUT3Percentage * LUT3Color) - + (adjustedPcwColorGradingMerge.LUT4Percentage * LUT4Color); -#if !FIX_LUT_GAMMA_MAPPING // Convert to linear after blending between LUTs, so the blends are done in linear space - mixedLUT = gamma_linear_to_sRGB(mixedLUT); -#endif // FIX_LUT_GAMMA_MAPPING - outMixedLUT[outUVW] = float4(mixedLUT, 1.f); -} - -[numthreads(16, 16, 1)] -void main(SPIRV_Cross_Input stage_input) -{ - gl_GlobalInvocationID = stage_input.gl_GlobalInvocationID; - CS(); -} \ No newline at end of file diff --git a/shaders/ColorGradingMerge/ColorGradingMerge_cs.hlsl b/shaders/ColorGradingMerge/ColorGradingMerge_cs.hlsl new file mode 100644 index 00000000..54eb3271 --- /dev/null +++ b/shaders/ColorGradingMerge/ColorGradingMerge_cs.hlsl @@ -0,0 +1,376 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "../math.hlsl" +#include "RootSignature.hlsl" + +// 0 None, 1 ShortFuse technique (normalization) +#define LUT_IMPROVEMENT_TYPE (FORCE_VANILLA_LOOK ? 0 : 1) +#define LUT_DEBUG_VALUES false +#if LUT_MAPPING_TYPE == 2 +#define DEBUG_COLOR linear_srgb_to_oklab(float3(1.f, 0.f, 1.f)) /*Magenta*/ +#else +#define DEBUG_COLOR float3(1.f, 0.f, 1.f) /*Magenta*/ +#endif // LUT_MAPPING_TYPE + +// These settings goes to influence the LUTs correction process, by determining how LUTs are linearized and how to correct the gamma mismatch baked into the game's look. +// There's many ways these LUTs could have been generated (designed, made): +// -They were made outside of the game on sRGB screens (this assumes that in the game they didn't look as the artists intended them) (sRGB raises blacks compared to 2.2) +// -They were made outside of the game on 2.2 screens (this assumes that in the game they didn't look as the artists intended them) +// -They were made inside of the game with the broken/optimized Bethesda sRGB gamma formula and outputting on sRGB screens +// -They were made inside of the game with the broken/optimized Bethesda sRGB gamma formula and outputting on 2.2 gamma screens (see "SDR_USE_GAMMA_2_2") +// +// Ultimately, it doesn't really matter too much how they were intended by the artists, as what matters is how they appeared in game, +// and we base our LUT correction/normalization process on that. +// Some of these options make LUTs too bright, and some other crush detail around shadow. +#if !SDR_USE_GAMMA_2_2 // sRGB->linear->LUT normalization + // This assumes the game used the sRGB gamma formula and was meant to be viewed on sRGB gamma displays. + #define LINEARIZE(x) gamma_sRGB_to_linear(x) + #define CORRECT_GAMMA(x) x +#else + // Follow the user setting (slower but it can probably help accross the whole range of LUTs and screens) + #define LINEARIZE(x) lerp(gamma_sRGB_to_linear(x), pow(x, 2.2f), HdrDllPluginConstants.GammaCorrection) + //#define LINEARIZE(x) pow(x, 2.2f) + #if GAMMA_CORRECTION_IN_LUTS // 2.2->linear->LUT normalization + // If we correct gamma in LUTs, there's nothing more to do than linearize (interpret) them as gamma 2.2, while the input coordinates keep using sRGB gamma. + // This single difference will correct the gamma on output. + #define CORRECT_GAMMA(x) x + #else // 2.2->linear->LUT normalization->sRGB->linear + // If we don't correct gamma in LUTs, we convert them back to sRGB gamma at the end, so that it will match the input coordinates gamma, as they also use sRGB. + // A further correction step will be done after that to acknowledge the gamma mismatch baked into the game look. + #if GAMMA_CORRECT_SDR_RANGE_ONLY + #define CORRECT_GAMMA(x) (gamma_sRGB_to_linear(lerp(gamma_linear_to_sRGB(saturate(x)), pow(saturate(x), 1.f / 2.2f), HdrDllPluginConstants.GammaCorrection)) + (x - saturate(x))) + //#define CORRECT_GAMMA(x) (gamma_sRGB_to_linear(pow(saturate(x), 1.f / 2.2f)) + (x - saturate(x))) + #else + // NOTE: to somehow conserve some HDR colors and not generate NaNs, we are doing inverse pow as gamma on negative numbers. + // Alternatively we could try to do this in BT.2020, so there's no negative colors. + #define CORRECT_GAMMA(x) (gamma_sRGB_to_linear(lerp(gamma_linear_to_sRGB(abs(x)), pow(abs(x), 1.f / 2.2f), HdrDllPluginConstants.GammaCorrection)) * sign(x)) + //#define CORRECT_GAMMA(x) (gamma_sRGB_to_linear(pow(abs(x), 1.f / 2.2f)) * sign(x)) + #endif // GAMMA_CORRECT_SDR_RANGE_ONLY + #endif // GAMMA_CORRECTION_IN_LUTS +#endif // SDR_USE_GAMMA_2_2 + +// Behaviour when the color Lightness goes beyond 1 +// -0: Allow lightness above 1 +// -1: Revert to original (non-normalized) color +// -2: Clamp lightness to 1 +#define LUT_SDR_ON_CLIP 1u +#define LUT_HDR_ON_CLIP 0u + +static const float AdditionalNeutralLUTPercentage = 0.f; // ~0.25 might be a good compromise, but this is mostly replaced by "HdrDllPluginConstants.LUTCorrectionStrength" + +cbuffer CPushConstantWrapper_ColorGradingMerge : register(b0, space0) +{ + PushConstantWrapper_ColorGradingMerge PcwColorGradingMerge : packoffset(c0); +}; + +Texture2D LUT1 : register(t0, space8); +Texture2D LUT2 : register(t1, space8); +Texture2D LUT3 : register(t2, space8); +Texture2D LUT4 : register(t3, space8); +RWTexture3D OutMixedLUT : register(u0, space8); + +struct LUTAnalysis +{ + float3 black; + float blackY; + float3 white; + float whiteY; + float whiteL; +}; + +static const uint LUTSizeLog2 = (uint)log2(LUT_SIZE); + +// In/Out in pixels +uint3 ThreeToTwoDimensionCoordinates(uint3 UVW) +{ + // 2D LUT extends horizontally. + const uint U = (UVW.z << LUTSizeLog2) + UVW.x; + return uint3(U, UVW.y, 0); +} + +void AnalyzeLUT(Texture2D LUT, inout LUTAnalysis Analysis) +{ + Analysis.black = LINEARIZE(LUT.Load(ThreeToTwoDimensionCoordinates(0u)).rgb); + Analysis.blackY = Luminance(Analysis.black); + Analysis.white = LINEARIZE(LUT.Load(ThreeToTwoDimensionCoordinates(LUT_MAX_UINT)).rgb); + Analysis.whiteY = Luminance(Analysis.white); + Analysis.whiteL = linear_srgb_to_oklab(Analysis.white)[0]; +} + +// Analyzes each LUT texel and normalizes their range. +// Slow but effective. +float3 PatchLUTColor(Texture2D LUT, uint3 UVW, float3 neutralLUTColor, bool SDRRange = false) +{ + LUTAnalysis analysis; + AnalyzeLUT(LUT, analysis); + + const float3 originalLinear = LINEARIZE(LUT.Load(UVW)); + const float3 originalLab = linear_srgb_to_oklab(originalLinear); + const float3 originalLCh = oklab_to_oklch(originalLab); + + if (analysis.whiteY < analysis.blackY // If LUT is inversed (eg: photo negative) don't do anything + || analysis.whiteY - analysis.blackY >= 1.f) // If LUT is full range already nothing to do + { +#if LUT_MAPPING_TYPE == 2 + return originalLab; +#else + return originalLinear; +#endif // LUT_MAPPING_TYPE + } + + // While it unclear how exactly the floor was raised, remove the tint to floor + // the values to 0. This will remove the haze and tint giving a fuller chroma + // Sample and hold targetChroma + +#if 0 // TODO: Expose or delete + //TODO: expose these values or find the best defaults. For now we skip these when "HdrDllPluginConstants.GammaCorrection" is on as it's not necessary + + // An additional tweak on top of "HdrDllPluginConstants.LUTCorrectionStrength" + float fixRaisedBlacksStrength = 1.f /*- HdrDllPluginConstants.DevSetting01*/; // Values between 0 and 1 + //TODO: improve the way "fixRaisedBlacksInputSmoothing" is applied, the curve isn't great now + // Modulates how much we fix the raised blacks based on how raised they were. + float fixRaisedBlacksInputSmoothing = lerp(1.f, 1.333f, HdrDllPluginConstants.GammaCorrection); // Values from 1 up, greater is smoother + float fixRaisedBlacksOutputSmoothing = lerp(1.f, 0.666f, HdrDllPluginConstants.GammaCorrection); // Values from 0 up, smaller than 1 is smoother + const float3 invertedBlack = 1.f - (pow(analysis.black, lerp(1.f, fixRaisedBlacksInputSmoothing, analysis.black)) * fixRaisedBlacksStrength); + const float3 blackScaling = lerp(1.f / invertedBlack, 1.f, pow(neutralLUTColor, fixRaisedBlacksOutputSmoothing)); +#elif 1 // Original implementation + const float3 blackScaling = lerp(1.f / (1.f - analysis.black), 1.f, neutralLUTColor); +#elif 0 // Alternative implementation, generates slightly smoother shadow gradients but it hasn't been tested around the game much, and still crushes blacks + const float3 blackScaling = lerp(1.f + analysis.black, 1.f, neutralLUTColor); +#else // Disable for quick testing + const float3 blackScaling = 1.f; +#endif + + // On full black (neutralLUTColor coordinates 0 0 0) this will always result in 0 0 0. + float3 detintedLinear = 1.f - ((1.f - originalLinear) * blackScaling); + + // It might seem that "detintedColor" couldn't go below 0 by looking at the math, + // but if Bethesda made luts that have solor LUT pixels that are much darker than the neutral LUT, this could happen. + // It must be done because if channels go negative otherwise it'll become + // amplified when gain is applied back, causing L to be lower than it should. + // Even if Y or L is positive before gain, a negative channel being multiplied + // will hurt visiblity. + // (eg: (-2,0,1) * 2 = (-4, 0, 2) instead of (0,0,2) + // Trade off here is, near black, more visibility vs smoother gradients. + // Basically without this, the output might be overly dark. + static const bool AlwaysClampDetintedColor = true; + if (AlwaysClampDetintedColor || SDRRange) { + detintedLinear = max(detintedLinear, 0.f); + } + +#if LUT_DEBUG_VALUES + // Should never happen, especially if "AlwaysClampDetintedColor" is true + if (Luminance(detintedColor) < 0.f) { + return DEBUG_COLOR; + } +#endif // LUT_DEBUG_VALUES + + // The saturation multiplier in LUTs is restricted to HDR as it easily goes beyond Rec.709 + const float detintedChroma = linear_srgb_to_oklch(detintedLinear)[1]; + const float saturation = linearNormalization(HdrDllPluginConstants.HDRSaturation, 0.f, 2.f, 0.5f, 1.5f); + const float targetChroma = detintedChroma * (SDRRange ? 1.f : saturation); + + // Adjust the value back to recreate a smooth Y gradient since 0 is floored + // Sample and hold "targetL" + + // We fork a bit from Normalized LUTs 2.0.0 here, because the scaling will + // now be symmetrical to avoid an extra lerp. + // Max shift in any channel is +0.00015736956998746443f + // In RGB8 this only shifts 8653 / 794,624 (1%) of texels enough to + // change one channel by 1/255 (and likely from rounding). + // None of those RGB8 values are near black or white + // At worse, it's 0.01% brighter + +#if 0 // TODO: enable this? It would only work in HDR though, and this brightness boost for the moment is meant for SDR. + const float ExtraLuminanceBoost = linearNormalization(HdrDllPluginConstants.SDRSecondaryBrightness, 0.f, 2.f, 0.75f, 1.25f); +#else + static const float ExtraLuminanceBoost = 1.f; +#endif + const float3 retintedLinear = detintedLinear * blackScaling * ExtraLuminanceBoost; + + float targetL = linear_srgb_to_oklab(retintedLinear)[0]; + +#if LUT_DEBUG_VALUES + if (targetL < 0.f) return DEBUG_COLOR; +#endif // LUT_DEBUG_VALUES + + // Texels exista as points in 3D cube. We are moving two heavily weighted + // points and need to compute the net force to be applied. + // Black texel is 0 from itself and sqrt(3) from white + // White texel is 0 from itself and sqrt(3) from black + // Values in between can be closer to one than the other. + // This can also be represented as [-1 to 1] or [-B to +W]. + // For interpolation between 0 and a maximum, it become [0, ..., W, ..., W+B] + // Distances do not always add up to sqrt(3) (eg: 1,0,0) + + const float blackDistance = length(neutralLUTColor); + const float whiteDistance = length(1.f - neutralLUTColor); + const float totalRange = blackDistance + whiteDistance; + +#if LUT_DEBUG_VALUES + // whiteL most always be > 0 + if (analysis.whiteL <= 0.f) return DEBUG_COLOR; +#endif // LUT_DEBUG_VALUES + + // Boost lightness by how much white was reduced + const float raiseL = linearNormalization( + whiteDistance, + 0.f, + totalRange, + 1.f / analysis.whiteL, + 1.f); + +#if LUT_DEBUG_VALUES + // increaseY must always be >= 1 + if (raiseL < 1.f) return DEBUG_COLOR; +#endif // LUT_DEBUG_VALUES + + // On full white (neutralLUTColor coordinates 1 1 1) this will always result in 1 1 1. + targetL *= raiseL; + + // Use hue from original LUT color + const float targetHue = originalLCh[2]; + + float3 outputLCh; + + if (targetL >= 1.f) { + const uint clipBehavior = SDRRange ? LUT_SDR_ON_CLIP : LUT_HDR_ON_CLIP; + if (clipBehavior == 0) // As is (treat it the same as any other color) + outputLCh = float3(targetL, targetChroma, targetHue); + else if (clipBehavior == 1) { + outputLCh = originalLCh; // Keep original color (do nothing) + } else if (clipBehavior == 2) { + outputLCh = float3(1.f, targetChroma, targetHue); + } + } + else { + outputLCh = float3(targetL, targetChroma, targetHue); + } + +#if LUT_DEBUG_VALUES // Debug black point + float3 debugLinear = oklch_to_linear_srgb(outputLCh); + + bool isBlackPoint = neutralLUTColor.r == 0.f && neutralLUTColor.g == 0.f && neutralLUTColor.b == 0.f; + + bool wasBlack = !any(linearColor); + + // If neutralLutColor is 0,0,0, force 0 + + debugLinear *= (!isBlackPoint); + + bool nowBlack = !any(debugLinear); + + if (isBlackPoint) { + if (wasBlack) { + // color = float3(0.f,1.f, 0.f); // Green (OK) + } else if (nowBlack) { + // L has recorded upto `0.000004829726509479252` + // If below 0.000005, ignore it + if (targetL >= 0.01f) { + debugLinear = float3(1.f,1.f, 0.f); // Yellow (Bad L) + } + } + } else if (nowBlack || targetL < 0.01f) { + if (!wasBlack) { + debugLinear = float3(0.f,1.f, 1.f); // Cyan (Crush) + } + } + outputLCh = linear_srgb_to_oklch(debugLinear); + + // Should never happen + if (Luminance(debugLinear) < 0.f) { + return DEBUG_COLOR; + } + + // Print all HDR colors + if (any(debugLinear != saturate(debugLinear))) { + return DEBUG_COLOR; + } +#endif // LUT_DEBUG_VALUES + + float3 outputLab = oklch_to_oklab(outputLCh); + // Blending in Oklab should even better than doing it in linear + outputLab = lerp(originalLab, outputLab, HdrDllPluginConstants.LUTCorrectionStrength); + +#if LUT_MAPPING_TYPE == 2 + return outputLab; +#else + float3 outputLinear = oklab_to_linear_srgb(outputLab); + if (SDRRange) { + // Optional step to keep colors in the SDR range. + outputLinear = saturate(outputLinear); + } + // To note, color channels may be negative, even if -0.00001, probably due to multiple color space conversions. +// else if (Luminance(outputLinear) < 0.f) { +// outputLinear = 0.f; +// } +// commented out as this can cause "black dot issues" + return outputLinear; +#endif +} + +// Dispatch size is 1 1 16 (x and y have one thread and one thread group, while z has 16 thread groups with a thread each) +[RootSignature(ShaderRootSignature)] +[numthreads(LUT_SIZE_UINT, LUT_SIZE_UINT, 1)] +void CS(uint3 SV_DispatchThreadID : SV_DispatchThreadID) +{ + const uint3 inUVW = ThreeToTwoDimensionCoordinates(SV_DispatchThreadID); + const uint3 outUVW = SV_DispatchThreadID; + + float3 neutralLUTColor = float3(outUVW) / (LUT_SIZE - 1.f); // The neutral LUT is automatically generated by the coordinates, but it's baked with sRGB or 2.2 gamma + neutralLUTColor = LINEARIZE(neutralLUTColor); // Yes, we indeed this we want this pre-gamma corrected even on neutral LUT + +#if LUT_IMPROVEMENT_TYPE != 1 + float3 LUT1Color = LUT1.Load(inUVW); + float3 LUT2Color = LUT2.Load(inUVW); + float3 LUT3Color = LUT3.Load(inUVW); + float3 LUT4Color = LUT4.Load(inUVW); + LUT1Color = LINEARIZE(LUT1Color); + LUT2Color = LINEARIZE(LUT2Color); + LUT3Color = LINEARIZE(LUT3Color); + LUT4Color = LINEARIZE(LUT4Color); +#endif // LUT_IMPROVEMENT_TYPE + + const bool SDRRange = HdrDllPluginConstants.DisplayMode <= 0 || (bool)FORCE_SDR_LUTS; +#if LUT_IMPROVEMENT_TYPE == 1 + float3 LUT1Color = PatchLUTColor(LUT1, inUVW, neutralLUTColor, SDRRange); + float3 LUT2Color = PatchLUTColor(LUT2, inUVW, neutralLUTColor, SDRRange); + float3 LUT3Color = PatchLUTColor(LUT3, inUVW, neutralLUTColor, SDRRange); + float3 LUT4Color = PatchLUTColor(LUT4, inUVW, neutralLUTColor, SDRRange); +#else + LUT1Color = linear_srgb_to_oklab(LUT1Color); + LUT2Color = linear_srgb_to_oklab(LUT2Color); + LUT3Color = linear_srgb_to_oklab(LUT3Color); + LUT4Color = linear_srgb_to_oklab(LUT4Color); +#endif // LUT_IMPROVEMENT_TYPE + +#if LUT_MAPPING_TYPE == 2 + neutralLUTColor = linear_srgb_to_oklab(neutralLUTColor); +#endif // LUT_MAPPING_TYPE + + // Blend in linear space or Oklab space depending on "LUT_MAPPING_TYPE" + float adjustedNeutralLUTPercentage = lerp(PcwColorGradingMerge.neutralLUTPercentage, 1.f, AdditionalNeutralLUTPercentage); + float adjustedLUT1Percentage = lerp(PcwColorGradingMerge.LUT1Percentage, 0.f, AdditionalNeutralLUTPercentage); + float adjustedLUT2Percentage = lerp(PcwColorGradingMerge.LUT2Percentage, 0.f, AdditionalNeutralLUTPercentage); + float adjustedLUT3Percentage = lerp(PcwColorGradingMerge.LUT3Percentage, 0.f, AdditionalNeutralLUTPercentage); + float adjustedLUT4Percentage = lerp(PcwColorGradingMerge.LUT4Percentage, 0.f, AdditionalNeutralLUTPercentage); + + float3 mixedLUT = (adjustedNeutralLUTPercentage * neutralLUTColor) + + (adjustedLUT1Percentage * LUT1Color) + + (adjustedLUT2Percentage * LUT2Color) + + (adjustedLUT3Percentage * LUT3Color) + + (adjustedLUT4Percentage * LUT4Color); + +// If necessary (!GAMMA_CORRECTION_IN_LUTS), shift from gamma 2.2 to sRGB interpretation, so the LUT input and output colors +// are in the same gamma space, which should be more mathematically correct, and we can then instead do the gamma correction later. +#if LUT_MAPPING_TYPE != 2 + mixedLUT = CORRECT_GAMMA(mixedLUT); +#endif // LUT_MAPPING_TYPE + +// Convert to sRGB gamma after blending between LUTs, so the blends are done in linear space, which gives more consistent and correct results +#if LUT_MAPPING_TYPE == 0 + mixedLUT = gamma_linear_to_sRGB(mixedLUT); +#endif // LUT_MAPPING_TYPE + + OutMixedLUT[outUVW] = float4(mixedLUT, 1.f); +} diff --git a/shaders/ColorGradingMerge/RootSignature.hlsl b/shaders/ColorGradingMerge/RootSignature.hlsl new file mode 100644 index 00000000..170672a9 --- /dev/null +++ b/shaders/ColorGradingMerge/RootSignature.hlsl @@ -0,0 +1,68 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(0), " \ + \ + "RootConstants(num32BitConstants=5, b0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=6), " \ + "SRV(t1, space=6), " \ + "SRV(t2, space=6, flags=DATA_VOLATILE), " \ + "SRV(t3, space=6), " \ + "SRV(t4, space=6), " \ + "SRV(t5, space=6), " \ + "SRV(t7, space=6), " \ + "SRV(t8, space=6), " \ + "SRV(t9, space=6), " \ + "SRV(t10, space=6), " \ + "SRV(t11, space=6), " \ + "SRV(t12, space=6), " \ + "SRV(t13, space=6), " \ + "SRV(t14, space=6), " \ + "SRV(t15, space=6), " \ + "SRV(t16, space=6), " \ + "SRV(t17, space=6), " \ + "SRV(t18, space=6), " \ + "SRV(t19, space=6), " \ + "SRV(t20, space=6), " \ + "SRV(t21, space=6), " \ + "SRV(t22, space=6), " \ + "SRV(t23, space=6), " \ + "SRV(t24, space=6), " \ + "SRV(t25, space=6), " \ + "SRV(t26, space=6), " \ + "UAV(u0, space=6), " \ + "UAV(u1, space=6), " \ + "SRV(t27, space=6), " \ + "SRV(t28, space=6) " \ + "), " \ + \ + "DescriptorTable( " \ + "Sampler(s0, numDescriptors=10, space=6), " \ + "Sampler(s10, numDescriptors=2, space=6) " \ + "), " \ + \ + "SRV(t6, space=6), " \ + "CBV(b0, space=6), " \ + "CBV(b1, space=6), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8), " \ + "SRV(t1, space=8), " \ + "SRV(t2, space=8), " \ + "SRV(t3, space=8), " \ + "UAV(u0, space=8) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s12, filter=FILTER_MIN_MAG_MIP_POINT, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s13, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s14, filter=FILTER_MIN_MAG_MIP_LINEAR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s15, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s16, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s17, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s18, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s19, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s20, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_LESS, space=6), " \ + "StaticSampler(s21, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_GREATER, space=6) " diff --git a/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_100FF94_cs.hlsl b/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_100FF94_cs.hlsl deleted file mode 100644 index c6233cdf..00000000 --- a/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_100FF94_cs.hlsl +++ /dev/null @@ -1,247 +0,0 @@ -#define ENABLE_HDR 1 - -cbuffer _16_18 : register(b0, space6) -{ - float4 _18_m0[8] : packoffset(c0); -}; - -cbuffer _21_23 : register(b0, space8) -{ - float4 _23_m0[4] : packoffset(c0); -}; - -Texture2D _8 : register(t0, space8); -RWTexture2D _11 : register(u0, space8); - -static uint3 gl_WorkGroupID; -static uint3 gl_LocalInvocationID; -struct SPIRV_Cross_Input -{ - uint3 gl_WorkGroupID : SV_GroupID; - uint3 gl_LocalInvocationID : SV_GroupThreadID; -}; - -uint spvPackHalf2x16(float2 value) -{ - uint2 Packed = f32tof16(value); - return Packed.x | (Packed.y << 16); -} - -float2 spvUnpackHalf2x16(uint value) -{ - return f16tof32(uint2(value & 0xffff, value >> 16)); -} - -void comp_main() -{ -#if ENABLE_HDR - // butchered the CS so it just outputs the input - uint4 _55 = asuint(_23_m0[2u]); - uint _58 = _55.x + (((gl_LocalInvocationID.x >> 1u) & 7u) | (gl_WorkGroupID.x << 4u)); - uint _59 = ((((gl_LocalInvocationID.x >> 3u) & 6u) | (gl_LocalInvocationID.x & 1u)) | (gl_WorkGroupID.y << 4u)) + _55.y; - uint _458 = _58 + 8u; - uint _489 = _59 + 8u; - - _11[uint2(_58, _59)] = _8.Load(int3(uint2(_58, _59), 0u)); - _11[uint2(_458, _59)] = _8.Load(int3(uint2(_458, _59), 0u)); - _11[uint2(_58, _489)] = _8.Load(int3(uint2(_58, _489), 0u)); - _11[uint2(_458, _489)] = _8.Load(int3(uint2(_458, _489), 0u)); -#else - uint4 _55 = asuint(_23_m0[2u]); - uint _58 = _55.x + (((gl_LocalInvocationID.x >> 1u) & 7u) | (gl_WorkGroupID.x << 4u)); - uint _59 = ((((gl_LocalInvocationID.x >> 3u) & 6u) | (gl_LocalInvocationID.x & 1u)) | (gl_WorkGroupID.y << 4u)) + _55.y; - uint4 _69 = asuint(_23_m0[3u]); - uint _70 = _69.x; - uint _71 = _69.y; - uint _72 = _69.z; - uint _73 = _69.w; - uint _74 = _58 << 16u; - uint _76 = uint(int(_74) >> int(16u)); - uint _77 = _59 << 16u; - uint _87 = uint(int(max(min(_76, _72), _70) << 16u) >> int(16u)); - uint _89 = uint(int(max(min(uint(int(_77 + 4294901760u) >> int(16u)), _73), _71) << 16u) >> int(16u)); - float4 _91 = _8.Load(int3(uint2(_87, _89), 0u)); - uint _96 = uint(int(_74 + 4294901760u) >> int(16u)); - uint _105 = uint(int(max(min(uint(int(_77) >> int(16u)), _73), _71) << 16u) >> int(16u)); - float4 _106 = _8.Load(int3(uint2(uint(int(max(min(_96, _72), _70) << 16u) >> int(16u)), _105), 0u)); - float4 _109 = _8.Load(int3(uint2(_87, _105), 0u)); - uint _114 = uint(int(_74 + 65536u) >> int(16u)); - float4 _119 = _8.Load(int3(uint2(uint(int(max(min(_114, _72), _70) << 16u) >> int(16u)), _105), 0u)); - uint _127 = uint(int(max(min(uint(int(_77 + 65536u) >> int(16u)), _73), _71) << 16u) >> int(16u)); - float4 _128 = _8.Load(int3(uint2(_87, _127), 0u)); - uint _134 = uint(int((_58 << 16u) + 524288u) >> int(16u)); - uint _138 = uint(int(max(min(_134, _72), _70) << 16u) >> int(16u)); - float4 _139 = _8.Load(int3(uint2(_138, _89), 0u)); - uint _146 = uint(int(_74 + 458752u) >> int(16u)); - float4 _151 = _8.Load(int3(uint2(uint(int(max(min(_146, _72), _70) << 16u) >> int(16u)), _105), 0u)); - float4 _156 = _8.Load(int3(uint2(_138, _105), 0u)); - uint _163 = uint(int(_74 + 589824u) >> int(16u)); - float4 _168 = _8.Load(int3(uint2(uint(int(max(min(_163, _72), _70) << 16u) >> int(16u)), _105), 0u)); - float4 _173 = _8.Load(int3(uint2(_138, _127), 0u)); - float _193 = exp2(log2((_91.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _194 = exp2(log2((_139.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _213 = exp2(log2((_106.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _214 = exp2(log2((_151.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _233 = exp2(log2((_109.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _234 = exp2(log2((_156.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _253 = exp2(log2((_119.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _254 = exp2(log2((_168.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _273 = exp2(log2((_128.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _274 = exp2(log2((_173.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _280 = isnan(_213) ? _193 : (isnan(_193) ? _213 : min(_193, _213)); - float _281 = isnan(_214) ? _194 : (isnan(_194) ? _214 : min(_194, _214)); - float _282 = isnan(_233) ? _280 : (isnan(_280) ? _233 : min(_280, _233)); - float _283 = isnan(_234) ? _281 : (isnan(_281) ? _234 : min(_281, _234)); - float _284 = isnan(_273) ? _253 : (isnan(_253) ? _273 : min(_253, _273)); - float _285 = isnan(_274) ? _254 : (isnan(_254) ? _274 : min(_254, _274)); - float _286 = isnan(_282) ? _284 : (isnan(_284) ? _282 : min(_284, _282)); - float _287 = isnan(_283) ? _285 : (isnan(_285) ? _283 : min(_285, _283)); - float _288 = isnan(_213) ? _193 : (isnan(_193) ? _213 : max(_193, _213)); - float _289 = isnan(_214) ? _194 : (isnan(_194) ? _214 : max(_194, _214)); - float _290 = isnan(_233) ? _288 : (isnan(_288) ? _233 : max(_288, _233)); - float _291 = isnan(_234) ? _289 : (isnan(_289) ? _234 : max(_289, _234)); - float _292 = isnan(_273) ? _253 : (isnan(_253) ? _273 : max(_253, _273)); - float _293 = isnan(_274) ? _254 : (isnan(_254) ? _274 : max(_254, _274)); - float _294 = isnan(_290) ? _292 : (isnan(_292) ? _290 : max(_292, _290)); - float _295 = isnan(_291) ? _293 : (isnan(_293) ? _291 : max(_293, _291)); - float _299 = 1.0f - _294; - float _300 = 1.0f - _295; - float _303 = (isnan(_299) ? _286 : (isnan(_286) ? _299 : min(_286, _299))) * (1.0f / _294); - float _304 = (isnan(_300) ? _287 : (isnan(_287) ? _300 : min(_287, _300))) * (1.0f / _295); - float _981 = isnan(0.0f) ? _303 : (isnan(_303) ? 0.0f : max(_303, 0.0f)); - float _992 = isnan(0.0f) ? _304 : (isnan(_304) ? 0.0f : max(_304, 0.0f)); - float2 _313 = spvUnpackHalf2x16(asuint(_23_m0[1u]).y & 65535u); - float _314 = _313.x; - float _315 = _314 * sqrt(isnan(1.0f) ? _981 : (isnan(_981) ? 1.0f : min(_981, 1.0f))); - float _316 = _314 * sqrt(isnan(1.0f) ? _992 : (isnan(_992) ? 1.0f : min(_992, 1.0f))); - float _322 = 1.0f / ((_315 * 4.0f) + 1.0f); - float _323 = 1.0f / ((_316 * 4.0f) + 1.0f); - float _329 = ((_316 * (((exp2(_18_m0[1u].w * log2((_151.x + 0.05499267578125f) * 0.9482421875f)) + exp2(_18_m0[1u].w * log2((_139.x + 0.05499267578125f) * 0.9482421875f))) + exp2(_18_m0[1u].w * log2((_168.x + 0.05499267578125f) * 0.9482421875f))) + exp2(_18_m0[1u].w * log2((_173.x + 0.05499267578125f) * 0.9482421875f)))) + exp2(_18_m0[1u].w * log2((_156.x + 0.05499267578125f) * 0.9482421875f))) * _323; - float _1003 = isnan(0.0f) ? _329 : (isnan(_329) ? 0.0f : max(_329, 0.0f)); - float _336 = ((_316 * (((_214 + _194) + _254) + _274)) + _234) * _323; - float _1014 = isnan(0.0f) ? _336 : (isnan(_336) ? 0.0f : max(_336, 0.0f)); - float _343 = ((_316 * (((exp2(log2((_151.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_139.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_168.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_173.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w))) + exp2(log2((_156.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _323; - float _1025 = isnan(0.0f) ? _343 : (isnan(_343) ? 0.0f : max(_343, 0.0f)); - float _345 = isnan(0.00100040435791015625f) ? _18_m0[1u].w : (isnan(_18_m0[1u].w) ? 0.00100040435791015625f : max(_18_m0[1u].w, 0.00100040435791015625f)); - if ((_58 <= _55.z) && (_59 <= _55.w)) - { - float _388 = (((((exp2(log2((_106.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_91.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_119.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_128.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _315) + exp2(log2((_109.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _322; - float _1041 = isnan(0.0f) ? _388 : (isnan(_388) ? 0.0f : max(_388, 0.0f)); - float _391 = 1.0f / _345; - float _396 = (exp2(_391 * log2(isnan(1.0f) ? _1041 : (isnan(_1041) ? 1.0f : min(_1041, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _404 = ((_315 * (((_213 + _193) + _253) + _273)) + _233) * _322; - float _1057 = isnan(0.0f) ? _404 : (isnan(_404) ? 0.0f : max(_404, 0.0f)); - float _410 = (exp2(_391 * log2(isnan(1.0f) ? _1057 : (isnan(_1057) ? 1.0f : min(_1057, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _447 = (((((exp2(log2((_106.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_91.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_119.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_128.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _315) + exp2(log2((_109.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _322; - float _1073 = isnan(0.0f) ? _447 : (isnan(_447) ? 0.0f : max(_447, 0.0f)); - float _453 = (exp2(_391 * log2(isnan(1.0f) ? _1073 : (isnan(_1073) ? 1.0f : min(_1073, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - _11[uint2(_58, _59)] = float4(isnan(0.0f) ? _453 : (isnan(_453) ? 0.0f : max(_453, 0.0f)), isnan(0.0f) ? _410 : (isnan(_410) ? 0.0f : max(_410, 0.0f)), isnan(0.0f) ? _396 : (isnan(_396) ? 0.0f : max(_396, 0.0f)), 1.0f); - } - uint _458 = _58 + 8u; - uint4 _461 = asuint(_23_m0[2u]); - if ((_458 <= _461.z) && (_59 <= _461.w)) - { - float _468 = 1.0f / _345; - float _472 = (exp2(_468 * log2(isnan(1.0f) ? _1025 : (isnan(_1025) ? 1.0f : min(_1025, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _478 = (exp2(_468 * log2(isnan(1.0f) ? _1014 : (isnan(_1014) ? 1.0f : min(_1014, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _484 = (exp2(_468 * log2(isnan(1.0f) ? _1003 : (isnan(_1003) ? 1.0f : min(_1003, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - _11[uint2(_458, _59)] = float4(isnan(0.0f) ? _484 : (isnan(_484) ? 0.0f : max(_484, 0.0f)), isnan(0.0f) ? _478 : (isnan(_478) ? 0.0f : max(_478, 0.0f)), isnan(0.0f) ? _472 : (isnan(_472) ? 0.0f : max(_472, 0.0f)), 1.0f); - } - uint _489 = _59 + 8u; - uint4 _492 = asuint(_23_m0[3u]); - uint _493 = _492.x; - uint _494 = _492.y; - uint _495 = _492.z; - uint _496 = _492.w; - uint _497 = _489 << 16u; - uint _505 = uint(int(max(min(_76, _495), _493) << 16u) >> int(16u)); - uint _507 = uint(int(max(min(uint(int(_497 + 4294901760u) >> int(16u)), _496), _494) << 16u) >> int(16u)); - float4 _509 = _8.Load(int3(uint2(_505, _507), 0u)); - uint _520 = uint(int(max(min(uint(int(_497) >> int(16u)), _496), _494) << 16u) >> int(16u)); - float4 _521 = _8.Load(int3(uint2(uint(int(max(min(_96, _495), _493) << 16u) >> int(16u)), _520), 0u)); - float4 _524 = _8.Load(int3(uint2(_505, _520), 0u)); - float4 _531 = _8.Load(int3(uint2(uint(int(max(min(_114, _495), _493) << 16u) >> int(16u)), _520), 0u)); - uint _539 = uint(int(max(min(uint(int(_497 + 65536u) >> int(16u)), _496), _494) << 16u) >> int(16u)); - float4 _540 = _8.Load(int3(uint2(_505, _539), 0u)); - uint _546 = uint(int(max(min(_134, _495), _493) << 16u) >> int(16u)); - float4 _547 = _8.Load(int3(uint2(_546, _507), 0u)); - float4 _556 = _8.Load(int3(uint2(uint(int(max(min(_146, _495), _493) << 16u) >> int(16u)), _520), 0u)); - float4 _561 = _8.Load(int3(uint2(_546, _520), 0u)); - float4 _570 = _8.Load(int3(uint2(uint(int(max(min(_163, _495), _493) << 16u) >> int(16u)), _520), 0u)); - float4 _575 = _8.Load(int3(uint2(_546, _539), 0u)); - float _596 = exp2(log2((_509.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _597 = exp2(log2((_547.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _616 = exp2(log2((_521.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _617 = exp2(log2((_556.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _636 = exp2(log2((_524.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _637 = exp2(log2((_561.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _656 = exp2(log2((_531.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _657 = exp2(log2((_570.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _676 = exp2(log2((_540.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _677 = exp2(log2((_575.y + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w); - float _683 = isnan(_616) ? _596 : (isnan(_596) ? _616 : min(_596, _616)); - float _684 = isnan(_617) ? _597 : (isnan(_597) ? _617 : min(_597, _617)); - float _685 = isnan(_636) ? _683 : (isnan(_683) ? _636 : min(_683, _636)); - float _686 = isnan(_637) ? _684 : (isnan(_684) ? _637 : min(_684, _637)); - float _687 = isnan(_676) ? _656 : (isnan(_656) ? _676 : min(_656, _676)); - float _688 = isnan(_677) ? _657 : (isnan(_657) ? _677 : min(_657, _677)); - float _689 = isnan(_685) ? _687 : (isnan(_687) ? _685 : min(_687, _685)); - float _690 = isnan(_686) ? _688 : (isnan(_688) ? _686 : min(_688, _686)); - float _691 = isnan(_616) ? _596 : (isnan(_596) ? _616 : max(_596, _616)); - float _692 = isnan(_617) ? _597 : (isnan(_597) ? _617 : max(_597, _617)); - float _693 = isnan(_636) ? _691 : (isnan(_691) ? _636 : max(_691, _636)); - float _694 = isnan(_637) ? _692 : (isnan(_692) ? _637 : max(_692, _637)); - float _695 = isnan(_676) ? _656 : (isnan(_656) ? _676 : max(_656, _676)); - float _696 = isnan(_677) ? _657 : (isnan(_657) ? _677 : max(_657, _677)); - float _697 = isnan(_693) ? _695 : (isnan(_695) ? _693 : max(_695, _693)); - float _698 = isnan(_694) ? _696 : (isnan(_696) ? _694 : max(_696, _694)); - float _701 = 1.0f - _697; - float _702 = 1.0f - _698; - float _705 = (isnan(_701) ? _689 : (isnan(_689) ? _701 : min(_689, _701))) * (1.0f / _697); - float _706 = (isnan(_702) ? _690 : (isnan(_690) ? _702 : min(_690, _702))) * (1.0f / _698); - float _1194 = isnan(0.0f) ? _705 : (isnan(_705) ? 0.0f : max(_705, 0.0f)); - float _1205 = isnan(0.0f) ? _706 : (isnan(_706) ? 0.0f : max(_706, 0.0f)); - float _711 = _314 * sqrt(isnan(1.0f) ? _1194 : (isnan(_1194) ? 1.0f : min(_1194, 1.0f))); - float _712 = _314 * sqrt(isnan(1.0f) ? _1205 : (isnan(_1205) ? 1.0f : min(_1205, 1.0f))); - float _717 = 1.0f / ((_711 * 4.0f) + 1.0f); - float _718 = 1.0f / ((_712 * 4.0f) + 1.0f); - float _724 = ((_712 * (((exp2(_18_m0[1u].w * log2((_556.x + 0.05499267578125f) * 0.9482421875f)) + exp2(_18_m0[1u].w * log2((_547.x + 0.05499267578125f) * 0.9482421875f))) + exp2(_18_m0[1u].w * log2((_570.x + 0.05499267578125f) * 0.9482421875f))) + exp2(_18_m0[1u].w * log2((_575.x + 0.05499267578125f) * 0.9482421875f)))) + exp2(_18_m0[1u].w * log2((_561.x + 0.05499267578125f) * 0.9482421875f))) * _718; - float _1216 = isnan(0.0f) ? _724 : (isnan(_724) ? 0.0f : max(_724, 0.0f)); - float _731 = ((_712 * (((_617 + _597) + _657) + _677)) + _637) * _718; - float _1227 = isnan(0.0f) ? _731 : (isnan(_731) ? 0.0f : max(_731, 0.0f)); - float _738 = ((_712 * (((exp2(log2((_556.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_547.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_570.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_575.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w))) + exp2(log2((_561.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _718; - float _1238 = isnan(0.0f) ? _738 : (isnan(_738) ? 0.0f : max(_738, 0.0f)); - uint4 _742 = asuint(_23_m0[2u]); - if ((_58 <= _742.z) && (_489 <= _742.w)) - { - float _783 = (((((exp2(log2((_521.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_509.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_531.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_540.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _711) + exp2(log2((_524.z + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _717; - float _1249 = isnan(0.0f) ? _783 : (isnan(_783) ? 0.0f : max(_783, 0.0f)); - float _786 = 1.0f / _345; - float _790 = (exp2(_786 * log2(isnan(1.0f) ? _1249 : (isnan(_1249) ? 1.0f : min(_1249, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _797 = ((_711 * (((_616 + _596) + _656) + _676)) + _636) * _717; - float _1265 = isnan(0.0f) ? _797 : (isnan(_797) ? 0.0f : max(_797, 0.0f)); - float _803 = (exp2(_786 * log2(isnan(1.0f) ? _1265 : (isnan(_1265) ? 1.0f : min(_1265, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _840 = (((((exp2(log2((_521.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w) + exp2(log2((_509.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_531.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) + exp2(log2((_540.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _711) + exp2(log2((_524.x + 0.05499267578125f) * 0.9482421875f) * _18_m0[1u].w)) * _717; - float _1281 = isnan(0.0f) ? _840 : (isnan(_840) ? 0.0f : max(_840, 0.0f)); - float _846 = (exp2(_786 * log2(isnan(1.0f) ? _1281 : (isnan(_1281) ? 1.0f : min(_1281, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - _11[uint2(_58, _489)] = float4(isnan(0.0f) ? _846 : (isnan(_846) ? 0.0f : max(_846, 0.0f)), isnan(0.0f) ? _803 : (isnan(_803) ? 0.0f : max(_803, 0.0f)), isnan(0.0f) ? _790 : (isnan(_790) ? 0.0f : max(_790, 0.0f)), 1.0f); - } - uint4 _853 = asuint(_23_m0[2u]); - if ((_458 <= _853.z) && (_489 <= _853.w)) - { - float _860 = 1.0f / _345; - float _864 = (exp2(_860 * log2(isnan(1.0f) ? _1238 : (isnan(_1238) ? 1.0f : min(_1238, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _870 = (exp2(_860 * log2(isnan(1.0f) ? _1227 : (isnan(_1227) ? 1.0f : min(_1227, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - float _876 = (exp2(_860 * log2(isnan(1.0f) ? _1216 : (isnan(_1216) ? 1.0f : min(_1216, 1.0f)))) * 1.0546875f) + (-0.05499267578125f); - _11[uint2(_458, _489)] = float4(isnan(0.0f) ? _876 : (isnan(_876) ? 0.0f : max(_876, 0.0f)), isnan(0.0f) ? _870 : (isnan(_870) ? 0.0f : max(_870, 0.0f)), isnan(0.0f) ? _864 : (isnan(_864) ? 0.0f : max(_864, 0.0f)), 1.0f); - } -#endif -} - -[numthreads(64, 1, 1)] -void main(SPIRV_Cross_Input stage_input) -{ - gl_WorkGroupID = stage_input.gl_WorkGroupID; - gl_LocalInvocationID = stage_input.gl_LocalInvocationID; - comp_main(); -} diff --git a/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_cs.hlsl b/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_cs.hlsl new file mode 100644 index 00000000..447e3f08 --- /dev/null +++ b/shaders/ContrastAdaptiveSharpening/ContrastAdaptiveSharpening_cs.hlsl @@ -0,0 +1,846 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +//#define USE_PACKED_MATH +//#define USE_UPSCALING + +// this is CAS upscaling in FP16 with FFX_CAS_USE_PRECISE_MATH [100FF94] +// other variants are also available but seemingly unused, which are: +// - CAS upscaling in FP32 [200FF94] +// - CAS upscaling in FP16 with FFX_CAS_USE_PRECISE_MATH and FFX_CAS_BETTER_DIAGONALS [300FF94] +// - just CAS sharpening in FP32 [FF94] + +// TODO: make full process in half not just after csp conversion? (needs matrices in half) + +// don't need it +//cbuffer _16_18 : register(b0, space6) +//{ +// float4 _18_m0[8] : packoffset(c0); // _18_m0[1u].w = Gamma +//}; + +cbuffer CCASData : register(b0, space8) +{ + ContrastAdaptiveSharpeningData CASData : packoffset(c0); +}; + +Texture2D ColorIn : register(t0, space8); +RWTexture2D ColorOut : register(u0, space8); + +struct CSInput +{ + uint3 SV_GroupID : SV_GroupID; + uint3 SV_GroupThreadID : SV_GroupThreadID; +}; + +//uint spvPackHalf2x16(float2 value) +//{ +// uint2 Packed = f32tof16(value); +// return Packed.x | (Packed.y << 16); +//} +// +//half2 spvUnpackHalf2x16(uint value) +//{ +// return f16tof32(uint2(value & 0xffff, value >> 16)); +//} + +#if SDR_LINEAR_INTERMEDIARY + #define GAMMA_TO_LINEAR(x) x + #define LINEAR_TO_GAMMA(x) x +#elif SDR_USE_GAMMA_2_2 + #define GAMMA_TO_LINEAR(x) pow(x, 2.2h) + #define LINEAR_TO_GAMMA(x) pow(x, half(1.f / 2.2f)) +#else // doing sRGB in half is not accurate enough + #define GAMMA_TO_LINEAR(x) gamma_sRGB_to_linear(x) + #define LINEAR_TO_GAMMA(x) gamma_linear_to_sRGB(x) +#endif + +#define HDR_BT2020 1 + +// since blue is the least contributing in terms of luminance +// the worst case is red and green at 0 and blue high enough +// so that the luminance is HdrDllPluginConstants.HDRPeakBrightnessNits +#if HDR_BT2020 + static const float BlueFactor = 0.059265948832035064697265625f; +#else + static const float BlueFactor = 0.07214272022247314453125f; +#endif +// normalize for the worst HDR10 case. It's still better than always normalizing it based on 10k nits. +// clamped at PQMaxWhitePoint (125) as that is the max HDR10 brightness (10000 / 80). +// Setting it as static const here is actually an optimization. +static const half NormalizationFactor = + min((HdrDllPluginConstants.HDRPeakBrightnessNits / WhiteNits_sRGB) / BlueFactor, PQMaxWhitePoint); + + +half3 PrepareForProcessing(half3 Color) +{ + if (HdrDllPluginConstants.DisplayMode > 0) + { +#if HDR_BT2020 + Color = BT709_To_BT2020_half(Color); +#endif + return saturate(Color / NormalizationFactor); + } + else + { + return saturate(GAMMA_TO_LINEAR(Color)); + } +} + +half3 PrepareForOutput(half3 Color) +{ + if (HdrDllPluginConstants.DisplayMode > 0) + { + Color *= NormalizationFactor; +#if HDR_BT2020 + return BT2020_To_BT709_half(Color); +#else + return Color; +#endif + } + else + { + return LINEAR_TO_GAMMA(Color); + } +} + + +[RootSignature(ShaderRootSignature)] +[numthreads(64, 1, 1)] +void CS(CSInput csInput) +{ +#if defined(USE_PACKED_MATH) \ + && defined(USE_UPSCALING) + + uint4 _55 = CASData.rectLimits0; + + uint _58 = ((csInput.SV_GroupThreadID.x >> 1) & 7) + | (csInput.SV_GroupID.x << 4); + _58 += _55.x; + + uint _59 = ((csInput.SV_GroupThreadID.x >> 3) & 6) + | (csInput.SV_GroupThreadID.x & 1) + | (csInput.SV_GroupID.y << 4); + _59 += _55.y; + + CASConst0 _62 = CASData.upscalingConst0; + CASConst1 _69 = CASData.upscalingConst1; + + float _85 = (float(_58) * _62.rcpScalingFactorX) + _62.otherScalingFactorX; + float _86 = (float(_59) * _62.rcpScalingFactorY) + _62.otherScalingFactorY; + + half _91 = frac(_85); + half _93 = frac(_86); + + uint _95 = uint(_85); + uint _96 = uint(_86); + + uint _131 = _95 - 1; + uint _114 = _95; + uint _148 = _95 + 1; + uint _163 = _95 + 2; + + uint _116 = _96 - 1; + uint _133 = _96; + uint _173 = _96 + 1; + uint _187 = _96 + 2; + + half3 _118 = ColorIn.Load(int3(_114, _116, 0)).rgb; + half3 _134 = ColorIn.Load(int3(_131, _133, 0)).rgb; + half3 _138 = ColorIn.Load(int3(_114, _133, 0)).rgb; + half3 _149 = ColorIn.Load(int3(_148, _116, 0)).rgb; + half3 _153 = ColorIn.Load(int3(_148, _133, 0)).rgb; + half3 _164 = ColorIn.Load(int3(_163, _133, 0)).rgb; + half3 _174 = ColorIn.Load(int3(_131, _173, 0)).rgb; + half3 _178 = ColorIn.Load(int3(_114, _173, 0)).rgb; + half3 _188 = ColorIn.Load(int3(_114, _187, 0)).rgb; + half3 _192 = ColorIn.Load(int3(_148, _173, 0)).rgb; + half3 _196 = ColorIn.Load(int3(_163, _173, 0)).rgb; + half3 _200 = ColorIn.Load(int3(_148, _187, 0)).rgb; + + float _205 = _85 + _69.rcpScalingFactorXTimes8; + + half _208 = frac(_205); + + uint _209 = uint(_205); + + uint _228 = _209 - 1; + uint _214 = _209; + uint _250 = _209 + 1; + uint _272 = _209 + 2; + + half3 _215 = ColorIn.Load(int3(_214, _116, 0)).rgb; + half3 _229 = ColorIn.Load(int3(_228, _133, 0)).rgb; + half3 _237 = ColorIn.Load(int3(_214, _133, 0)).rgb; + half3 _251 = ColorIn.Load(int3(_250, _116, 0)).rgb; + half3 _259 = ColorIn.Load(int3(_250, _133, 0)).rgb; + half3 _273 = ColorIn.Load(int3(_272, _133, 0)).rgb; + half3 _281 = ColorIn.Load(int3(_228, _173, 0)).rgb; + half3 _289 = ColorIn.Load(int3(_214, _173, 0)).rgb; + half3 _297 = ColorIn.Load(int3(_214, _187, 0)).rgb; + half3 _305 = ColorIn.Load(int3(_250, _173, 0)).rgb; + half3 _313 = ColorIn.Load(int3(_272, _173, 0)).rgb; + half3 _321 = ColorIn.Load(int3(_250, _187, 0)).rgb; + + _118 = PrepareForProcessing(_118); + _134 = PrepareForProcessing(_134); + _138 = PrepareForProcessing(_138); + _149 = PrepareForProcessing(_149); + _153 = PrepareForProcessing(_153); + _164 = PrepareForProcessing(_164); + _174 = PrepareForProcessing(_174); + _178 = PrepareForProcessing(_178); + _188 = PrepareForProcessing(_188); + _192 = PrepareForProcessing(_192); + _196 = PrepareForProcessing(_196); + _200 = PrepareForProcessing(_200); + _215 = PrepareForProcessing(_215); + _229 = PrepareForProcessing(_229); + _237 = PrepareForProcessing(_237); + _251 = PrepareForProcessing(_251); + _259 = PrepareForProcessing(_259); + _273 = PrepareForProcessing(_273); + _281 = PrepareForProcessing(_281); + _289 = PrepareForProcessing(_289); + _297 = PrepareForProcessing(_297); + _305 = PrepareForProcessing(_305); + _313 = PrepareForProcessing(_313); + _321 = PrepareForProcessing(_321); + + half _344 = _118.y; + half _345 = _215.y; + half _364 = _149.y; + half _365 = _251.y; + half _384 = _134.y; + half _385 = _229.y; + half _404 = _138.y; + half _405 = _237.y; + half _424 = _153.y; + half _425 = _259.y; + half _444 = _164.y; + half _445 = _273.y; + half _464 = _174.y; + half _465 = _281.y; + half _484 = _178.y; + half _485 = _289.y; + half _504 = _192.y; + half _505 = _305.y; + half _524 = _196.y; + half _525 = _313.y; + half _544 = _188.y; + half _545 = _297.y; + half _564 = _200.y; + half _565 = _321.y; + + half _571 = min(_384, _404); + half _572 = min(_385, _405); + half _573 = min(_344, _571); + half _574 = min(_345, _572); + half _575 = min(_424, _484); + half _576 = min(_425, _485); + half _577 = min(_573, _575); + half _578 = min(_574, _576); + half _579 = max(_384, _404); + half _580 = max(_385, _405); + half _581 = max(_344, _579); + half _582 = max(_345, _580); + half _583 = max(_424, _484); + half _584 = max(_425, _485); + half _585 = max(_581, _583); + half _586 = max(_582, _584); + half _587 = min(_404, _424); + half _588 = min(_405, _425); + half _589 = min(_364, _587); + half _590 = min(_365, _588); + half _591 = min(_444, _504); + half _592 = min(_445, _505); + half _593 = min(_589, _591); + half _594 = min(_590, _592); + half _595 = max(_404, _424); + half _596 = max(_405, _425); + half _597 = max(_364, _595); + half _598 = max(_365, _596); + half _599 = max(_444, _504); + half _600 = max(_445, _505); + half _601 = max(_597, _599); + half _602 = max(_598, _600); + half _603 = min(_464, _484); + half _604 = min(_465, _485); + half _605 = min(_404, _603); + half _606 = min(_405, _604); + half _607 = min(_504, _544); + half _608 = min(_505, _545); + half _609 = min(_605, _607); + half _610 = min(_606, _608); + half _611 = max(_464, _484); + half _612 = max(_465, _485); + half _613 = max(_404, _611); + half _614 = max(_405, _612); + half _615 = max(_504, _544); + half _616 = max(_505, _545); + half _617 = max(_613, _615); + half _618 = max(_614, _616); + half _619 = min(_484, _504); + half _620 = min(_485, _505); + half _621 = min(_424, _619); + half _622 = min(_425, _620); + half _623 = min(_524, _564); + half _624 = min(_525, _565); + half _625 = min(_621, _623); + half _626 = min(_622, _624); + half _627 = max(_484, _504); + half _628 = max(_485, _505); + half _629 = max(_424, _627); + half _630 = max(_425, _628); + half _631 = max(_524, _564); + half _632 = max(_525, _565); + half _633 = max(_629, _631); + half _634 = max(_630, _632); + + half _644 = 1.h - _585; + half _645 = 1.h - _586; + half _653 = 1.h - _601; + half _654 = 1.h - _602; + half _661 = 1.h - _617; + half _662 = 1.h - _618; + half _669 = 1.h - _633; + half _670 = 1.h - _634; + + half _648 = min(_577, _644) * (1.h / _585); + half _649 = min(_578, _645) * (1.h / _586); + half _657 = min(_593, _653) * (1.h / _601); + half _658 = min(_594, _654) * (1.h / _602); + half _665 = min(_609, _661) * (1.h / _617); + half _666 = min(_610, _662) * (1.h / _618); + half _673 = min(_625, _669) * (1.h / _633); + half _674 = min(_626, _670) * (1.h / _634); + + half _2515 = max(_648, 0.h); + half _2526 = max(_649, 0.h); + half _2547 = max(_657, 0.h); + half _2558 = max(_658, 0.h); + half _2579 = max(_665, 0.h); + half _2590 = max(_666, 0.h); + half _2611 = max(_673, 0.h); + half _2622 = max(_674, 0.h); + + half hSharp = f16tof32(_69.sharpAsHalf & 0xFFFF); + + half _699 = 1.h - _91; + half _700 = 1.h - _208; + half _701 = 1.h - _93; + + half _717 = (_699 * _701) * (1.h / ((0.03125h - _577) + _585)); + half _718 = (_700 * _701) * (1.h / ((0.03125h - _578) + _586)); + half _725 = ( _91 * _701) * (1.h / ((0.03125h - _593) + _601)); + half _726 = (_208 * _701) * (1.h / ((0.03125h - _594) + _602)); + half _733 = (_699 * _93) * (1.h / ((0.03125h - _609) + _617)); + half _734 = (_700 * _93) * (1.h / ((0.03125h - _610) + _618)); + half _741 = ( _91 * _93) * (1.h / ((0.03125h - _625) + _633)); + half _742 = (_208 * _93) * (1.h / ((0.03125h - _626) + _634)); + + half _743 = _717 * (hSharp * sqrt(min(_2515, 1.h))); + half _744 = _718 * (hSharp * sqrt(min(_2526, 1.h))); + half _745 = _725 * (hSharp * sqrt(min(_2547, 1.h))); + half _746 = _726 * (hSharp * sqrt(min(_2558, 1.h))); + half _747 = _733 * (hSharp * sqrt(min(_2579, 1.h))); + half _748 = _734 * (hSharp * sqrt(min(_2590, 1.h))); + half _753 = _741 * (hSharp * sqrt(min(_2611, 1.h))); + half _754 = _742 * (hSharp * sqrt(min(_2622, 1.h))); + + half _750 = (_745 + _717) + _747; + half _752 = (_746 + _718) + _748; + half _756 = (_725 + _743) + _753; + half _758 = (_726 + _744) + _754; + half _760 = (_733 + _743) + _753; + half _762 = (_734 + _744) + _754; + half _765 = (_747 + _745) + _741; + half _766 = (_748 + _746) + _742; + + half _784 = 1.h / ((((_765 + _750) + ((((_745 + _743) + _747) + _753) * 2.h)) + _756) + _760); + half _785 = 1.h / ((((_766 + _752) + ((((_746 + _744) + _748) + _754) * 2.h)) + _758) + _762); + + half3 _803 = ((((((((_752 * _237) + (_744 * (_229 + _215))) + (_766 * _305)) + (_758 * _259)) + (_762 * _289)) + (_754 * (_321 + _313))) + (_748 * (_297 + _281))) + (_746 * (_273 + _251))) * _785; + half3 colorOut2 = saturate(_803); + + colorOut2 = PrepareForOutput(colorOut2); + + if ((_58 <= _55.z) && (_59 <= _55.w)) + { + half3 _961 = ((((((((_138 * _750) + ((_134 + _118) * _743)) + (_153 * _756)) + (_178 * _760)) + (_192 * _765)) + ((_200 + _196) * _753)) + ((_188 + _174) * _747)) + ((_164 + _149) * _745)) * _784; + half3 colorOut1 = saturate(_961); + + colorOut1 = PrepareForOutput(colorOut1); + + ColorOut[uint2(_58, _59)] = float4(float3(colorOut1), 1.f); + } + + uint _1119 = _58 + 8; + + if ((_1119 <= _55.z) && (_59 <= _55.w)) + { + ColorOut[uint2(_1119, _59)] = float4(float3(colorOut2), 1.f); + } + + uint _1153 = _59 + 8; + + float _1156 = (float(_1153) * _62.rcpScalingFactorY) + _62.otherScalingFactorY; + + half _1159 = frac(_1156); + + uint _1160 = uint(_1156); + + uint _1177 = _1160 - 1; + uint _1191 = _1160; + uint _1225 = _1160 + 1; + uint _1239 = _1160 + 2; + + half3 _1179 = ColorIn.Load(int3(_114, _1177, 0)).rgb; + half3 _1192 = ColorIn.Load(int3(_131, _1191, 0)).rgb; + half3 _1196 = ColorIn.Load(int3(_114, _1191, 0)).rgb; + half3 _1204 = ColorIn.Load(int3(_148, _1177, 0)).rgb; + half3 _1208 = ColorIn.Load(int3(_148, _1191, 0)).rgb; + half3 _1216 = ColorIn.Load(int3(_163, _1191, 0)).rgb; + half3 _1226 = ColorIn.Load(int3(_131, _1225, 0)).rgb; + half3 _1230 = ColorIn.Load(int3(_114, _1225, 0)).rgb; + half3 _1240 = ColorIn.Load(int3(_114, _1239, 0)).rgb; + half3 _1244 = ColorIn.Load(int3(_148, _1225, 0)).rgb; + half3 _1248 = ColorIn.Load(int3(_163, _1225, 0)).rgb; + half3 _1252 = ColorIn.Load(int3(_148, _1239, 0)).rgb; + half3 _1260 = ColorIn.Load(int3(_214, _1177, 0)).rgb; + half3 _1272 = ColorIn.Load(int3(_228, _1191, 0)).rgb; + half3 _1280 = ColorIn.Load(int3(_214, _1191, 0)).rgb; + half3 _1292 = ColorIn.Load(int3(_250, _1177, 0)).rgb; + half3 _1300 = ColorIn.Load(int3(_250, _1191, 0)).rgb; + half3 _1312 = ColorIn.Load(int3(_272, _1191, 0)).rgb; + half3 _1320 = ColorIn.Load(int3(_228, _1225, 0)).rgb; + half3 _1328 = ColorIn.Load(int3(_214, _1225, 0)).rgb; + half3 _1336 = ColorIn.Load(int3(_214, _1239, 0)).rgb; + half3 _1344 = ColorIn.Load(int3(_250, _1225, 0)).rgb; + half3 _1352 = ColorIn.Load(int3(_272, _1225, 0)).rgb; + half3 _1360 = ColorIn.Load(int3(_250, _1239, 0)).rgb; + + _1179 = PrepareForProcessing(_1179); + _1192 = PrepareForProcessing(_1192); + _1196 = PrepareForProcessing(_1196); + _1204 = PrepareForProcessing(_1204); + _1208 = PrepareForProcessing(_1208); + _1216 = PrepareForProcessing(_1216); + _1226 = PrepareForProcessing(_1226); + _1230 = PrepareForProcessing(_1230); + _1240 = PrepareForProcessing(_1240); + _1244 = PrepareForProcessing(_1244); + _1248 = PrepareForProcessing(_1248); + _1252 = PrepareForProcessing(_1252); + _1260 = PrepareForProcessing(_1260); + _1272 = PrepareForProcessing(_1272); + _1280 = PrepareForProcessing(_1280); + _1292 = PrepareForProcessing(_1292); + _1300 = PrepareForProcessing(_1300); + _1312 = PrepareForProcessing(_1312); + _1320 = PrepareForProcessing(_1320); + _1328 = PrepareForProcessing(_1328); + _1336 = PrepareForProcessing(_1336); + _1344 = PrepareForProcessing(_1344); + _1352 = PrepareForProcessing(_1352); + _1360 = PrepareForProcessing(_1360); + + half _1385 = _1179.y; + half _1386 = _1260.y; + half _1405 = _1204.y; + half _1406 = _1292.y; + half _1425 = _1192.y; + half _1426 = _1272.y; + half _1445 = _1196.y; + half _1446 = _1280.y; + half _1465 = _1208.y; + half _1466 = _1300.y; + half _1485 = _1216.y; + half _1486 = _1312.y; + half _1505 = _1226.y; + half _1506 = _1320.y; + half _1525 = _1230.y; + half _1526 = _1328.y; + half _1545 = _1244.y; + half _1546 = _1344.y; + half _1565 = _1248.y; + half _1566 = _1352.y; + half _1585 = _1240.y; + half _1586 = _1336.y; + half _1605 = _1252.y; + half _1606 = _1360.y; + + half _1612 = min(_1425, _1445); + half _1613 = min(_1426, _1446); + half _1614 = min(_1385, _1612); + half _1615 = min(_1386, _1613); + half _1616 = min(_1465, _1525); + half _1617 = min(_1466, _1526); + half _1618 = min(_1614, _1616); + half _1619 = min(_1615, _1617); + half _1620 = max(_1425, _1445); + half _1621 = max(_1426, _1446); + half _1622 = max(_1385, _1620); + half _1623 = max(_1386, _1621); + half _1624 = max(_1465, _1525); + half _1625 = max(_1466, _1526); + half _1626 = max(_1622, _1624); + half _1627 = max(_1623, _1625); + half _1628 = min(_1445, _1465); + half _1629 = min(_1446, _1466); + half _1630 = min(_1405, _1628); + half _1631 = min(_1406, _1629); + half _1632 = min(_1485, _1545); + half _1633 = min(_1486, _1546); + half _1634 = min(_1630, _1632); + half _1635 = min(_1631, _1633); + half _1636 = max(_1445, _1465); + half _1637 = max(_1446, _1466); + half _1638 = max(_1405, _1636); + half _1639 = max(_1406, _1637); + half _1640 = max(_1485, _1545); + half _1641 = max(_1486, _1546); + half _1642 = max(_1638, _1640); + half _1643 = max(_1639, _1641); + half _1644 = min(_1505, _1525); + half _1645 = min(_1506, _1526); + half _1646 = min(_1445, _1644); + half _1647 = min(_1446, _1645); + half _1648 = min(_1545, _1585); + half _1649 = min(_1546, _1586); + half _1650 = min(_1646, _1648); + half _1651 = min(_1647, _1649); + half _1652 = max(_1505, _1525); + half _1653 = max(_1506, _1526); + half _1654 = max(_1445, _1652); + half _1655 = max(_1446, _1653); + half _1656 = max(_1545, _1585); + half _1657 = max(_1546, _1586); + half _1658 = max(_1654, _1656); + half _1659 = max(_1655, _1657); + half _1660 = min(_1525, _1545); + half _1661 = min(_1526, _1546); + half _1662 = min(_1465, _1660); + half _1663 = min(_1466, _1661); + half _1664 = min(_1565, _1605); + half _1665 = min(_1566, _1606); + half _1666 = min(_1662, _1664); + half _1667 = min(_1663, _1665); + half _1668 = max(_1525, _1545); + half _1669 = max(_1526, _1546); + half _1670 = max(_1465, _1668); + half _1671 = max(_1466, _1669); + half _1672 = max(_1565, _1605); + half _1673 = max(_1566, _1606); + half _1674 = max(_1670, _1672); + half _1675 = max(_1671, _1673); + + half _1684 = 1.h - _1626; + half _1685 = 1.h - _1627; + half _1692 = 1.h - _1642; + half _1693 = 1.h - _1643; + half _1700 = 1.h - _1658; + half _1701 = 1.h - _1659; + half _1708 = 1.h - _1674; + half _1709 = 1.h - _1675; + + half _1688 = min(_1618, _1684) * (1.h / _1626); + half _1689 = min(_1619, _1685) * (1.h / _1627); + half _1696 = min(_1634, _1692) * (1.h / _1642); + half _1697 = min(_1635, _1693) * (1.h / _1643); + half _1704 = min(_1650, _1700) * (1.h / _1658); + half _1705 = min(_1651, _1701) * (1.h / _1659); + half _1712 = min(_1666, _1708) * (1.h / _1674); + half _1713 = min(_1667, _1709) * (1.h / _1675); + + half _3064 = max(_1688, 0.h); + half _3075 = max(_1689, 0.h); + half _3096 = max(_1696, 0.h); + half _3107 = max(_1697, 0.h); + half _3128 = max(_1704, 0.h); + half _3139 = max(_1705, 0.h); + half _3160 = max(_1712, 0.h); + half _3171 = max(_1713, 0.h); + + half _1732 = 1.h - _1159; + + half _1747 = ( _699 * _1732) * (1.h / ((0.03125h - _1618) + _1626)); + half _1748 = ( _700 * _1732) * (1.h / ((0.03125h - _1619) + _1627)); + half _1755 = ( _91 * _1732) * (1.h / ((0.03125h - _1634) + _1642)); + half _1756 = ( _208 * _1732) * (1.h / ((0.03125h - _1635) + _1643)); + half _1763 = ( _699 * _1159) * (1.h / ((0.03125h - _1650) + _1658)); + half _1764 = ( _700 * _1159) * (1.h / ((0.03125h - _1651) + _1659)); + half _1771 = ( _91 * _1159) * (1.h / ((0.03125h - _1666) + _1674)); + half _1772 = ( _208 * _1159) * (1.h / ((0.03125h - _1667) + _1675)); + + half _1773 = _1747 * (hSharp * sqrt(min(_3064, 1.h))); + half _1774 = _1748 * (hSharp * sqrt(min(_3075, 1.h))); + half _1775 = _1755 * (hSharp * sqrt(min(_3096, 1.h))); + half _1776 = _1756 * (hSharp * sqrt(min(_3107, 1.h))); + half _1777 = _1763 * (hSharp * sqrt(min(_3128, 1.h))); + half _1778 = _1764 * (hSharp * sqrt(min(_3139, 1.h))); + half _1783 = _1771 * (hSharp * sqrt(min(_3160, 1.h))); + half _1784 = _1772 * (hSharp * sqrt(min(_3171, 1.h))); + + half _1780 = (_1775 + _1747) + _1777; + half _1782 = (_1776 + _1748) + _1778; + half _1786 = (_1755 + _1773) + _1783; + half _1788 = (_1756 + _1774) + _1784; + half _1790 = (_1763 + _1773) + _1783; + half _1792 = (_1764 + _1774) + _1784; + half _1795 = (_1777 + _1775) + _1771; + half _1796 = (_1778 + _1776) + _1772; + + half _1813 = 1.h / ((((_1795 + _1780) + ((((_1775 + _1773) + _1777) + _1783) * 2.h)) + _1786) + _1790); + half _1814 = 1.h / ((((_1796 + _1782) + ((((_1776 + _1774) + _1778) + _1784) * 2.h)) + _1788) + _1792); + + half3 _1832 = ((((((((_1782 * _1280) + (_1774 * (_1272 + _1260))) + (_1796 * _1344)) + (_1788 * _1300)) + (_1792 * _1328)) + (_1784 * (_1360 + _1352))) + (_1778 * (_1336 + _1320))) + (_1776 * (_1312 + _1292))) * _1814; + half3 colorOut4 = saturate(_1832); + + colorOut4 = PrepareForOutput(colorOut4); + + if ((_58 <= _55.z) && (_1153 <= _55.w)) + { + half3 _1987 = ((((((((_1196 * _1780) + ((_1192 + _1179) * _1773)) + (_1208 * _1786)) + (_1230 * _1790)) + (_1244 * _1795)) + ((_1252 + _1248) * _1783)) + ((_1240 + _1226) * _1777)) + ((_1216 + _1204) * _1775)) * _1813; + half3 colorOut3 = saturate(_1987); + + colorOut3 = PrepareForOutput(colorOut3); + + ColorOut[uint2(_58, _1153)] = float4(float3(colorOut3), 1.f); + } + + if ((_1119 <= _55.z) && (_1153 <= _55.w)) + { + ColorOut[uint2(_1119, _1153)] = float4(float3(colorOut4), 1.f); + } + +#elif defined(USE_PACKED_MATH) \ + && !defined(USE_UPSCALING) +#if 0 // Disable the CS so it just outputs the input + uint2 _55 = CASData.cas2.xy; + uint _58 = _55.x + (((csInput.SV_GroupThreadID.x >> 1u) & 7u) | (csInput.SV_GroupID.x << 4u)); + uint ppx = _58; + uint ppy = ((((csInput.SV_GroupThreadID.x >> 3u) & 6u) | (csInput.SV_GroupThreadID.x & 1u)) | (csInput.SV_GroupID.y << 4u)) + _55.y; + + ColorOut[uint2(ppx, ppy)] = ColorIn.Load(int3(uint2(ppx, ppy), 0)); + + ppx += 8; + + ColorOut[uint2(ppx, ppy)] = ColorIn.Load(int3(uint2(ppx, ppy), 0)); + + ppy += 8; + + ColorOut[uint2(_58, ppy)] = ColorIn.Load(int3(uint2(_58, ppy), 0)); + ColorOut[uint2(ppx, ppy)] = ColorIn.Load(int3(uint2(ppx, ppy), 0)); +#else + + uint4 _55 = CASData.rectLimits0; + + uint _58 = ((csInput.SV_GroupThreadID.x >> 1) & 7) + | (csInput.SV_GroupID.x << 4); + _58 += _55.x; + + uint _59 = ((csInput.SV_GroupThreadID.x >> 3) & 6) + | (csInput.SV_GroupThreadID.x & 1) + | (csInput.SV_GroupID.y << 4); + _59 += _55.y; + + uint2 pp = uint2(_58, _59); + + uint _107 = pp.x - 1; + uint _87 = pp.x; + uint _118 = pp.x + 1; + + uint _89 = pp.y - 1; + uint _105 = pp.y; + uint _127 = pp.y + 1; + + uint _150 = pp.x + 7; + uint _138 = pp.x + 8; + uint _167 = pp.x + 9; + + half3 _91 = ColorIn.Load(int3( _87, _89, 0)).rgb; + half3 _106 = ColorIn.Load(int3(_107, _105, 0)).rgb; + half3 _109 = ColorIn.Load(int3( _87, _105, 0)).rgb; + half3 _119 = ColorIn.Load(int3(_118, _105, 0)).rgb; + half3 _128 = ColorIn.Load(int3( _87, _127, 0)).rgb; + half3 _139 = ColorIn.Load(int3(_138, _89, 0)).rgb; + half3 _151 = ColorIn.Load(int3(_150, _105, 0)).rgb; + half3 _156 = ColorIn.Load(int3(_138, _105, 0)).rgb; + half3 _168 = ColorIn.Load(int3(_167, _105, 0)).rgb; + half3 _173 = ColorIn.Load(int3(_138, _127, 0)).rgb; + + _91 = PrepareForProcessing( _91); + _106 = PrepareForProcessing(_106); + _109 = PrepareForProcessing(_109); + _119 = PrepareForProcessing(_119); + _128 = PrepareForProcessing(_128); + _139 = PrepareForProcessing(_139); + _151 = PrepareForProcessing(_151); + _156 = PrepareForProcessing(_156); + _168 = PrepareForProcessing(_168); + _173 = PrepareForProcessing(_173); + + half _193 = _91.y; + half _194 = _139.y; + half _213 = _106.y; + half _214 = _151.y; + half _233 = _109.y; + half _234 = _156.y; + half _253 = _119.y; + half _254 = _168.y; + half _273 = _128.y; + half _274 = _173.y; + + half _280 = min(_193, _213); + half _281 = min(_194, _214); + half _282 = min(_280, _233); + half _283 = min(_281, _234); + half _284 = min(_253, _273); + half _285 = min(_254, _274); + half _286 = min(_284, _282); + half _287 = min(_285, _283); + + half _288 = max(_193, _213); + half _289 = max(_194, _214); + half _290 = max(_288, _233); + half _291 = max(_289, _234); + half _292 = max(_253, _273); + half _293 = max(_254, _274); + half _294 = max(_292, _290); + half _295 = max(_293, _291); + + half _299 = 1.h - _294; + half _300 = 1.h - _295; + + half _303 = min(_286, _299) * (1.h / _294); + half _304 = min(_287, _300) * (1.h / _295); + + half _981 = saturate(_303); + half _992 = saturate(_304); + + half hSharp = f16tof32(CASData.upscalingConst1.sharpAsHalf & 0xFFFF); + + half _315 = hSharp * sqrt(_981); + half _316 = hSharp * sqrt(_992); + + half _322 = 1.h / ((_315 * 4.h) + 1.h); + half _323 = 1.h / ((_316 * 4.h) + 1.h); + + half3 _329 = (((_151 + _139 + _168 + _173) * _316) + _156) * _323; + half3 colorOut2 = saturate(_329); + + colorOut2 = PrepareForOutput(colorOut2); + + if ((pp.x <= _55.z) && (pp.y <= _55.w)) + { + half3 _388 = (((_106 + _91 + _119 + _128) * _315) + _109) * _322; + half3 colorOut1 = saturate(_388); + + colorOut1 = PrepareForOutput(colorOut1); + + ColorOut[pp] = float4(colorOut1, 1.f); + } + + pp.x += 8; + + if ((pp.x <= _55.z) && (pp.y <= _55.w)) + { + ColorOut[pp] = float4(colorOut2, 1.f); + } + + pp.y += 8; + + uint _507 = pp.y - 1; + uint _520 = pp.y; + uint _539 = pp.y + 1; + + half3 _509 = ColorIn.Load(int3( _87, _507, 0)).rgb; + half3 _521 = ColorIn.Load(int3(_107, _520, 0)).rgb; + half3 _524 = ColorIn.Load(int3( _87, _520, 0)).rgb; + half3 _531 = ColorIn.Load(int3(_118, _520, 0)).rgb; + half3 _540 = ColorIn.Load(int3( _87, _539, 0)).rgb; + half3 _547 = ColorIn.Load(int3(_138, _507, 0)).rgb; + half3 _556 = ColorIn.Load(int3(_150, _520, 0)).rgb; + half3 _561 = ColorIn.Load(int3(_138, _520, 0)).rgb; + half3 _570 = ColorIn.Load(int3(_167, _520, 0)).rgb; + half3 _575 = ColorIn.Load(int3(_138, _539, 0)).rgb; + + _509 = PrepareForProcessing(_509); + _547 = PrepareForProcessing(_547); + _521 = PrepareForProcessing(_521); + _556 = PrepareForProcessing(_556); + _524 = PrepareForProcessing(_524); + _561 = PrepareForProcessing(_561); + _531 = PrepareForProcessing(_531); + _570 = PrepareForProcessing(_570); + _540 = PrepareForProcessing(_540); + _575 = PrepareForProcessing(_575); + + half _596 = _509.y; + half _597 = _547.y; + half _616 = _521.y; + half _617 = _556.y; + half _636 = _524.y; + half _637 = _561.y; + half _656 = _531.y; + half _657 = _570.y; + half _676 = _540.y; + half _677 = _575.y; + + half _683 = min(_596, _616); + half _684 = min(_597, _617); + half _685 = min(_683, _636); + half _686 = min(_684, _637); + half _687 = min(_656, _676); + half _688 = min(_657, _677); + half _689 = min(_687, _685); + half _690 = min(_688, _686); + + half _691 = max(_596, _616); + half _692 = max(_597, _617); + half _693 = max(_691, _636); + half _694 = max(_692, _637); + half _695 = max(_656, _676); + half _696 = max(_657, _677); + half _697 = max(_695, _693); + half _698 = max(_696, _694); + + half _701 = 1.h - _697; + half _702 = 1.h - _698; + + half _705 = min(_689, _701) * (1.h / _697); + half _706 = min(_690, _702) * (1.h / _698); + + half _1194 = saturate(_705); + half _1205 = saturate(_706); + + half _711 = hSharp * sqrt(_1194); + half _712 = hSharp * sqrt(_1205); + + half _717 = 1.h / ((_711 * 4.h) + 1.h); + half _718 = 1.h / ((_712 * 4.h) + 1.h); + + half3 _724 = (((_556 + _547 + _570 + _575) * _712) + _561) * _718; + half3 colorOut4 = saturate(_724); + + colorOut4 = PrepareForOutput(colorOut4); + + if ((pp.x <= _55.z) && (pp.y <= _55.w)) + { + half3 _783 = (((_521 + _509 + _531 + _540) * _711) + _524) * _717; + half3 colorOut3 = saturate(_783); + + colorOut3 = PrepareForOutput(colorOut3); + + ColorOut[uint2(_58, pp.y)] = float4(colorOut3, 1.f); + } + + if ((pp.x <= _55.z) && (pp.y <= _55.w)) + { + ColorOut[pp] = float4(colorOut4, 1.f); + } + +#endif +#endif // USE_PACKED_MATH +} diff --git a/shaders/ContrastAdaptiveSharpening/RootSignature.hlsl b/shaders/ContrastAdaptiveSharpening/RootSignature.hlsl new file mode 100644 index 00000000..87118912 --- /dev/null +++ b/shaders/ContrastAdaptiveSharpening/RootSignature.hlsl @@ -0,0 +1,83 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=6), " \ + "SRV(t1, space=6), " \ + "SRV(t2, space=6, flags=DATA_VOLATILE), " \ + "SRV(t3, space=6), " \ + "SRV(t4, space=6), " \ + "SRV(t5, space=6), " \ + "SRV(t7, space=6), " \ + "SRV(t8, space=6), " \ + "SRV(t9, space=6), " \ + "SRV(t10, space=6), " \ + "SRV(t11, space=6), " \ + "SRV(t12, space=6), " \ + "SRV(t13, space=6), " \ + "SRV(t14, space=6), " \ + "SRV(t15, space=6), " \ + "SRV(t16, space=6), " \ + "SRV(t17, space=6), " \ + "SRV(t18, space=6), " \ + "SRV(t19, space=6), " \ + "SRV(t20, space=6), " \ + "SRV(t21, space=6), " \ + "SRV(t22, space=6), " \ + "SRV(t23, space=6), " \ + "SRV(t24, space=6), " \ + "SRV(t25, space=6), " \ + "SRV(t26, space=6), " \ + "UAV(u0, space=6), " \ + "UAV(u1, space=6), " \ + "SRV(t27, space=6), " \ + "SRV(t28, space=6) " \ + "), " \ + \ + "DescriptorTable( " \ + "Sampler(s0, numDescriptors=10, space=6), " \ + "Sampler(s10, numDescriptors=2, space=6) " \ + "), " \ + \ + "SRV(t6, space=6), " \ + "CBV(b0, space=6), " \ + "CBV(b1, space=6), " \ + \ + "DescriptorTable( " \ + "SRV(t2, space=7), " \ + "SRV(t3, space=7), " \ + "SRV(t5, space=7, flags=DATA_VOLATILE), " \ + "SRV(t6, space=7, flags=DATA_VOLATILE), " \ + "UAV(u0, space=7), " \ + "UAV(u1, space=7), " \ + "UAV(u2, space=7), " \ + "UAV(u3, space=7), " \ + "SRV(t7, numDescriptors=12, space=7, flags=DATA_VOLATILE) " \ + "), " \ + \ + "SRV(t0, space=7), " \ + "SRV(t1, space=7), " \ + "SRV(t4, space=7), " \ + "CBV(b0, space=7), " \ + "CBV(b1, space=7), " \ + "CBV(b2, space=7), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8), " \ + "UAV(u0, space=8) " \ + "), " \ + \ + "CBV(b0, space=8), " \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s12, filter=FILTER_MIN_MAG_MIP_POINT, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s13, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s14, filter=FILTER_MIN_MAG_MIP_LINEAR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s15, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s16, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s17, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s18, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s19, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s20, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_LESS, space=6), " \ + "StaticSampler(s21, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_GREATER, space=6) " diff --git a/shaders/Copy/Copy_ps.hlsl b/shaders/Copy/Copy_ps.hlsl new file mode 100644 index 00000000..38984ed2 --- /dev/null +++ b/shaders/Copy/Copy_ps.hlsl @@ -0,0 +1,80 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +Texture2D inputTexture : register(t0, space8); +SamplerState inputSampler : register(s0, space8); + +struct PSInputs +{ + float2 uv : TEXCOORD0; + float4 pos : SV_Position; +}; + +#if SDR_USE_GAMMA_2_2 + #define GAMMA_TO_LINEAR(x) pow(x, 2.2f) + #define LINEAR_TO_GAMMA(x) pow(x, 1.f / 2.2f) +#else + #define GAMMA_TO_LINEAR(x) gamma_sRGB_to_linear(x) + #define LINEAR_TO_GAMMA(x) gamma_linear_to_sRGB(x) +#endif + +[RootSignature(ShaderRootSignature)] +float4 PS(PSInputs inputs) : SV_Target +{ + float4 color = inputTexture.Sample(inputSampler, inputs.uv); + +#if defined(OUTPUT_TO_R16G16B16A16_SFLOAT) \ + || defined(OUTPUT_TO_R10G10B10A2) + + if (HdrDllPluginConstants.IsAtEndOfFrame) + { +#if defined(OUTPUT_TO_R16G16B16A16_SFLOAT) + if (HdrDllPluginConstants.DisplayMode == 2) // HDR scRGB + { +#if 1 + // Clamp to AP0D65 to avoid invalid colors + color.rgb = BT709_To_AP0D65(color.rgb); + color.rgb = max(color.rgb, 0.f); + color.rgb = AP0D65_To_BT709(color.rgb); +#endif + } + else if (HdrDllPluginConstants.DisplayMode == -1) // SDR on scRGB HDR (gamma to linear space conversion) + { +#if !SDR_LINEAR_INTERMEDIARY + color.rgb = GAMMA_TO_LINEAR(color.rgb); +#endif // !SDR_LINEAR_INTERMEDIARY + +#if CLAMP_INPUT_OUTPUT || 1 + color.rgb = saturate(color.rgb); // Remove any non SDR color, this mode is just meant for debugging SDR in HDR +#endif // CLAMP_INPUT_OUTPUT || 1 + const float paperWhite = HdrDllPluginConstants.HDRGamePaperWhiteNits / WhiteNits_sRGB; + color.rgb *= paperWhite; + } +#endif // defined(OUTPUT_TO_R16G16B16A16_SFLOAT) + +#if defined(OUTPUT_TO_R10G10B10A2) + if (HdrDllPluginConstants.DisplayMode == 1) // HDR10 PQ BT.2020 + { + // There is no need to clamp values above 1 here as the output buffer is unorm10 so it will clip anything beyond 0-1. + // Negative values need to be clamped though to avoid doing pow on a negative values. + color.rgb = BT709_To_BT2020(color.rgb); + color.rgb = max(color.rgb, 0.f); + color.rgb = Linear_to_PQ(color.rgb, PQMaxWhitePoint); + } +#if SDR_LINEAR_INTERMEDIARY + else if (HdrDllPluginConstants.DisplayMode == 0) // SDR (linear to gamma space conversion) + { + + color.rgb = LINEAR_TO_GAMMA(color.rgb); + } +#endif // SDR_LINEAR_INTERMEDIARY + +#endif // defined(OUTPUT_TO_R10G10B10A2) + + } + +#endif // defined(OUTPUT_TO_R16G16B16A16_SFLOAT) || defined(OUTPUT_TO_R10G10B10A2) + + return color; +} diff --git a/shaders/Copy/RootSignature.hlsl b/shaders/Copy/RootSignature.hlsl new file mode 100644 index 00000000..4ac41be6 --- /dev/null +++ b/shaders/Copy/RootSignature.hlsl @@ -0,0 +1,14 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8) " \ + "), " \ + \ + "DescriptorTable( " \ + "Sampler(s0, space=8) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ diff --git a/shaders/FilmGrain/FilmGrain_FF75_ps.hlsl b/shaders/FilmGrain/FilmGrain_FF75_ps.hlsl deleted file mode 100644 index dac50022..00000000 --- a/shaders/FilmGrain/FilmGrain_FF75_ps.hlsl +++ /dev/null @@ -1,108 +0,0 @@ -#define ENABLE_HDR 1 -#define HDR_GAME_PAPER_WHITE 2.5f -#define FILM_GRAIN_TEXTURE_SIZE 1024u - -cbuffer _13_15 : register(b0, space0) -{ - float4 filmGrainColorAndIntensity : packoffset(c0); -}; - -Texture2D TonemappedColorTexture : register(t0, space8); // Possibly in gamma space in SDR -SamplerState Sampler0 : register(s0, space8); - -static float4 TEXCOORD; -static float4 SV_Target; - -struct SPIRV_Cross_Input -{ - float4 TEXCOORD : TEXCOORD0; -}; - -struct SPIRV_Cross_Output -{ - float4 SV_Target : SV_Target0; -}; - -float gamma_linear_to_sRGB(float channel) -{ - [flatten] - if (channel <= 0.0031308f) - { - channel = channel * 12.92f; - } - else - { - channel = 1.055f * pow(channel, 1.0f / 2.4f) - 0.055f; - } - return channel; -} - -float3 gamma_linear_to_sRGB(float3 Color) -{ - return float3(gamma_linear_to_sRGB(Color.r), - gamma_linear_to_sRGB(Color.g), - gamma_linear_to_sRGB(Color.b)); -} - -float gamma_sRGB_to_linear(float channel) -{ - [flatten] - if (channel <= 0.04045f) - { - channel = channel / 12.92f; - } - else - { - channel = pow((channel + 0.055f) / 1.055f, 2.4f); - } - return channel; -} - -float3 gamma_sRGB_to_linear(float3 Color) -{ - return float3(gamma_sRGB_to_linear(Color.r), - gamma_sRGB_to_linear(Color.g), - gamma_sRGB_to_linear(Color.b)); -} -float Luminance(float3 color) -{ - // Fixed from "wrong" values: 0.2125 0.7154 0.0721f - return dot(color, float3(0.2126f, 0.7152f, 0.0722f)); -} - -void frag_main() -{ - float3 tonemappedColor = TonemappedColorTexture.Sample(Sampler0, float2(TEXCOORD.x, TEXCOORD.y)); -#if ENABLE_HDR - tonemappedColor /= HDR_GAME_PAPER_WHITE; - tonemappedColor = gamma_linear_to_sRGB(tonemappedColor); - float inverseLuminance = saturate(1.f - Luminance(tonemappedColor)); -#else - float inverseLuminance = saturate(1.f - Luminance(tonemappedColor)); -#endif // ENABLE_HDR - -#if 0 // WIP fixes - const float filmGrainInvSize = 1.f / FILM_GRAIN_TEXTURE_SIZE; // This was "1.f / (FILM_GRAIN_TEXTURE_SIZE - 1u)", though that seems incorrect - const float filmGrainHalfSize = FILM_GRAIN_TEXTURE_SIZE * 0.5f; // This was "521.f", which seems like a mistake on 512 -#else - const float filmGrainInvSize = 1.f / (FILM_GRAIN_TEXTURE_SIZE - 1u); - const float filmGrainHalfSize = 521.f; //TODO: rename in case we keep this as 521 -#endif - float additiveFilmGrain = (((frac(sin(((float(int(uint(filmGrainColorAndIntensity.x) & (FILM_GRAIN_TEXTURE_SIZE - 1u))) * filmGrainInvSize) + TEXCOORD.x) + (((float(int(uint(filmGrainColorAndIntensity.y) & (FILM_GRAIN_TEXTURE_SIZE - 1u))) * filmGrainInvSize) + TEXCOORD.y) * filmGrainHalfSize)) * 493013.f) * 2.f) - 1.f) * filmGrainColorAndIntensity.z) * inverseLuminance; - float3 tonemappedColorWithFilmGrain = tonemappedColor + float3(additiveFilmGrain, additiveFilmGrain, additiveFilmGrain); // Note: we let this possibly generate colors below 1 for scRGB -#if ENABLE_HDR - tonemappedColorWithFilmGrain = gamma_sRGB_to_linear(tonemappedColorWithFilmGrain) * HDR_GAME_PAPER_WHITE; -#endif // ENABLE_HDR - - SV_Target.xyz = tonemappedColorWithFilmGrain; - SV_Target.w = 1.0f; -} - -SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input) -{ - TEXCOORD = stage_input.TEXCOORD; - frag_main(); - SPIRV_Cross_Output stage_output; - stage_output.SV_Target = SV_Target; - return stage_output; -} \ No newline at end of file diff --git a/shaders/FilmGrain/FilmGrain_ps.hlsl b/shaders/FilmGrain/FilmGrain_ps.hlsl new file mode 100644 index 00000000..dbbe0690 --- /dev/null +++ b/shaders/FilmGrain/FilmGrain_ps.hlsl @@ -0,0 +1,238 @@ +#include "../math.hlsl" +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +#define FILM_GRAIN_TEXTURE_SIZE 1024 + +#if SDR_LINEAR_INTERMEDIARY + #define GAMMA_TO_LINEAR(x) x + #define LINEAR_TO_GAMMA(x) x +#elif SDR_USE_GAMMA_2_2 + #define GAMMA_TO_LINEAR(x) pow(x, 2.2f) + #define LINEAR_TO_GAMMA(x) pow(x, 1.f / 2.2f) +#else + #define GAMMA_TO_LINEAR(x) gamma_sRGB_to_linear(x) + #define LINEAR_TO_GAMMA(x) gamma_linear_to_sRGB(x) +#endif + +#define IMPROVED_FILM_GRAIN true + +cbuffer CPushConstantWrapper_FilmGrain : register(b0, space0) +{ + float4 filmGrainColorAndIntensity : packoffset(c0); +}; + +Texture2D TonemappedColorTexture : register(t0, space8); // Possibly in gamma space in SDR +SamplerState Sampler0 : register(s0, space8); + +struct PSInput +{ + float4 TEXCOORD : TEXCOORD0; +}; + +// Better random generator +float rand(float2 uv) { + return frac(sin(dot(uv,float2(12.9898,78.233)))*43758.5453123); +} + + +// Returns a random number between 0 and 1 based on seed +float bethesdaRandom(float seed) { + return frac(sin(seed) * 493013.f); +} + +// This is an attempt to replicate Kodak Vision 5242 with (0,3) range: +// Should be channel independent (R/G/B), but just using R curve for now +// Reference target is actually just luminance * 2.046f; +// (0, 0) +// (0.5, 0.22) +// (1.5, 1.08) +// (2.5, 2.01) +// (3.0, 2.3) +float computeFilmDensity(float luminance) { + float scaledX = luminance * 3.0f; + float result = 3.386477f + (0.08886645f - 3.386477f)/pow(1.f + (scaledX/2.172591f),2.240936f); + return result; +} + +// Bartleson +// https://www.imaging.org/common/uploaded%20files/pdfs/Papers/2003/PICS-0-287/8583.pdf +float computeFilmGraininess(float density) { + float preComputedMin = 7.5857757502918375f; + float bofDOverC = 0.880f - (0.736f * density) - (0.003f * pow(density, 7.6f)); + return pow(10.f, bofDOverC); +} + + +[RootSignature(ShaderRootSignature)] +float4 PS(PSInput psInput) : SV_Target +{ +// TEXCOORD = float2 [0,1] relative to screen +// TonemappedColorTexture is the framebuffer? +// Generate random noise and overlay on top of screen buffer +// filmGrainColorAndIntensity +// .x - randomInt32? changed every frame? +// .y = randomInt32? changed every frame? +// .z = Film Grading Intensity (0 - 0.03) + + const float3 inputColor = TonemappedColorTexture.Sample(Sampler0, psInput.TEXCOORD.xy); + bool isHDR = HdrDllPluginConstants.DisplayMode > 0; + bool isInOutColorLinear = isHDR; +#if SDR_LINEAR_INTERMEDIARY + isInOutColorLinear |= HdrDllPluginConstants.DisplayMode <= 0; +#endif // SDR_LINEAR_INTERMEDIARY + + float3 outputColor; + + if (HdrDllPluginConstants.FilmGrainType == 0) + { + float3 color = inputColor; + + float filmGrainIntensity = filmGrainColorAndIntensity.z; + + float luminance; + + if (isInOutColorLinear) { + color /= PQMaxWhitePoint; + + // get relative luminance in normalized space + luminance = Luminance(color); + + color = BT709_To_AP0D65(color); + + color = Linear_to_PQ_approx(color); + } + else { + luminance = Luminance(GAMMA_TO_LINEAR(color)); + } + + float inverseLuminance = saturate(1.f - luminance); + + static const float filmGrainInvSize = 1.f / (FILM_GRAIN_TEXTURE_SIZE - 1); + static const float filmGrainHalfSize = 511.f; + // Applying modulus against 1023 will give value between 0 and 1023 + // Same two values for all texels this frame + float2 randomFromRange = int2(filmGrainColorAndIntensity.xy) & (FILM_GRAIN_TEXTURE_SIZE - 1); + + // Divide by 1023 to get a number between 0 and 1 + float2 randomNormalized = randomFromRange * filmGrainInvSize; + + // Offset by x/y position + float2 unique = randomNormalized + psInput.TEXCOORD.xy; + unique.y *= filmGrainHalfSize; + + // Unique each frame and texel. (Is it though?) + float seed = (unique.x + unique.y); + + // Generate a random number between 0 and 1; + float randomNumber = bethesdaRandom(seed); + + float luminanceShift = (randomNumber * 2.f) - 1.f; + + float additiveFilmGrain = (luminanceShift * (filmGrainIntensity * inverseLuminance)); + + outputColor = color + additiveFilmGrain; + + if (isInOutColorLinear) + { + outputColor = PQ_approx_to_Linear(outputColor); + + outputColor = max(outputColor, 0.f); + outputColor = AP0D65_To_BT709(outputColor); + + outputColor *= PQMaxWhitePoint; + } + +#if 0 // Output Visualization + float oldY = Luminance(GAMMA_TO_LINEAR(linearColor)); + float newY = Luminance(GAMMA_TO_LINEAR(outputColor)); + float yChange = (oldY/newY) - 1.f; + outputColor = abs(yChange); +#endif + + } + else + { + float fps = HdrDllPluginConstants.FilmGrainCap; + // Mod by FPS to ensure consistent range + float2 seed = psInput.TEXCOORD.xy; + if (fps > 0.f) { + float frameNumber = floor(HdrDllPluginConstants.RuntimeMS / (1000.f/(fps))); + // TODO: Use iteration? Use only if repeating is noticeable + // float iteration = fmod(frameNumber, (fps * fps)); + float frame = fmod(frameNumber, fps); + seed += (frame / fps); + } else { + seed += frac(HdrDllPluginConstants.RuntimeMS / 1000.f); + } + + float randomNumber = rand(seed); + + float colorY; + + float3 linearColor = inputColor; + if (isInOutColorLinear) { + linearColor /= PQMaxWhitePoint; + + // get relative luminance in normalized space + colorY = Luminance(linearColor); + + linearColor = BT709_To_AP0D65(linearColor); + + // approximation of PQ + linearColor = Linear_to_PQ_approx(linearColor); + } + else { + colorY = Luminance(GAMMA_TO_LINEAR(linearColor)); + } + // Film grain is based on film density + // Film works in negative, meaning black has no density + // The greater the film density (lighter), more perceived grain + // Simplified, grain scales with Y + + // Scaling is not not linear + + float yAdjustment = isHDR + ? (HdrDllPluginConstants.HDRGamePaperWhiteNits / PQMaxWhitePoint) + : 1.f; + + float adjustedColorY = linearNormalization(colorY,0.f,yAdjustment,0.f,1.f); + //float adjustedColorY = colorY; + + // Emulate density from a chosen film stock (Removed) + // float density = computeFilmDensity(adjustedColorY); + + // Ideal film density matches 0-3. Skip emulating film stock + // https://www.mr-alvandi.com/technique/measuring-film-speed.html + float density = adjustedColorY * 3.f; + + float graininess = computeFilmGraininess(density); + float randomFactor = (randomNumber * 2.f) - 1.f; + + float yChange = randomFactor + * graininess + * filmGrainColorAndIntensity.z // fFilmGrainAmountMax (0.03) + * 3.333f; // Bump to 10% + + yChange *= 0.0666f; + + outputColor = linearColor * (1.f + yChange); + + if (isInOutColorLinear) { + outputColor = PQ_approx_to_Linear(outputColor); + + outputColor = max(outputColor, 0.f); + outputColor = AP0D65_To_BT709(outputColor); + + outputColor *= PQMaxWhitePoint; + } + +#if 0 // Output Visualization + outputColor = abs(yChange); +#endif + } + + return float4(isHDR ? outputColor + : saturate(outputColor), 1.f); +} diff --git a/shaders/FilmGrain/RootSignature.hlsl b/shaders/FilmGrain/RootSignature.hlsl new file mode 100644 index 00000000..84482c7a --- /dev/null +++ b/shaders/FilmGrain/RootSignature.hlsl @@ -0,0 +1,13 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "RootConstants(num32BitConstants=4, b0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=8) " diff --git a/shaders/HDRComposite/HDRComposite_ps.hlsl b/shaders/HDRComposite/HDRComposite_ps.hlsl index f7a56683..245513f3 100644 --- a/shaders/HDRComposite/HDRComposite_ps.hlsl +++ b/shaders/HDRComposite/HDRComposite_ps.hlsl @@ -1,176 +1,71 @@ -// These are defined at compile time (shaders permutations) +#include "../shared.hlsl" +#include "../color.hlsl" +#include "../math.hlsl" +#include "RootSignature.hlsl" + +// These are defined at compile time (shaders permutations), +// they are generally all on by default, you can undefine them manually below if necessary. //#define APPLY_BLOOM //#define APPLY_TONEMAPPING -//#define APPLY_CINEMATICS +//#define APPLY_CINEMATICS // this is post processing //#define APPLY_MERGED_COLOR_GRADING_LUT -// Also in "ps_4105314757" -#define ENABLE_HDR 1 -#define HDR_GAME_PAPER_WHITE 2.5f -#define SDR_USE_GAMMA_2_2 0 -#define FIX_WRONG_SRGB_GAMMA 1 -// Also in "cs_580663709" -#define FIX_LUT_GAMMA_MAPPING 1 -#define LUT_SIZE 16.f -// Also sets "DISABLE_LUT" and "DISABLE_POST_PROCESS" and "DISABLE_INVERSE_TONEMAP" -#define DISABLE_TONEMAP 0 -#define DISABLE_POST_PROCESS 1 -#define DISABLE_LUT 1 -#define DISABLE_INVERSE_TONEMAP 1 -#define DISABLE_INVERSE_POST_PROCESS 1 -#define CLAMP_INPUT_OUTPUT 0 - -struct ResolutionBlock -{ - float2 f2_0; - float2 f2_1; - float2 f2_2; - float2 f2_3; - int4 i4_0; - float2 f2_4; - float2 f2_5; - float2 f2_6; - float2 f2_7; - float2 f2_8; - int2 i2_0; - int4 i4_1; - float f_0; - int i_0; - int i_1; - int i_2; -}; - -struct CameraBlock -{ - float3 f3_0; - int i_1; - float4x4 f4x4_0; - float4x4 f4x4_1; - float4x4 f4x4_2; - float4x4 f4x4_3; - float4x4 f4x4_4; - float4x4 f4x4_5; - float3 f3_1; - int i_0; - float4x4 f4x4_6; - float4x4 f4x4_7; - float4x4 f4x4_8; - float4 f4_0; - float4 f4_1; - float4 f4_2; - float4 f4_3; - float2 f2_0; - float f_0; - float f_1; -}; - -struct CameraBlockArray -{ - CameraBlock cb0; - CameraBlock cb1; - CameraBlock cb2; - ResolutionBlock rb0; - ResolutionBlock rb1; - ResolutionBlock rb2; - ResolutionBlock rb3; - ResolutionBlock rb4; -}; - -struct TonemappingParams -{ - float AcesParam0; - float AcesParam1; - float HableParam0; - float HableParam1; - float HableParam2; - float HableParam3; - float HableParam4; - int param7; //unused -}; - -struct SPerSceneConstants -{ - CameraBlockArray cba; -// WindData; -// CameraExposureData; -// GlobalLightData; -// GlobalShadowData; -// ReflectionProbeDescData; -// ReflectionProbeExposureData; -// SIndirectLightingData; -// ProbeRenderData; -// PlanetConstantsData; -// float pcs0; -// int pcs1; -// int pcs2; -// float pcs3; -// TiledBinning_idTech7FrameData; -// float pcs4; -// float pcs5; -// float pcs6; -// float pcs7; -// float pcs8; -// float pcs9; -// float pcs10; -// float pcs11; -// float pcs12; -// int pcs13; -// int pcs14; -// int pcs15; -// HairConstantData; -// FogParams; -// VolumetricLightingApplyParameters; -// PrecomputeTransmittanceParameters; -// HeightfieldData; -// MomentBasedOITSettings; -// TiledLightingDebug; -// GPUDebugGeometrySettings; -// TonemappingParams; -// EffectsAlphaThresholdParams; -}; - -struct PushConstantWrapper_HDRComposite -{ - uint HdrCmpDatIndex; - uint Tmo; //tone mapping operator - float BloomMultiplier; -}; - -struct FrameDebug { int2 u1; int2 u2; int2 u3; int u4; int u5; float u6; int u7; int u8; int u9; int u10; int u11; int u12; int u13; }; -struct FrameData { int u1; int u2; float2 u3; float u4; float u5; float u6; float Gamma; FrameDebug u8; float4 u9; float u10; float u11; int u12; int u13; }; - -struct HDRCompositeData +// This disables most other features (post processing/cinematics, LUTs, ...) +#define ENABLE_TONEMAP 1 +// 0 disable contrast adjustment +// 1 original (weak, generates values beyond 0-1 which then might get clipped) +// 2 improved (looks more natural, avoids values below 0, but will overshoot beyond 1 more often, and will raise blacks) +// 3 Sigmoidal inspired and biases contrast increases towards the lower and top end +// (optimisation left if "contrastIntensity" doesn't go below 1) +#define POST_PROCESS_CONTRAST_TYPE (FORCE_VANILLA_LOOK ? 1 : 3) +#define ENABLE_LUT 1 +// LUTs are too low resolutions to resolve gradients smoothly if the LUT color suddenly changes between samples +#define ENABLE_LUT_TETRAHEDRAL_INTERPOLATION (FORCE_VANILLA_LOOK ? 0 : 1) +//TODO: WIP +#define ENABLE_LUT_EXTRAPOLATION (FORCE_VANILLA_LOOK ? 0 : 0) +#define ENABLE_REPLACED_TONEMAP 1 +#define ALLOW_EXPAND_GAMUT 1 +// 0 inverts all of the range (the whole image), to then re-tonemap it with an HDR tonemapper. +// 1 keeps SDR toe/shadow, invert tonemap in the rest of the range. +// 2 keeps SDR toe/shadow and midtones, inverts highlights only. +// Only invert highlights, which helps conserve the SDR filmic look (shadow crush) and altered colors. +// The alternative is to keep the linear space image tonemapped by the lightweight DICE tonemapper, +// or to replicate the SDR tonemapper by luminance, though both would alter the look too much and break some scenes. +#define INVERT_TONEMAP_TYPE 2 +// 0 per channel (also fallback) +// 1 on the luminance +// 2 in ICtCp +// If we are running in HDR, and we are keeping the SDR tonemapped shadow and midtones ("INVERT_TONEMAP_TYPE" >0), +// then if this is 1+, we replace the SDR tonemapped image with one tonemapped by channel instead than by luminance, to maintain more saturation. +#define HDR_TONEMAP_TYPE 2 +// Note: this could cause a disconnect in gradients, as LUTs shift colors by channel, not by luminance. +// It also dampens colors, making them darker and less saturation, especially bright colors. +#define HDR_INVERT_SDR_TONEMAP_BY_LUMINANCE 0 +#define DRAW_LUT 0 + + +cbuffer CSharedFrameData : register(b0, space6) { - float4 HighlightsColourFilter; - float4 ColourFilter; - float HableSaturation; - float BrightnessMultiplier; - float ContrastIntensity; - int i_0; //unused + FrameData SharedFrameData : packoffset(c0); }; -cbuffer SharedFrameData : register(b0, space6) -{ - FrameData SharedFrameData; -} - -cbuffer PerSceneConstants : register(b0, space7) +cbuffer CPerSceneConstants : register(b0, space7) { - float4 PerSceneConstants[3269] : packoffset(c0); + float4 PerSceneConstants[3269] : packoffset(c0); }; -cbuffer PushConstantWrapper_HDRComposite : register(b0, space0) +cbuffer CPushConstantWrapper_HDRComposite : register(b0, space0) { - PushConstantWrapper_HDRComposite PcwHdrComposite : packoffset(c0); + PushConstantWrapper_HDRComposite PcwHdrComposite : packoffset(c0); }; -Texture2D InputColour : register(t0, space9); +Texture2D InputColorTexture : register(t0, space9); #if defined(APPLY_MERGED_COLOR_GRADING_LUT) -Texture2D LutMask : register(t1, space9); -Texture3D Lut : register(t3, space9); +Texture2D LUTMaskTexture : register(t1, space9); +Texture3D LUTTexture : register(t3, space9); #endif @@ -190,13 +85,13 @@ SamplerState Sampler0 : register(s0, space9); // Clamped Bilinear struct PSInput { - float4 SV_Position : SV_Position0; - float2 TEXCOORD : TEXCOORD0; + float4 SV_Position : SV_Position0; + float2 TEXCOORD : TEXCOORD0; }; struct PSOutput { - float4 SV_Target : SV_Target0; + float4 SV_Target : SV_Target0; }; // 1.1920928955078125e-07 @@ -216,612 +111,1278 @@ struct PSOutput // exp2(x * 1.44269502162933349609375f) is the same as exp(x) -#define FLT10_MAX 64512.f -#define FLT11_MAX 65024.f -#define FLT16_MAX 65504.f +static const float SDRTonemapHDRStrength = 1.f; +static const float PostProcessStrength = 1.f; +// 0 Ignored, 1 ACES Reference, 2 ACES Custom, 3 Hable, 4+ Disable tonemapper +static const uint ForceTonemapper = 0; +// 1 is neutral. Suggested range 0.5-1.5 though 1 is heavily suggested. +// Exposure to the user for more customization. +static const float HDRHighlightsModulation = 1.f; + +static const float ACES_a = 2.51f; +static const float ACES_b = 0.03f; +static const float ACES_c = 2.43f; +static const float ACES_d = 0.59f; +static const float ACES_e = 0.14f; -static float LUTStrenght = 0.f; -static float RestorePreLUTLuminance = 1.f; -static bool ForceACES = false; //TODO: delete once Hable works -float gamma_linear_to_sRGB(float channel) +template +T ACES( + T Color, + bool Clamp, + float modE, + float modA) { - [flatten] - if (channel <= 0.0031308f) - { - channel = channel * 12.92f; - } - else - { - channel = 1.055f * pow(channel, 1.0f / 2.4f) - 0.055f; - } - return channel; + Color = (Color * (modA * Color + ACES_b)) + / ((Color * (ACES_c * Color + ACES_d)) + modE); + + return Clamp ? saturate(Color) : Color; } -float3 gamma_linear_to_sRGB(float3 Color) +// ACESFilm by Krzysztof Narkowicz (https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/) +// (color * ((a * color) + b)) / (color * ((c * color) + d) + e) +template +T ACESReference( + T Color, + bool Clamp) { - return float3(gamma_linear_to_sRGB(Color.r), - gamma_linear_to_sRGB(Color.g), - gamma_linear_to_sRGB(Color.b)); + return ACES(Color, Clamp, ACES_e, ACES_a); } -float gamma_sRGB_to_linear(float channel) +// ACESFilm "per scene" +template +T ACESParametric( + in T Color, + in bool Clamp, + inout float modE, + inout float modA) { - [flatten] - if (channel <= 0.04045f) - { - channel = channel / 12.92f; - } - else - { - channel = pow((channel + 0.055f) / 1.055f, 2.4f); - } - return channel; + const float AcesParam0 = PerSceneConstants[3266u].x; // Constant is usually 11.2 + const float AcesParam1 = PerSceneConstants[3266u].y; // Constant is usually 0.022 + + modE = AcesParam1; + modA = ((0.56f / AcesParam0) + ACES_b) + (AcesParam1 / (AcesParam0 * AcesParam0)); + + return ACES(Color, Clamp, modE, modA); } -float3 gamma_sRGB_to_linear(float3 Color) +template +T ACES_Inverse( + T Color, + float modE, + float modA) { - return float3(gamma_sRGB_to_linear(Color.r), - gamma_sRGB_to_linear(Color.g), - gamma_sRGB_to_linear(Color.b)); + // ACES is not defined for any values beyond 0-1, as they already represent the 0-INF range. + Color = saturate(Color); + + T fixed0 = (-ACES_d * Color) + ACES_b; + T fixed1 = (ACES_c * Color) - modA; + + T variable_numerator_part0 = -fixed0; + T variable_numerator = sqrt((variable_numerator_part0 * variable_numerator_part0) - (4.f * modE * Color * fixed1)); + + T denominator = 2.f * fixed1; + + T result0 = (fixed0 + variable_numerator) / denominator; + T result1 = (fixed0 - variable_numerator) / denominator; + + // "result1" is likely what we always want + return max(result0, result1); } -float Luminance(float3 Color) +template +T ACESReference_Inverse(T Color) { - // Fixed from "wrong" values: 0.2125 0.7154 0.0721f - return dot(Color, float3(0.2126f, 0.7152f, 0.0722f)); + return ACES_Inverse(Color, ACES_e, ACES_a); } -static const float ACES_a = 2.51f; -static const float ACES_b = 0.03f; -static const float ACES_c = 2.43f; -static const float ACES_d = 0.59f; -static const float ACES_e = 0.14f; +template +T ACESParametric_Inverse(T Color, float modE, float modA) +{ + return ACES_Inverse(Color, modE, modA); +} -float3 ACES(float3 Colour, bool Clamp, float modE, float modA) +float HableEval( + float normX, + HableEvalParams eParams) { - Colour = (Colour * (modA * Colour + ACES_b)) / ((Colour * (ACES_c * Colour + ACES_d)) + modE); - return Clamp ? saturate(Colour) : Colour; + float channelOut = 0.f; + + // Toe + if (normX < eParams.params_x0) + { + if (normX > 0.f) + { + channelOut = exp2(((((log2(normX) * eParams.toeSegment_B) + eParams.toeSegment_optimised) * RCP_LOG2_E) + eParams.toeSegment_lnA_optimised) * LOG2_E); + } + } + // Mid + else if (normX < eParams.params_x1) + { + float evalMidSegment_y0 = normX + eParams.midSegment_offsetX; // was -(-hableParams.midSegment.offsetX) + if (evalMidSegment_y0 > 0.f) + { + channelOut = exp2(log2(evalMidSegment_y0) + eParams.midSegment_lnA_optimised); + } + } + // Shoulder (highlight) + else + { + // Note that this will "clip" to 1 way before +INF + + //float evalShoulderSegment_y0 = ((-1.f) - params_overshootX) + normX; // small optimisation from the original decompilation + float evalShoulderSegment_y0 = (1.f + eParams.params_overshootX) - normX; + float evalShoulderReturn = 0.f; + if (evalShoulderSegment_y0 > 0.f) + { + evalShoulderReturn = exp2(((eParams.shoulderSegment_B_optimised * log2(evalShoulderSegment_y0)) + eParams.shoulderSegment_lnA) * LOG2_E); + } + channelOut = eParams.params_overshootY - evalShoulderReturn; + } + return channelOut; } -// ACESFilm by Krzysztof Narkowicz (https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/) -// (color * ((a * color) + b)) / (color * ((c * color) + d) + e) -float3 ACESReference(float3 Colour, bool Clamp) +// https://github.com/johnhable/fw-public +// http://filmicworlds.com/blog/filmic-tonemapping-with-piecewise-power-curves/ +// This is NOT the Uncharted 2 tonemapper, which was also by Hable. +float3 Hable( + in float3 InputColor, + out HableParams hableParams) { - return ACES(Colour, Clamp, ACES_e, ACES_a); + // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L202 + + // Note that all these variables can vary depending on the level. + // The 2.2 pow is so you don't have to input very small numbers, it's not related to gamma. + const float toeLength = pow(saturate(PerSceneConstants[3266u].w), 2.2f); // Constant is usually 0.3 + const float toeStrength = saturate(PerSceneConstants[3266u].z); // Constant is usually 0.5 + const float shoulderLength = clamp(saturate(PerSceneConstants[3267u].y), EPSILON, BTHCNST); // Constant is usually 0.8 + const float shoulderStrength = max(PerSceneConstants[3267u].x, 0.f); // Constant is usually 9.9 + const float shoulderAngle = saturate(PerSceneConstants[3267u].z); // Constant is usually 0.3 + + //dstParams + float dstParams_x0 = toeLength * 0.5f; + float dstParams_y0 = (1.f - toeStrength) * dstParams_x0; + + float remainingY = 1.f - dstParams_y0; + + float y1_offset = (1.f - shoulderLength) * remainingY; + //dstParams + float dstParams_x1 = dstParams_x0 + y1_offset; + float dstParams_y1 = dstParams_y0 + y1_offset; + + float extraW = exp2(shoulderStrength) - LFLT1; + float initialW = dstParams_x0 + remainingY; + hableParams.dstParams.W = initialW + extraW; + + const float shoulderAngleXshoulderStrength = shoulderAngle * shoulderStrength; + // "W * " was optimised away by DXIL->SPIRV->HLSL conversion as down the line there was a "/ W" + float dstParams_overshootX = 2.f * shoulderAngleXshoulderStrength; + float dstParams_overshootY = 0.5f * shoulderAngleXshoulderStrength; + + // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L87 + + //dstCurve + float dstCurve_invW = 1.f / hableParams.dstParams.W; + + //params + float params_x0 = dstParams_x0 / hableParams.dstParams.W; + float params_x1 = dstParams_x1 / hableParams.dstParams.W; + float dx = y1_offset / hableParams.dstParams.W; + //float params_overshootX = dstParams_overshootX / hableParams.dstParams.W; // this step was optimised away + const float params_overshootX = dstParams_overshootX; + + // mid section + // AsSlopeIntercept https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L67 + float m = (abs(dx) < EPSILON) ? 1.f : (y1_offset / dx); + m += EPSILON; + float b = dstParams_y0 - (m * params_x0); + + hableParams.midSegment.offsetX = (b / m); //no minus + float midSegment_lnA_optimised = log2(m); + hableParams.midSegment.lnA = RCP_LOG2_E * midSegment_lnA_optimised; + // mid section end + + // toeM and shoulderM are missing because EvalDerivativeLinearGamma (https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L81-L85) + // evaluates to gamma * m * pow(m * x + b, gamma - 1) with gamma being 1 + // this just returns m + const float toeM = m; + const float shoulderM = m; + + // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L137-L138 + // max(EPSILON, pow(params_yX, gamma)) + hableParams.params.y0 = max(EPSILON, dstParams_y0); // is pow(x, gamma) with gamma = 1 + //OLD: hableParams.params.y0 = max(EPSILON, exp2(log2(dstParams_y0))); + hableParams.params.y1 = max(EPSILON, dstParams_y1); // is pow(x, gamma) with gamma = 1 + //OLD: hableParams.params.y1 = max(EPSILON, exp2(log2(dstParams_y1))); + + // pow(1.f + dstParams_overshootY, gamma) - 1.f + // -1 was optimised away as hableParams.shoulderSegment.offsetY is "params_overshootY + 1" + float params_overshootY = 1.f + dstParams_overshootY; // is pow(x, gamma) with gamma = 1 + //OLD: float params_overshootY = exp2(log2(1.f + dstParams_overshootY)); + + // toe section + // SolveAB https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L60 + hableParams.toeSegment.B = (toeM * params_x0) / (hableParams.params.y0 + EPSILON); + float toeSegment_optimised = log2(hableParams.params.y0); + float toeSegment_lnA_optimised = -hableParams.toeSegment.B * log(params_x0); + hableParams.toeSegment.lnA = toeSegment_optimised * RCP_LOG2_E + toeSegment_lnA_optimised; + // toe section end + + // shoulder section + float shoulderSection_x0 = 1.f + params_overshootX - params_x1; + float shoulderSection_y0 = params_overshootY - hableParams.params.y1; // 1 + x was optimised away + hableParams.shoulderSegment.offsetX = 1.f + params_overshootX; + hableParams.shoulderSegment.offsetY = params_overshootY; // x + 1 was optimised away + // SolveAB + hableParams.shoulderSegment.B = ((shoulderM * shoulderSection_x0) / (shoulderSection_y0 + EPSILON)); + float shoulderSegment_B_optimised = hableParams.shoulderSegment.B * RCP_LOG2_E; + hableParams.shoulderSegment.lnA = (log2(shoulderSection_y0) * RCP_LOG2_E) - (shoulderSegment_B_optimised * log2(shoulderSection_x0)); + // shoulder section end + + // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L6 + // Eval + float evalY0 = params_overshootY; + if (params_overshootX > 0.f) // log2(0) goes towards -INF, exp2(-INF) is 0. "params_overshootX" cannot be < 0 but it can occasionally be 0. + { + evalY0 -= exp2(((shoulderSegment_B_optimised * log2(params_overshootX)) + hableParams.shoulderSegment.lnA) * LOG2_E); + } + // Eval end + hableParams.invScale = 1.f / evalY0; + + hableParams.toeEnd = (min(params_x0, params_x1) / dstCurve_invW) / hableParams.invScale; + hableParams.shoulderStart = (max(params_x0, params_x1) / dstCurve_invW) / hableParams.invScale; + + HableEvalParams evalParams; + + evalParams.params_x0 = params_x0; + evalParams.params_x1 = params_x1; + evalParams.params_overshootX = params_overshootX; + evalParams.params_overshootY = params_overshootY; + evalParams.toeSegment_lnA_optimised = toeSegment_lnA_optimised; + evalParams.toeSegment_optimised = toeSegment_optimised; + evalParams.toeSegment_B = hableParams.toeSegment.B; + evalParams.midSegment_offsetX = hableParams.midSegment.offsetX; + evalParams.midSegment_lnA_optimised = midSegment_lnA_optimised; + evalParams.shoulderSegment_lnA = hableParams.shoulderSegment.lnA; + evalParams.shoulderSegment_B_optimised = shoulderSegment_B_optimised; + + float3 toneMapped; + + toneMapped = InputColor * dstCurve_invW; // = normX + + toneMapped.r = HableEval(toneMapped.r, evalParams); + toneMapped.g = HableEval(toneMapped.g, evalParams); + toneMapped.b = HableEval(toneMapped.b, evalParams); + + toneMapped *= hableParams.invScale; + + return toneMapped; // Note: this color needs no clamping, it's already implied to be between 0-1 } -// ACESFilm "per scene" -float3 ACESParametric(in float3 Colour, in bool Clamp, inout float modE, inout float modA) +// https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L21-L34 +float HableEval_Inverse( + float Channel, + HableItmParams hableItmParams) { - const float AcesParam0 = PerSceneConstants[3266u].x; - const float AcesParam1 = PerSceneConstants[3266u].y; - modE = AcesParam1; - modA = ((0.56f / AcesParam0) + ACES_b) + (AcesParam1 / (AcesParam0 * AcesParam0)); - return ACES(Colour, Clamp, modE, modA); + // clamp to smallest float + float y0 = max((Channel - hableItmParams.offsetY) / hableItmParams.scaleY, asfloat(0x00000001)); + + float x0 = exp((log(y0) - hableItmParams.lnA) / hableItmParams.B); + + return x0 / hableItmParams.scaleX + hableItmParams.offsetX; } -float3 ACES_Inverse(float3 Colour, float modE, float modA) +float Hable_Inverse( + float ColorChannel, + HableParams hableParams) { - //TODO: does this apply for `ACESParametric` as well? Probably - //TODO: figure out if we could still use the unclamped color. There should be a way to invert it. - // ACES is not defined for any values beyond 0-1 - Colour = saturate(Colour); - - float3 fixed0 = (-ACES_d * Colour) + ACES_b; - float3 fixed1 = (ACES_c * Colour) - modA; - - float3 variable_numerator_part0 = -fixed0; - float3 variable_numerator = sqrt((variable_numerator_part0 * variable_numerator_part0) - (4.f * modE * Colour * fixed1)); - - float3 denominator = 2.f * fixed1; - - float3 result0 = (fixed0 + variable_numerator) / denominator; - float3 result1 = (fixed0 - variable_numerator) / denominator; - - // "result1" is likely what we always want - return max(result0, result1); + // There's no inverse formula for colors beyond the 0-1 range + ColorChannel = saturate(ColorChannel); + + // scaleY and offsetY setup: https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L187-L197 + // toe + if (ColorChannel < hableParams.params.y0) + { + // scaleXY and offsetXY setup: https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L151-L154 + HableItmParams hableItmParams; + + hableItmParams.offsetX = 0.f; + hableItmParams.offsetY = 0.f; // * hableParams.invScale; + hableItmParams.scaleX = 1.f; + hableItmParams.scaleY = hableParams.invScale; // 1.f * hableParams.invScale + hableItmParams.lnA = hableParams.toeSegment.lnA; + hableItmParams.B = hableParams.toeSegment.B; + + ColorChannel = HableEval_Inverse(ColorChannel, hableItmParams); + } + // mid (linear segment) + else if (ColorChannel < hableParams.params.y1) + { + // scaleXY and offsetY setup: https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L125-L127 + HableItmParams hableItmParams; + + hableItmParams.offsetX = -hableParams.midSegment.offsetX; // minus was optimised away + hableItmParams.offsetY = 0.f; // * hableParams.invScale + hableItmParams.scaleX = 1.f; + hableItmParams.scaleY = hableParams.invScale; // 1.f * hableParams.invScale + hableItmParams.lnA = hableParams.midSegment.lnA; + hableItmParams.B = 1.f; + + ColorChannel = HableEval_Inverse(ColorChannel, hableItmParams); + } + // shoulder + else + { + // scaleXY setup: https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L175-L176 + HableItmParams hableItmParams; + + hableItmParams.offsetX = hableParams.shoulderSegment.offsetX; + hableItmParams.offsetY = hableParams.shoulderSegment.offsetY * hableParams.invScale; + hableItmParams.scaleX = -1.f; + hableItmParams.scaleY = -hableParams.invScale; // -1.f * hableParams.invScale + hableItmParams.lnA = hableParams.shoulderSegment.lnA; + hableItmParams.B = hableParams.shoulderSegment.B; + + ColorChannel = HableEval_Inverse(ColorChannel, hableItmParams); + } + + return ColorChannel * hableParams.dstParams.W; } -float3 ACESReference_Inverse(float3 Colour) +// https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L45-L52 +// NOTE: the precision of this inverse formula is within an offset of 0.0005 on most pixels, with highlights struggling more to being recovered. +float3 Hable_Inverse( + float3 InputColor, + HableParams hableParams) { - return ACES_Inverse(Colour, ACES_e, ACES_a); + InputColor.r = Hable_Inverse(InputColor.r, hableParams); + InputColor.g = Hable_Inverse(InputColor.g, hableParams); + InputColor.b = Hable_Inverse(InputColor.b, hableParams); + + return InputColor; +} + +// Tonemapper inspired from DICE. Can work by luminance to maintain hue. +// "HighlightsShoulderStart" should be between 0 and 1. Determines where the highlights curve (shoulder) starts. Leaving at zero for now as it's a simple and good looking default. +float3 DICETonemap( + float3 Color, + float MaxOutputLuminance, + float HighlightsShoulderStart = 0.f, + float HighlightsModulationPow = 1.f) +{ +#if DEVELOPMENT + HighlightsModulationPow = linearNormalization(HdrDllPluginConstants.DevSetting04, 0.f, 1.f, 0.5f, 1.5f); +#endif + +#if HDR_TONEMAP_TYPE == 1 // By luminance + + const float sourceLuminance = Luminance(Color); + if (sourceLuminance > 0.0f) + { + const float compressedLuminance = luminanceCompress(sourceLuminance, MaxOutputLuminance, HighlightsShoulderStart, false, FLT_MAX, HighlightsModulationPow); + Color *= compressedLuminance / sourceLuminance; + } + return Color; + +#elif HDR_TONEMAP_TYPE == 2 // By ICtCp "luma" + + //optimisation needed to not execute this for every pixel... + static const float TargetCllInPq = Linear_to_PQ(MaxOutputLuminance, PQMaxWhitePoint); + static const float ShoulderStartInPq = Linear_to_PQ(HighlightsShoulderStart, PQMaxWhitePoint); + + //to L'M'S' and normalize to 1 = 10000 nits + float3 PQ_LMS = BT709_to_LMS(Color / PQMaxWhitePoint); + PQ_LMS = max(PQ_LMS, 0.f); + PQ_LMS = Linear_to_PQ(PQ_LMS); + + //Intensity + float i1 = 0.5f * PQ_LMS.x + 0.5f * PQ_LMS.y; + + // return untouched Color if no tone mapping is needed + if (i1 < ShoulderStartInPq) + { + return Color; + } + else + { + float i2 = luminanceCompress(i1, TargetCllInPq, ShoulderStartInPq, false, FLT_MAX, HighlightsModulationPow); + + //saturation adjustment to blow out highlights + float minI = min((i1 / i2), (i2 / i1)); + + //to L'M'S' + PQ_LMS = ICtCp_to_PQ_LMS(float3(i2, + dot(PQ_LMS, PQ_LMS_2_ICtCp[1]) * minI, + dot(PQ_LMS, PQ_LMS_2_ICtCp[2]) * minI)); + + PQ_LMS = max(PQ_LMS, 0.f); + + //to LMS + float3 LMS = PQ_to_Linear(PQ_LMS); + //to RGB + return LMS_to_BT709(LMS) * PQMaxWhitePoint; + } + +#else // By channel + + Color.r = luminanceCompress(Color.r, MaxOutputLuminance, HighlightsShoulderStart, false, FLT_MAX, HighlightsModulationPow); + Color.g = luminanceCompress(Color.g, MaxOutputLuminance, HighlightsShoulderStart, false, FLT_MAX, HighlightsModulationPow); + Color.b = luminanceCompress(Color.b, MaxOutputLuminance, HighlightsShoulderStart, false, FLT_MAX, HighlightsModulationPow); + return Color; + +#endif } -float3 ACESParametric_Inverse(float3 Colour, float modE, float modA) +// don't set this above 1 as it will break the curve (turns into a double S curve instead of a single one) +// below 1 it increases the amount of additional contrast being applied +// only change this for testing +#define C 1 + +static const float den = log2(C + 1.f); + +// bias towards smaller numbers +void Log2Adjust(inout float Channel) { - return ACES_Inverse(Colour, modE, modA); +#if (C != 1) + Channel = log2(Channel * c + 1.f) + / den; + return; +#else + Channel = log2(Channel + 1.f); + return; +#endif } -// https://github.com/johnhable/fw-public -float3 Hable( - in float3 InputColour, - inout float params_y0, - inout float params_y1, - inout float dstParams_W, - inout float toeSegment_lnA, - inout float toeSegment_B, - inout float midSegment_offsetX, - inout float midSegment_lnA, - inout float shoulderSegment_offsetX, - inout float shoulderSegment_offsetY, - inout float shoulderSegment_scaleX, - inout float shoulderSegment_lnA, - inout float shoulderSegment_B, - inout float invScale) +// sigmoidal inspired contrast adjustment using 2 power curves +// normalizes both lower and upper part which are divided by contrastMidPoint +// and then applies a power curve based off of contrastIntensity on each part +float SigmoidalContrastAdjustment( + float Channel, + float contrastMidPoint, + float contrastIntensity, + float normalizationFactorLower, + float normalizationFactorUpper) { - // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L202 - - float toeLength = pow(saturate(PerSceneConstants[3266u].w), 2.2f); - float toeStrength = saturate(PerSceneConstants[3266u].z); - float shoulderLength = clamp(saturate(PerSceneConstants[3267u].y), EPSILON, BTHCNST); - float shoulderStrength = max(PerSceneConstants[3267u].x, 0.f); - float shoulderAngle = saturate(PerSceneConstants[3267u].z); - - //dstParams - float dstParams_x0 = toeLength * 0.5f; - float dstParams_y0 = (1.f - toeStrength) * dstParams_x0; - - float remainingY = 1.f - dstParams_y0; - - float y1_offset = (1.f - shoulderLength) * remainingY; - //dstParams - float dstParams_x1 = dstParams_x0 + y1_offset; - float dstParams_y1 = dstParams_y0 + y1_offset; - - float extraW = exp2(shoulderStrength) - LFLT1; - float initialW = dstParams_x0 + remainingY; - dstParams_W = initialW + extraW; - - // "W * " was optimised away by DXIL->SPIRV->HLSL conversion as down the line there is a "/ W" - float dstParams_overshootX = 2.f * shoulderAngle * shoulderStrength; - float dstParams_overshootY = 0.5f * shoulderAngle * shoulderStrength; - - // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L87 - - //dstCurve - float dstCurve_invW = 1.f / dstParams_W; - //params - float params_x0 = dstParams_x0 / dstParams_W; - float params_x1 = dstParams_x1 / dstParams_W; - //float params_overshootX = dstParams_overshootX / dstParams_W; // this step was optimised away - #define params_overshootX dstParams_overshootX - float dx = y1_offset / dstParams_W; - - // AsSlopeIntercept https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L67 - float m = (abs(dx) < EPSILON) ? 1.f : (y1_offset / dx); - m += EPSILON; - float b = dstParams_y0 - (m * params_x0); - - midSegment_offsetX = (b / m); //no minus - midSegment_lnA = log2(m); - - // EvalDerivativeLinearGamma https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L81 - // max(EPSILON, pow(params_yX, gamma)) - params_y0 = max(EPSILON, dstParams_y0); // is pow(x, 1) because gamma = 1 - //OLD: params_y0 = max(EPSILON, exp2(log2(dstParams_y0))); // toeM - params_y1 = max(EPSILON, dstParams_y1); // is pow(x, 1) because gamma = 1 - //OLD: params_y1 = max(EPSILON, exp2(log2(dstParams_y1))); // shoulderM - - // pow(1.f + dstParams_overshootY, gamma) - 1.f - // -1 was optimised away as shoulderSegment_offsetY is params_overshootY + 1 - float params_overshootY = 1.f + dstParams_overshootY; // is pow(x, 1) because gamma = 1 - //OLD: float params_overshootY = exp2(log2(1.f + dstParams_overshootY)); - - // toe section - // SolveAB https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L60 - toeSegment_B = (m * params_x0) / (params_y0 + EPSILON); - float _410 = log2(params_y0); //doesn't belong to SolveAB - toeSegment_lnA = toeSegment_B * (-log(params_x0)); - // toe section end - - // shoulder section - float shoulderSection_x0 = 1.f + params_overshootX - params_x1; - float shoulderSection_y0 = params_overshootY - params_y1; // 1 + x was optimised away - shoulderSegment_offsetX = 1.f + params_overshootX * dstParams_W; - float shoulderSegment_offsetX_optimised = 1.f + params_overshootX; - shoulderSegment_offsetY = params_overshootY; // x + 1 was optimised away - shoulderSegment_scaleX = -1.f; // could be optimised away if we move this outside of the PS - // SolveAB - shoulderSegment_B = ((m * shoulderSection_x0) / (shoulderSection_y0 + EPSILON)); - shoulderSegment_lnA = (log2(shoulderSection_y0) * RCP_LOG2_E) - (shoulderSegment_B * log2(shoulderSection_x0)); - float shoulderSegment_B_optimised = shoulderSegment_B * RCP_LOG2_E; - // shoulder section end - - // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L6 - // Eval - float evalY0 = 0.f; - if (params_overshootX > 0.f) - { - evalY0 = -exp2(((shoulderSegment_B_optimised * log2(params_overshootX)) + shoulderSegment_lnA) * LOG2_E); - } - // Eval end - invScale = 1.f / (evalY0 + params_overshootY); - - float3 toneMapped; - - for (uint channel = 0; channel < 3; channel++) - { - float normX = InputColour[channel] * dstCurve_invW; - bool isToeSegment = normX < params_x0; - float returnChannel = 0.f; - - if (isToeSegment && normX > 0.f) - { - returnChannel = exp2(((((log2(normX) * toeSegment_B) + _410) * RCP_LOG2_E) + toeSegment_lnA) * LOG2_E); - } - else if (normX < params_x1) - { - float evalMidSegment_y0 = normX + midSegment_offsetX; //is -(-midSegment_offsetX) - if (evalMidSegment_y0 > 0.f) - { - returnChannel = exp2(log2(evalMidSegment_y0) + midSegment_lnA); - } - } - else - { - //float evalShoulderSegment_y0 = ((-1.f) - params_overshootX) + normX; - float evalShoulderSegment_y0 = (normX - shoulderSegment_offsetX_optimised) * shoulderSegment_scaleX; - float evalShoulderReturn = 0.f; - if (evalShoulderSegment_y0 > 0.f) - { - evalShoulderReturn = exp2(((shoulderSegment_B_optimised * log2(evalShoulderSegment_y0)) + shoulderSegment_lnA) * LOG2_E); - } - returnChannel = params_overshootY - evalShoulderReturn; - } - toneMapped[channel] = returnChannel * invScale; - } - return toneMapped; + [flatten] + if (Channel <= contrastMidPoint) + { + Channel *= normalizationFactorLower; + // doing this for contrastIntensity below 1 greatly desaturates compared to not doing this + // look into if contrastIntensity ever goes below 1 + // and remove this check if it does not + if (contrastIntensity > 1.f) + { + Log2Adjust(Channel); + } + Channel = pow(Channel, contrastIntensity) + / normalizationFactorLower; + } + else + { + // protect against float issues + Channel = max(1.f - ((Channel - contrastMidPoint) * normalizationFactorUpper), asfloat(0x00000001)); + // doing this for contrastIntensity below 1 greatly desaturates compared to not doing this + // look into if contrastIntensity ever goes below 1 + // and remove this check if it does not + if (contrastIntensity > 1.f) + { + Log2Adjust(Channel); + } + Channel = (1.f - pow(Channel, contrastIntensity)) + / normalizationFactorUpper + contrastMidPoint; + } + + return Channel; } -// https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L21-L34 -float HableEvalInverse( - float Channel, - float offsetX, - float offsetY, - float scaleX, - float scaleY, - float lnA, - float B) +// "MidGrayScale" is how much the mid gray shifted from the originally intended tonemapped input (e.g. if we run this function on the untonemapped image, we can remap the mid gray) +float3 PostProcess( + float3 Color, + inout float ColorLuminance, + float MidGrayScale = 1.f) { - float y0 = (Channel - offsetY) / scaleY; - float x0 = 0.f; + const uint hdrCmpDatIndex = PcwHdrComposite.HdrCmpDatIndex; + const float4 highlightsColorFilter = HdrCmpDat[hdrCmpDatIndex].HighlightsColorFilter; + const float4 colorFilter = HdrCmpDat[hdrCmpDatIndex].ColorFilter; + const float hableSaturation = HdrCmpDat[hdrCmpDatIndex].HableSaturation; + const float brightnessMultiplier = HdrCmpDat[hdrCmpDatIndex].BrightnessMultiplier; // Neutral at 1 + const float contrastIntensity = HdrCmpDat[hdrCmpDatIndex].ContrastIntensity; // Neutral at 1 + const float contrastMidPoint = PerSceneConstants[316u].z * MidGrayScale; // Game usually has this around 0.18 (mid gray) + + ColorLuminance = Luminance(Color); + + // saturation adjustment a la Hable + // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicColorGrading.cpp#L307-L309 + Color = ((Color - ColorLuminance) * hableSaturation) + ColorLuminance; + + // Blend in another color based on the luminance. + Color += lerp(float3(0.f, 0.f, 0.f), ColorLuminance * highlightsColorFilter.rgb, highlightsColorFilter.a); + Color *= brightnessMultiplier; + +#if POST_PROCESS_CONTRAST_TYPE == 1 + + // Contrast adjustment (shift the colors from 0<->1 to (e.g.) -0.5<->0.5 range, multiply and shift back). + // The higher the distance from the contrast middle point, the more contrast will change the color. + // This generates negative colors for contrast > 1, and LUT's can't take them, unless they have "ENABLE_LUT_EXTRAPOLATION" + Color = ((Color - contrastMidPoint) * contrastIntensity) + contrastMidPoint; + +#elif POST_PROCESS_CONTRAST_TYPE == 2 + + // Do abs() to avoid negative power, even if it doesn't make 100% sense, these formulas are fine as long as they look good + Color = pow(abs(Color) / contrastMidPoint, contrastIntensity) * contrastMidPoint * sign(Color); + +#elif POST_PROCESS_CONTRAST_TYPE == 3 + + if (contrastIntensity != 1.f) // worth to do performance wise + { + float cIn = contrastIntensity; + // adjustment to match native better and make the curve be an S curve (too low intensity makes it a double S curve) + // only do them when contrastIntensity is above 1 because 1 is neutral (no adjustment) + // below 1 it matches native nicely (though idk if contrast is ever lowered) + if (contrastIntensity > 1.f) + { + cIn = contrastIntensity * (4.f / 3.f); + } + float cMid = contrastMidPoint; + + // normalization factors for lower and upper power curve + float normalizationFactorLower = 1.f / cMid; + float normalizationFactorUpper = 1.f / (1.f - cMid); + + Color.r = SigmoidalContrastAdjustment(Color.r, cMid, cIn, normalizationFactorLower, normalizationFactorUpper); + Color.g = SigmoidalContrastAdjustment(Color.g, cMid, cIn, normalizationFactorLower, normalizationFactorUpper); + Color.b = SigmoidalContrastAdjustment(Color.b, cMid, cIn, normalizationFactorLower, normalizationFactorUpper); + } - if (y0 > 0.f) - { - x0 = exp((log(y0) - lnA) / B); - } +#endif - return x0 / scaleX + offsetX; + Color = lerp(Color, colorFilter.rgb * MidGrayScale, colorFilter.a); + return Color; } -// https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicToneCurve.cpp#L45-L52 -float3 Hable_Inverse( - float3 InputColour, - float params_y0, - float params_y1, - float dstParams_W, - float toeSegment_lnA, - float toeSegment_B, - float midSegment_offsetX, - float midSegment_lnA, - float shoulderSegment_offsetX, - float shoulderSegment_offsetY, - float shoulderSegment_scaleX, - float shoulderSegment_lnA, - float shoulderSegment_B, - float invScale) +float3 PostProcess_Inverse( + float3 Color, + float OriginalColorLuminance, + float MidGrayScale = 1.f) { - float3 itmColour; - - for (uint channel = 0; channel < 3; channel++) - { - if (InputColour[channel] < params_y0) - { - itmColour[channel] = HableEvalInverse(InputColour[channel], - 0.f, - 0.f, // * invScale - 1.f, - 1.f * invScale, - toeSegment_lnA, - toeSegment_B); - } - else if (InputColour[channel] < params_y1) - { - itmColour[channel] = HableEvalInverse(InputColour[channel], - -midSegment_offsetX, // minus was optimised away - 0.f, // * invScale - 1.f, - 1.f * invScale, - midSegment_lnA, - 1.f); - } - else - { - itmColour[channel] = HableEvalInverse(InputColour[channel], - shoulderSegment_offsetX, - shoulderSegment_offsetY * invScale, - shoulderSegment_scaleX, - -1.f * invScale, - shoulderSegment_lnA, - shoulderSegment_B); - } - } - - return itmColour * dstParams_W; + const uint hdrCmpDatIndex = PcwHdrComposite.HdrCmpDatIndex; + const float4 highlightsColorFilter = HdrCmpDat[hdrCmpDatIndex].HighlightsColorFilter; + const float4 colorFilter = HdrCmpDat[hdrCmpDatIndex].ColorFilter; + const float hableSaturation = HdrCmpDat[hdrCmpDatIndex].HableSaturation; + const float brightnessMultiplier = HdrCmpDat[hdrCmpDatIndex].BrightnessMultiplier; // Neutral at 1 + const float contrastIntensity = HdrCmpDat[hdrCmpDatIndex].ContrastIntensity; // Neutral at 1 + const float contrastMidPoint = PerSceneConstants[316u].z * MidGrayScale; + + // We can't invert the color filter, so we will only inverse the post process by the unfiltered amount + const float colorFilterInverse = 1.f - colorFilter.a; + +#if POST_PROCESS_CONTRAST_TYPE == 1 + + Color = ((Color - contrastMidPoint) / contrastIntensity) + contrastMidPoint; + +#elif POST_PROCESS_CONTRAST_TYPE == 2 + + Color = pow(abs(Color) / contrastMidPoint, 1.f / contrastIntensity) * contrastMidPoint * sign(Color); + +#elif POST_PROCESS_CONTRAST_TYPE == 3 + + //TODO: implement + +#endif + + Color /= brightnessMultiplier; + + Color -= lerp(float3(0.f, 0.f, 0.f), OriginalColorLuminance * highlightsColorFilter.rgb, highlightsColorFilter.a); + + Color = ((Color - OriginalColorLuminance) / hableSaturation) + OriginalColorLuminance; + + return Color; } -float FindLuminanceToRestore(float tonemapLostLuminance, float preColorCorrectionLuminance, float postColorCorrectionLuminance) +// Takes input coordinates. Returns output color in linear space (also works in sRGB but it's not ideal). +float3 TetrahedralInterpolation( + Texture3D LUTTextureIn, + float3 LUTCoordinates) { - // Try to restore any luminance above "color", as it would have been lost during tone mapping. - // - // To achieve this, we re-apply the lost luminance, but only by the inverse amount the luminance changed during the color correction. - // e.g. if the color correction fully changed the luminance, then we don't change it any further, - // but if the color correction changed the luminance only by 25%, then we re-apply apply 75% of the lost luminance on top. - // This will be "accurate" as long as the color correction scaled the luminance linearly in the output as it grew in the input, - // but even if it didn't, it should still look fine. - - // This will re-apply an amount of lost luminance based on how much the CC reduced it: - // the more the CC reduced the luminance, the less we will apply. - // If the CC increased the luminance though, we will apply even more than the base lost amount. - tonemapLostLuminance = isnan(tonemapLostLuminance) ? 0.f : tonemapLostLuminance; - const float luminanceCCInvChange = max(1.f - (preColorCorrectionLuminance - postColorCorrectionLuminance), 0.f); - //const float luminanceCCInvChange = clamp(postColorCorrectionLuminance / preColorCorrectionLuminance, 0.f, 2.f); //TODO: try this - const float currentLum = postColorCorrectionLuminance; // Should be equal to "Luminance(color)" - const float targetLum = max(currentLum + tonemapLostLuminance, 0.f); - float scale = luminanceCCInvChange; - if (currentLum > 0.f) - { - scale *= targetLum / currentLum; - return scale; - } - return 1.f; + // We need to clip the input coordinates as LUT texure samples below are not clamped. + const float3 coords = saturate(LUTCoordinates) * (LUT_SIZE - 1); // Pixel coords + + // baseInd is on [0,LUT_SIZE-1] + const int3 baseInd = coords; + const int3 nextInd = baseInd + 1; + int3 indV2; + int3 indV3; + + // fract is on [0,1] + float3 fract = frac(coords); + + const float3 v1 = LUTTextureIn.Load(int4(baseInd, 0)); + const float3 v4 = LUTTextureIn.Load(int4(nextInd, 0)); + + float3 f1, f2, f3, f4; + + if (fract.r >= fract.g) + { + if (fract.g >= fract.b) // R > G > B + { + indV2 = int3(1, 0, 0); + indV3 = int3(1, 1, 0); + + f1 = 1.f - fract.r; + f4 = fract.b; + + f2 = fract.r - fract.g; + f3 = fract.g - fract.b; + } + else if (fract.r >= fract.b) // R > B > G + { + indV2 = int3(1, 0, 0); + indV3 = int3(1, 0, 1); + + f1 = 1.f - fract.r; + f4 = fract.g; + + f2 = fract.r - fract.b; + f3 = fract.b - fract.g; + } + else // B > R > G + { + indV2 = int3(0, 0, 1); + indV3 = int3(1, 0, 1); + + f1 = 1.f - fract.b; + f4 = fract.g; + + f2 = fract.b - fract.r; + f3 = fract.r - fract.g; + } + } + else + { + if (fract.g <= fract.b) // B > G > R + { + indV2 = int3(0, 0, 1); + indV3 = int3(0, 1, 1); + + f1 = 1.f - fract.b; + f4 = fract.r; + + f2 = fract.b - fract.g; + f3 = fract.g - fract.r; + } + else if (fract.r >= fract.b) // G > R > B + { + indV2 = int3(0, 1, 0); + indV3 = int3(1, 1, 0); + + f1 = 1.f - fract.g; + f4 = fract.b; + + f2 = fract.g - fract.r; + f3 = fract.r - fract.b; + } + else // G > B > R + { + indV2 = int3(0, 1, 0); + indV3 = int3(0, 1, 1); + + f1 = 1.f - fract.g; + f4 = fract.r; + + f2 = fract.g - fract.b; + f3 = fract.b - fract.r; + } + } + + // + // Refactored: + // + // dxc.exe ends up generating a pseudo-LUT of the above if statements using phi nodes. Mainly indV2 and indV3. Not much more can be done. + // + // + // This both minimizes the instruction count in divergent branches and guarantees all lanes (threads) will converge on + // the following .Load()s. Since lanes run in lock step within a wave (warp), if two or more pixels take different branches, + // they have to wait on individual loads. e.g. + // + // Lane 1, 3, 6: + // LUTTextureIn.Load(int4(nextInd, 0)); // branch taken when if(fract.g >= fract.b) + // LUTTextureIn.Load(int4(nextInd, 0)); + // ... + // Lane 2, 4, 9: + // LUTTextureIn.Load(int4(nextInd, 0)); // branch taken when if(fract.g <= fract.b) -- BUT we have to wait for the + // LUTTextureIn.Load(int4(nextInd, 0)); // previous Load() instructions to complete + // ... + // Lane 1, 2, 3, 4, 6, 9: + // return (f2 * v2) + (f3 * v3) + (f1 * v1) + (f4 * v4); // reconverge + // + // + // When moving .Load() outside the if statements: + // + // + // Lane 1, 2, 3, 4, 6, 9: + // LUTTextureIn.Load(int4(baseInd + indV2, 0)); // all lanes take the same path in the end. branches are still required to prepare indV2 + // LUTTextureIn.Load(int4(baseInd + indV3, 0)); // and indV3, but arthmetic ops are negligible. + // ... + // return (f2 * v2) + (f3 * v3) + (f1 * v1) + (f4 * v4); + // + const float3 v2 = LUTTextureIn.Load(int4(baseInd + indV2, 0)); + const float3 v3 = LUTTextureIn.Load(int4(baseInd + indV3, 0)); + + return (f1 * v1) + (f2 * v2) + (f3 * v3) + (f4 * v4); } -float3 PostProcess(float3 Color, inout float ColorLuminance) +#if defined(APPLY_MERGED_COLOR_GRADING_LUT) + +// In/Out linear space +float3 GradingLUT(float3 color, float2 uv) { - const uint hdrCmpDatIndex = PcwHdrComposite.HdrCmpDatIndex; - const float4 highlightsColorFilter = HdrCmpDat[hdrCmpDatIndex].HighlightsColourFilter; - const float4 colorFilter = HdrCmpDat[hdrCmpDatIndex].ColourFilter; - const float hableSaturation = HdrCmpDat[hdrCmpDatIndex].HableSaturation; - const float brightnessMultiplier = HdrCmpDat[hdrCmpDatIndex].BrightnessMultiplier; // Neutral at 1 - const float contrastIntensity = HdrCmpDat[hdrCmpDatIndex].ContrastIntensity; // Neutral at 1 - const float contrastMidPoint = PerSceneConstants[316u].z; - - ColorLuminance = Luminance(Color); - - // saturation adjustment a la Hable - // https://github.com/johnhable/fw-public/blob/37de36e662336415f5ef654d8edfc46b4ad025ed/FilmicCurve/FilmicColorGrading.cpp#L307-L309 - Color = ((Color - ColorLuminance) * hableSaturation) + ColorLuminance; - // Blend in another color based on the luminance. - Color += lerp(float3(0.f, 0.f, 0.f), ColorLuminance * highlightsColorFilter.rgb, highlightsColorFilter.a); - Color *= brightnessMultiplier; - - // Contrast adjustment (shift the colors from 0<->1 to (e.g.) -0.5<->0.5 range, multiply and shift back). - // The higher the distance from the contrast middle point, the more contrast will change the color. - Color = ((Color - contrastMidPoint) * contrastIntensity) + contrastMidPoint; - - Color = lerp(Color, colorFilter.rgb, colorFilter.a); - return Color; +// Overall, we don't really care about maintaining the wrong sRGB gamma formula as it broke LUT mapping, causing clipping, and just looked bad. +#if !FORCE_VANILLA_LOOK + const float3 LUTCoordinates = gamma_linear_to_sRGB(color); +#else + // Read gamma ini value, defaulting at 2.4 (makes little sense) + float inverseGamma = 1.f / (max(SharedFrameData.Gamma, 0.001f)); + // Weird linear -> sRGB conversion that clips values just above 0. + const float3 LUTCoordinates = max(gamma_linear_to_sRGB_Bethesda_Optimized(color, inverseGamma), 0.f); // Does "max()" is probably unnecessary as LUT sampling is already clamped. +#endif // FORCE_VANILLA_LOOK + +#if ENABLE_LUT_TETRAHEDRAL_INTERPOLATION + float3 LUTColor = TetrahedralInterpolation(LUTTexture, LUTCoordinates); +#else + float3 LUTCoordinatesScale = (LUT_SIZE - 1.0f) / LUT_SIZE; // Also "1-(1/LUT_SIZE)" + float3 LUTCoordinatesOffset = 1.0f / (2.0f * LUT_SIZE); // Also "(1/LUT_SIZE)/2" + float3 LUTColor = LUTTexture.Sample(Sampler0, (LUTCoordinates * LUTCoordinatesScale) + LUTCoordinatesOffset); +#endif // ENABLE_LUT_TETRAHEDRAL_INTERPOLATION + +#if LUT_MAPPING_TYPE == 2 + LUTColor = oklab_to_linear_srgb(LUTColor); + if (HdrDllPluginConstants.DisplayMode <= 0 || (bool)FORCE_SDR_LUTS) + { + LUTColor = saturate(LUTColor); + } +#elif LUT_MAPPING_TYPE == 0 + // We always work in linear space so convert to it. + // We never acknowledge the original wrong gamma function here (we don't really care). + LUTColor = gamma_sRGB_to_linear(LUTColor); +#endif // LUT_MAPPING_TYPE + +#if ENABLE_LUT_EXTRAPOLATION //TODO: does it even make sense given that "LUTCoordinates" is in sRGB? Negative numbers would be fkep up + // Extrapolate colors beyond the 0-1 input coordinates by finding the closest color to the LUT cube edge, + // and calculating the "color change" acceleration in that direction. + const float3 LUTCenterCoordinates = 0.5f; + //TODO: this should probably take into account the direction of our color and only move to the center of the closest 3D LUT texel + const float colorCenteringOffset = length((LUT_SIZE / 2.f) - 1.f) / length(LUT_SIZE / 2.f); + const float3 LUTCenteredCoordinates = ((saturate(LUTCoordinates) - LUTCenterCoordinates) * colorCenteringOffset) + LUTCenterCoordinates; + +#if ENABLE_LUT_TETRAHEDRAL_INTERPOLATION + float3 LUTCenterColor = TetrahedralInterpolation(LUTTexture, LUTCenteredCoordinates); +#else + float3 LUTCenterColor = LUTTexture.Sample(Sampler0, LUTCenteredCoordinates * (1.f - (1.f / LUT_SIZE)) + ((1.f / LUT_SIZE) / 2.f)); +#endif // ENABLE_LUT_TETRAHEDRAL_INTERPOLATION + + // Shift the color in the opposite direction of the centered one, by the ratio between the centered and the extra/external offset + LUTColor = lerp(LUTColor, LUTCenterColor, -abs(LUTCoordinates - saturate(LUTCoordinates)) / abs(saturate(LUTCoordinates) - LUTCenteredCoordinates)); + //TODO: clip negative luminance colors? +#endif // ENABLE_LUT_EXTRAPOLATION + + // "ColorGradingStrength" is similar to "AdditionalNeutralLUTPercentage" from the LUT mixing shader, though this is more precise as it skips the precision loss induced by a neutral LUT + const float LUTMaskAlpha = (1.f - LUTMaskTexture.Sample(Sampler0, uv).x) * HdrDllPluginConstants.ColorGradingStrength; + LUTColor = lerp(color, LUTColor, LUTMaskAlpha); + + return LUTColor; } -float3 PostProcess_Inverse(float3 Color, float ColorLuminance) +#endif // APPLY_MERGED_COLOR_GRADING_LUT + +// Takes a linear space untonemapped HDR color and a linear space tonemapped SDR color. +float3 RestorePostProcess(float3 inverseTonemappedColor, float3 postProcessColorRatio, float3 postProcessColorOffset, float3 tonemappedColor) { - const uint hdrCmpDatIndex = PcwHdrComposite.HdrCmpDatIndex; - const float4 highlightsColorFilter = HdrCmpDat[hdrCmpDatIndex].HighlightsColourFilter; - const float4 colorFilter = HdrCmpDat[hdrCmpDatIndex].ColourFilter; - const float hableSaturation = HdrCmpDat[hdrCmpDatIndex].HableSaturation; - const float brightnessMultiplier = HdrCmpDat[hdrCmpDatIndex].BrightnessMultiplier; // Neutral at 1 - const float contrastIntensity = HdrCmpDat[hdrCmpDatIndex].ContrastIntensity; // Neutral at 1 - const float contrastMidPoint = PerSceneConstants[316u].z; - - // We can't invert the color filter, so we will only inverse the post process by the unfiltered amount - const float colorFilterInverse = 1.f - colorFilter.a; - - Color = ((Color - contrastMidPoint) / contrastIntensity) + contrastMidPoint; - - Color /= brightnessMultiplier; - - Color -= lerp(float3(0.f, 0.f, 0.f), ColorLuminance * highlightsColorFilter.rgb, highlightsColorFilter.a); - - Color = ((Color - ColorLuminance) / hableSaturation) + ColorLuminance; - - return Color; + float3 postProcessedRatioColor = inverseTonemappedColor; + float3 postProcessedOffsetColor = inverseTonemappedColor; + postProcessedRatioColor *= postProcessColorRatio; + postProcessedOffsetColor += postProcessColorOffset; +// Near black, we prefer using the "offset" (sum) pp restoration method, as otherwise any raised black would not work, +// for example if any zero was shifted to a more raised color, "postProcessColorRatio" would not be able to replicate that shift due to a division by zero. +// Note: in case "INVERT_TONEMAP_TYPE" was 0, we might want to test the "postProcessedOffsetColor" blend in range more carefully. +// For the "INVERT_TONEMAP_TYPE" >0 case, this seems to work great, with the "MaxShadowsColor" setting that is there, anything more will raise colors. +#if 1 + return lerp(postProcessedOffsetColor, postProcessedRatioColor, saturate(tonemappedColor / MaxShadowsColor)); +#else // Doing the branching this way might not be so good, as near black colors could still end up with crazy value due to divisions between tiny values. Might not work with "HDR_TONEMAP_TYPE" > 1 (tonemap by luminance) + return select(tonemappedColor == 0.f, postProcessedOffsetColor, postProcessedRatioColor); +#endif +} + +void PostInverseTonemapByChannel( + float InputChannel, + float TonemappedChannel, + inout float InverseTonemappedColorChannel, + const SDRTonemapByLuminancePP sPP) +{ +#if 1 // Directly use the input/source non tonemapped color for comparisons against the highlights, hopefully this won't cause any gradients disconnects + const bool isHighlight = InputChannel >= sPP.minHighlightsColorOut; +#elif 0 + const bool isHighlight = (sPP.needsInverseTonemap ? InverseTonemappedColorChannel : InputChannel) >= sPP.minHighlightsColorOut; +#else // The least precise of them all + const bool isHighlight = TonemappedChannel >= sPP.minHighlightsColorIn; +#endif + // Restore the SDR tonemapped colors for non highlights, + // We scale all non highlights by the scale the smallest (first) highlight would have, so we keep the curves connected + if (INVERT_TONEMAP_TYPE > 0 && !isHighlight) + { + InverseTonemappedColorChannel = TonemappedChannel * (sPP.minHighlightsColorOut / sPP.minHighlightsColorIn); + } + // Restore any highlight clipped or just crushed by the direct tonemappers (Hable does that). + if (sPP.needsInverseTonemap && isHighlight) + { + InverseTonemappedColorChannel = InputChannel; + } +} + +#if defined(APPLY_MERGED_COLOR_GRADING_LUT) && DRAW_LUT +float3 DrawLUTTexture(float2 PixelPosition, uint PixelScale, inout bool DrawnLUT) { + const uint2 LUTPixelPosition2D = PixelPosition / PixelScale; + const uint3 LUTPixelPosition3D = uint3(LUTPixelPosition2D.x % LUT_SIZE_UINT, LUTPixelPosition2D.y, LUTPixelPosition2D.x / LUT_SIZE_UINT); + if (!any(LUTPixelPosition3D < 0u) && !any(LUTPixelPosition3D > LUT_MAX_UINT)) + { + DrawnLUT = true; + float3 loadedColor = LUTTexture.Load(uint4(LUTPixelPosition3D, 0)).rgb; +#if LUT_MAPPING_TYPE == 2 + loadedColor = oklab_to_linear_srgb(loadedColor); +#elif LUT_MAPPING_TYPE == 0 + loadedColor = gamma_sRGB_to_linear(loadedColor); +#endif // LUT_MAPPING_TYPE + return loadedColor; + } + return 0; +} + +float3 DrawLUTGradients(float2 PixelPosition, uint PixelScale, inout bool DrawnLUT) { + static const uint DrawLUTSquareSize = LUT_SIZE_UINT * PixelScale; + float width; + float height; + // We draw this on the bottom left + InputColorTexture.GetDimensions(width, height); + if (PixelPosition.y < (height - DrawLUTSquareSize)) + return 0; + + const uint2 position = uint2(PixelPosition.x / PixelScale, (PixelPosition.y - (height - DrawLUTSquareSize)) / PixelScale); + uint xPoint = position.x; + uint yPoint = position.y; + // NOTE: this is extremely slow. + if ((xPoint <= LUT_MAX_UINT && yPoint >= 0 && yPoint <= LUT_MAX_UINT)) + { + DrawnLUT = true; + float3 xyz; + uint row = 0u; + float coord = float(xPoint) / float(LUT_MAX_UINT); + float inverse = float(LUT_MAX_UINT - xPoint) / float(LUT_MAX_UINT); + if (yPoint == row++) xyz = float3(coord , coord , coord ); // Black => White + + else if (yPoint == row++) xyz = float3(coord , 0 , 0 ); // Black => Red + else if (yPoint == row++) xyz = float3(0 , coord , 0 ); // Black => Green + else if (yPoint == row++) xyz = float3(0 , 0 , coord ); // Black => Blue + + else if (yPoint == row++) xyz = float3(0 , coord , coord ); // Black => Cyan + else if (yPoint == row++) xyz = float3(coord , coord , 0 ); // Black => Yellow + else if (yPoint == row++) xyz = float3(coord , 0 , coord ); // Black => Magenta + + else if (yPoint == row++) xyz = float3(1u , coord , coord ); // Red to White + else if (yPoint == row++) xyz = float3(coord , 1u , coord ); // Green to White + else if (yPoint == row++) xyz = float3(coord , coord , 1u ); // Blue to White + + else if (yPoint == row++) xyz = float3(coord , 1u , 1u ); // Cyan to White + else if (yPoint == row++) xyz = float3(1u , 1u , coord ); // Yellow to White + else if (yPoint == row++) xyz = float3(1u , coord , 1u ); // Magenta to White + + else if (yPoint == row++) xyz = float3(inverse, coord , coord ); // Red to Cyan + else if (yPoint == row++) xyz = float3(coord , inverse, coord ); // Green to Magenta + else if (yPoint == row++) xyz = float3(coord , coord , inverse); // Blue to Yellow + + float3 loadedColor = LUTTexture.Load(uint4(xyz.rgb * LUT_MAX_UINT, 0)).rgb; +#if LUT_MAPPING_TYPE == 2 + loadedColor = oklab_to_linear_srgb(loadedColor); +#elif LUT_MAPPING_TYPE == 0 + loadedColor = gamma_sRGB_to_linear(loadedColor); +#endif // LUT_MAPPING_TYPE + return loadedColor; + } + return 0; } +#endif // APPLY_MERGED_COLOR_GRADING_LUT && DRAW_LUT +[RootSignature(ShaderRootSignature)] PSOutput PS(PSInput psInput) -{ - float3 inputColour = InputColour.Load(int3(int2(psInput.SV_Position.xy), 0)); -#if CLAMP_INPUT_OUTPUT - // Remove any negative value caused by using R16G16B16A16F buffers (originally this was R11G11B10F, which has no negative values). - // Doing gamut mapping, or keeping the colors outside of BT.709 doesn't seem to be right, as they seem to be just be accidentally coming out of some shader math. - inputColour = max(inputColour, 0.f); +{ +#if defined(APPLY_MERGED_COLOR_GRADING_LUT) && DRAW_LUT + static const uint DrawLUTTextureScale = 10u; // Pixel scale + static const uint DrawLUTGradientScale = 30u; // Pixel scale + bool drawnLUT = false; + float3 LUTColor = DrawLUTTexture(psInput.SV_Position.xy, DrawLUTTextureScale, drawnLUT); + if (!drawnLUT) // Avoids drawing on top of each other + { + LUTColor = DrawLUTGradients(psInput.SV_Position.xy, DrawLUTGradientScale, drawnLUT); + } + + if (drawnLUT) + { + float3 outputColor = LUTColor; + if (HdrDllPluginConstants.DisplayMode <= 0) // SDR + { +#if SDR_USE_GAMMA_2_2 && !GAMMA_CORRECTION_IN_LUTS + outputColor = lerp(outputColor, pow(gamma_linear_to_sRGB(outputColor), 2.2f), HdrDllPluginConstants.GammaCorrection); +#endif // SDR_USE_GAMMA_2_2 && !GAMMA_CORRECTION_IN_LUTS + +#if !SDR_LINEAR_INTERMEDIARY +#if SDR_USE_GAMMA_2_2 + outputColor = pow(outputColor, 1.f / 2.2f); +#else + outputColor = gamma_linear_to_sRGB(outputColor); +#endif // SDR_USE_GAMMA_2_2 +#endif // SDR_LINEAR_INTERMEDIARY + } + else + { + outputColor *= HdrDllPluginConstants.HDRGamePaperWhiteNits / WhiteNits_sRGB; + } + + PSOutput psOutput; + psOutput.SV_Target.rgb = outputColor; + psOutput.SV_Target.a = 1.f; + return psOutput; + } #endif -#if defined(APPLY_BLOOM) + // Linear HDR color straight from the renderer (possibly with exposure pre-applied to it, assuming the game has some auto exposure mechanism) + float3 inputColor = InputColorTexture.Load(int3(int2(psInput.SV_Position.xy), 0)); - float3 bloom = Bloom.Sample(Sampler0, psInput.TEXCOORD); +#if CLAMP_INPUT_OUTPUT + // Remove any negative value caused by using R16G16B16A16F buffers (originally this was R11G11B10F, which has no negative values). + // Doing gamut mapping, or keeping the colors outside of BT.709 doesn't seem to be right, as they seem to be just be accidentally coming out of some shader math. + inputColor = max(inputColor, 0.f); +#endif // CLAMP_INPUT_OUTPUT - float bloomMultiplier = PcwHdrComposite.BloomMultiplier; +#if defined(APPLY_BLOOM) - inputColour = (bloomMultiplier * bloom) + inputColour; + float3 bloom = Bloom.Sample(Sampler0, psInput.TEXCOORD); + inputColor += PcwHdrComposite.BloomMultiplier * bloom; #endif // APPLY_BLOOM - float3 tonemappedColor; - float3 tonemappedUnclampedColor; + float3 outputColor = inputColor; -#if DISABLE_TONEMAP - tonemappedColor = inputColour; - tonemappedUnclampedColor = inputColour; -#else - - float acesParam_modE; - float acesParam_modA; - - float hable_params_y0; - float hable_params_y1; - float hable_dstParams_W; - float hable_toeSegment_lnA; - float hable_toeSegment_B; - float hable_midSegment_offsetX; - float hable_midSegment_lnA; - float hable_shoulderSegment_offsetX; - float hable_shoulderSegment_offsetY; - float hable_shoulderSegment_scaleX; - float hable_shoulderSegment_lnA; - float hable_shoulderSegment_B; - float hable_invScale; - - const bool clampACES = false; - if (PcwHdrComposite.Tmo == 1u || ForceACES) - { - tonemappedUnclampedColor = ACESReference(inputColour, clampACES); - tonemappedColor = saturate(tonemappedUnclampedColor); - } - else if (PcwHdrComposite.Tmo == 2u) - { - tonemappedUnclampedColor = ACESParametric(inputColour, clampACES, acesParam_modE, acesParam_modA); - tonemappedColor = saturate(tonemappedUnclampedColor); - } - else if (PcwHdrComposite.Tmo == 3u) - { - tonemappedUnclampedColor = Hable(inputColour, - hable_params_y0, - hable_params_y1, - hable_dstParams_W, - hable_toeSegment_lnA, - hable_toeSegment_B, - hable_midSegment_offsetX, - hable_midSegment_lnA, - hable_shoulderSegment_offsetX, - hable_shoulderSegment_offsetY, - hable_shoulderSegment_scaleX, - hable_shoulderSegment_lnA, - hable_shoulderSegment_B, - hable_invScale); - tonemappedColor = tonemappedUnclampedColor; // Hable was never clamped - } - else - { - tonemappedUnclampedColor = inputColour; - tonemappedColor = saturate(tonemappedUnclampedColor); - } - -#if !DISABLE_POST_PROCESS - float prePostProcessColorLuminance; - float prePostProcessUnclampedColorLuminance; - tonemappedColor = PostProcess(tonemappedColor, prePostProcessColorLuminance); - // Repeat on unclamped tonemapped color to later retrieve the lost luminance - tonemappedUnclampedColor = PostProcess(tonemappedUnclampedColor, prePostProcessUnclampedColorLuminance); -#endif -#endif // DISABLE_TONEMAP - - tonemappedColor = saturate(tonemappedColor); - - // This is the luminance lost by clamping SDR tonemappers to the 0-1 range, and again by the fact that LUTs only take 0-1 range input. - const float tonemapLostLuminance = Luminance(tonemappedUnclampedColor - tonemappedColor); //TODO: clip any negative values here? The unclamped tonemapper might actually have negative "lost" luminance. - - const float preColorCorrectionLuminance = Luminance(tonemappedColor); - - float3 colour = tonemappedColor; - -#if defined(APPLY_MERGED_COLOR_GRADING_LUT) && !DISABLE_TONEMAP && !DISABLE_LUT - -#if FIX_WRONG_SRGB_GAMMA - float3 LUTEncodedColour = gamma_linear_to_sRGB(colour); + float3 tonemappedColor; + float3 tonemappedByLuminanceColor; + +#if !ENABLE_TONEMAP + tonemappedColor = inputColor; + tonemappedByLuminanceColor = inputColor; + float3 tonemappedPostProcessedColor = tonemappedColor; #else - //read gamma ini value, defaulting at 2.4 (makes little sense) - float inverseGamma = 1.f / (max(SharedFrameData.Gamma, 0.001f)); - //weird linear -> sRGB conversion that clips values just above 0, and raises blacks. - float3 LUTEncodedColour = (pow(colour, inverseGamma) * 1.055f) - 0.055f; - LUTEncodedColour = max(LUTEncodedColour, 0.f); // Unnecessary as the LUT sampling is already clamped. -#endif // FIX_WRONG_SRGB_GAMMA - - float3 LUTColor = Lut.Sample(Sampler0, LUTEncodedColour * (1.f - (1.f / LUT_SIZE)) + ((1.f / LUT_SIZE) / 2.f)); -#if !FIX_LUT_GAMMA_MAPPING - LUTColor = gamma_sRGB_to_linear(LUTColor); -#endif // FIX_LUT_GAMMA_MAPPING - float LUTMaskAlpha = saturate(LutMask.Sample(Sampler0, psInput.TEXCOORD).x + (1.f - LUTStrenght)); - colour = lerp(LUTColor, colour, LUTMaskAlpha); + + float acesParam_modE; + float acesParam_modA; + + HableParams hableParams; + + const bool clampACES = false; + + int tonemapperIndex = ForceTonemapper > 0 ? ForceTonemapper : PcwHdrComposite.Tmo; + + const float untonemappedColorLuminance = Luminance(inputColor); + float tonemappedColorLuminance; + + switch (tonemapperIndex) + { + case 1: + { + tonemappedColor = ACESReference(inputColor, clampACES); + tonemappedColorLuminance = ACESReference(untonemappedColorLuminance, clampACES); + } break; + + case 2: + { + tonemappedColor = ACESParametric(inputColor, clampACES, acesParam_modE, acesParam_modA); + tonemappedColorLuminance = ACESParametric(untonemappedColorLuminance, clampACES, acesParam_modE, acesParam_modA); + } break; + + case 3: + { + tonemappedColor = Hable(inputColor, hableParams); + tonemappedColorLuminance = Hable(untonemappedColorLuminance.xxx, hableParams).x; //TODO: make hable templatable + } break; + + default: + { + tonemappedColor = inputColor; + tonemappedColorLuminance = untonemappedColorLuminance; + } break; + } + + tonemappedByLuminanceColor = inputColor * safeDivision(tonemappedColorLuminance, untonemappedColorLuminance); + +#if defined(APPLY_CINEMATICS) + float prePostProcessColorLuminance; + float3 tonemappedPostProcessedColor = lerp(tonemappedColor, PostProcess(tonemappedColor, prePostProcessColorLuminance), PostProcessStrength); #else + float3 tonemappedPostProcessedColor = tonemappedColor; // No need to do anything (not even a saturate here) +#endif //APPLY_CINEMATICS + +#endif // ENABLE_TONEMAP + + float3 tonemappedPostProcessedGradedColor = tonemappedPostProcessedColor; + +#if defined(APPLY_MERGED_COLOR_GRADING_LUT) && ENABLE_TONEMAP + +#if ENABLE_LUT + tonemappedPostProcessedGradedColor = GradingLUT(tonemappedPostProcessedColor, psInput.TEXCOORD); +#endif // ENABLE_LUT + +#if GAMMA_CORRECT_SDR_RANGE_ONLY + const float3 tonemappedPostProcessedGradedSDRColors = saturate(tonemappedPostProcessedGradedColor); + const float3 tonemappedPostProcessedGradedSDRExcessColors = tonemappedPostProcessedGradedColor - tonemappedPostProcessedGradedSDRColors; + tonemappedPostProcessedGradedColor = tonemappedPostProcessedGradedSDRColors; +#endif // GAMMA_CORRECT_SDR_RANGE_ONLY + +// Do this even if "ENABLE_LUT" is false, for consistency +#if SDR_USE_GAMMA_2_2 && (!ENABLE_LUT || !GAMMA_CORRECTION_IN_LUTS) + // This error was always built in the image if we assume Bethesda calibrated the game on gamma 2.2 displays. + // Possibly, if there's no color grading LUT, there shouldn't be any gamma adjustment, as the error might have been exclusively baked into LUTs, + // while a neutral LUT (or no LUT) image would have never been calibrated, so we couldn't say for sure there was a gamma mismatch in it, but for the sake of simplicity, + // we don't care about that, and there's a setting exposed for users anyway (it does indeed seem like the world is too dark with gamma correction on if there's no color grading). + tonemappedPostProcessedGradedColor = lerp(tonemappedPostProcessedGradedColor, pow(gamma_linear_to_sRGB(tonemappedPostProcessedGradedColor), 2.2f), HdrDllPluginConstants.GammaCorrection); +#endif // SDR_USE_GAMMA_2_2 + + // The dll makes sure this is 1 when we are in HDR. + if (HdrDllPluginConstants.SDRSecondaryBrightness != 1.f) + { + float3 oklabColor = linear_srgb_to_oklab(tonemappedPostProcessedGradedColor); + oklabColor[0] = pow(oklabColor[0], linearNormalization(HdrDllPluginConstants.SDRSecondaryBrightness, 0.f, 2.f, 1.25f, 0.75f)); + tonemappedPostProcessedGradedColor = oklab_to_linear_srgb(oklabColor); + } + +#if GAMMA_CORRECT_SDR_RANGE_ONLY + tonemappedPostProcessedGradedColor += tonemappedPostProcessedGradedSDRExcessColors; +#endif // GAMMA_CORRECT_SDR_RANGE_ONLY #endif // APPLY_MERGED_COLOR_GRADING_LUT - - const float postColorCorrectionLuminance = Luminance(colour); - -#if ENABLE_HDR - // Restore any luminance beyond 1 that ended up clipped by HDR->SDR tonemappers and any subsequent image manipulation - colour *= FindLuminanceToRestore(tonemapLostLuminance, preColorCorrectionLuminance, postColorCorrectionLuminance); - -#if !DISABLE_TONEMAP && !DISABLE_INVERSE_TONEMAP - -#if !DISABLE_POST_PROCESS && !DISABLE_INVERSE_POST_PROCESS - //TODO: passing in the previous luminance might not be the best, though is there any other way really? - //Should we at least shift it by how much the LUT shifted the luminance? To invert it more correctly. - colour = PostProcess_Inverse(colour, prePostProcessColorLuminance); -#endif // !DISABLE_POST_PROCESS && !DISABLE_INVERSE_POST_PROCESS - - if (PcwHdrComposite.Tmo == 1u || ForceACES) - { - colour = ACESReference_Inverse(colour); - } - else if (PcwHdrComposite.Tmo == 2u) - { - colour = ACESParametric_Inverse(colour, acesParam_modE, acesParam_modA); - } - else if (PcwHdrComposite.Tmo == 3u) - { - colour = Hable_Inverse(colour, - hable_params_y0, - hable_params_y1, - hable_dstParams_W, - hable_toeSegment_lnA, - hable_toeSegment_B, - hable_midSegment_offsetX, - hable_midSegment_lnA, - hable_shoulderSegment_offsetX, - hable_shoulderSegment_offsetY, - hable_shoulderSegment_scaleX, - hable_shoulderSegment_lnA, - hable_shoulderSegment_B, - hable_invScale); - } - else - { - // Any luminance lost by this tonemap case would have already been restored above with "tonemapLostLuminance". - } - -#if !DISABLE_POST_PROCESS && !DISABLE_INVERSE_POST_PROCESS - //TODO: ... this has no use now, and also, it won't work in the HDR range - colour = PostProcess(colour, prePostProcessColorLuminance); -#endif // !DISABLE_POST_PROCESS && !DISABLE_INVERSE_POST_PROCESS -#endif // !DISABLE_TONEMAP && !DISABLE_INVERSE_TONEMAP - - colour *= HDR_GAME_PAPER_WHITE; -#if CLAMP_INPUT_OUTPUT - colour = clamp(colour, 0.f, FLT16_MAX); // Avoid extremely high numbers turning into NaN in FP16 + + const float3 finalOriginalColor = tonemappedPostProcessedGradedColor; // Final "original" (vanilla, ~unmodded) linear SDR color before output transform + +#if ENABLE_TONEMAP && ENABLE_REPLACED_TONEMAP + const bool SDRTonemapByLuminance = (HDR_TONEMAP_TYPE > 0) && (bool)HDR_INVERT_SDR_TONEMAP_BY_LUMINANCE; +#if 1 // This is delicate and could make things worse, especially within "RestorePostProcess()", but without it, highlights have uncontiguos gradients that shift color (due to strong LUTs) + if (SDRTonemapByLuminance) + { + tonemappedColor = tonemappedByLuminanceColor; + } +#endif + + const float3 postProcessColorRatio = safeDivision(finalOriginalColor, tonemappedColor); + const float3 postProcessColorOffset = finalOriginalColor - tonemappedColor; #endif - - //TODO: do DICE tonemapping to display nits, or some Hable like HDR tonemapper. - + + if (HdrDllPluginConstants.DisplayMode > 0) // HDR + { +#if ENABLE_TONEMAP && ENABLE_REPLACED_TONEMAP + + const float paperWhite = HdrDllPluginConstants.HDRGamePaperWhiteNits / WhiteNits_sRGB; + + const float midGrayIn = MidGray; + float midGrayOut = midGrayIn; + +//TODO: rename "minHighlightsColorIn" and "minHighlightsColorOut" to something more generic, as now we have "INVERT_TONEMAP_TYPE" (so it could be highlights or midtones, ...) +#if INVERT_TONEMAP_TYPE != 1 // invert highlights + float minHighlightsColorIn = MinHighlightsColor; // We consider highlight the last ~33% of perception SDR space +#else // invert midtones and highlights + float minHighlightsColorIn = MaxShadowsColor; // We consider shdadow the first ~33% of perception SDR space +#endif + float minHighlightsColorOut = minHighlightsColorIn; +#if DEVELOPMENT + const float localSDRTonemapHDRStrength = 1.f - HdrDllPluginConstants.DevSetting01; #else - -#if SDR_USE_GAMMA_2_2 //TODO: This makes sense to have if we fix up the LUTs, though the SDR tonemapper had still been developed with sRGB<->2.2 mismatch - colour = pow(colour, 1.f / 2.2f); + const float localSDRTonemapHDRStrength = SDRTonemapHDRStrength; +#endif + // If true, we need to calculate the inverse tonemap + const bool needsInverseTonemap = (INVERT_TONEMAP_TYPE <= 0) || localSDRTonemapHDRStrength != 1.f; + + float3 inverseTonemappedColor = needsInverseTonemap ? tonemappedColor : inputColor; + + // Restore a color very close to the original linear one (some information might get close in the direct tonemapper) + switch (tonemapperIndex) + { + case 1: + { + if (needsInverseTonemap) + { + inverseTonemappedColor = ACESReference_Inverse(inverseTonemappedColor); + midGrayOut = ACESReference_Inverse(midGrayIn); + } + minHighlightsColorOut = ACESReference_Inverse(minHighlightsColorIn); + } break; + + case 2: + { + if (needsInverseTonemap) + { + inverseTonemappedColor = ACESParametric_Inverse(inverseTonemappedColor, acesParam_modE, acesParam_modA); + midGrayOut = ACESParametric_Inverse(midGrayIn, acesParam_modE, acesParam_modA); + } + minHighlightsColorOut = ACESParametric_Inverse(minHighlightsColorIn, acesParam_modE, acesParam_modA); + } break; + + case 3: + { +#if INVERT_TONEMAP_TYPE != 1 + // Setup highlights for Hable, we use the official param based highlights shoulder start for it, so that we switch tonemapper in the same place where the hable curve would change direction (or so I think) + const float shoulderOutStart = max(hableParams.params.y0, hableParams.params.y1); // Check both toe and mid params for extra safety + minHighlightsColorIn = shoulderOutStart; #else - // Do sRGB gamma even if we'd be playing on gamma 2.2 screens, as the game was already calibrated for 2.2 gamma - colour = gamma_linear_to_sRGB(colour); -#if CLAMP_INPUT_OUTPUT - colour = clamp(colour, 0.f, 1.f); + const float toeOutEnd = min(hableParams.params.y0, hableParams.params.y1); + minHighlightsColorIn = toeOutEnd; +#endif + + if (needsInverseTonemap) + { + inverseTonemappedColor = Hable_Inverse(inverseTonemappedColor, hableParams); + midGrayOut = Hable_Inverse(midGrayIn, hableParams); + } +#if INVERT_TONEMAP_TYPE != 1 // Optimized and more "accurate" + minHighlightsColorOut = hableParams.shoulderStart; +#elif 1 + minHighlightsColorOut = hableParams.toeEnd; +#else + minHighlightsColorOut = Hable_Inverse(minHighlightsColorIn, hableParams); +#endif + } break; + + default: + break; + } + + if (!SDRTonemapByLuminance) + { + SDRTonemapByLuminancePP sPP; + sPP.minHighlightsColorIn = minHighlightsColorIn; + sPP.minHighlightsColorOut = minHighlightsColorOut; + sPP.needsInverseTonemap = needsInverseTonemap; + + PostInverseTonemapByChannel(inputColor.r, tonemappedColor.r, inverseTonemappedColor.r, sPP); + PostInverseTonemapByChannel(inputColor.g, tonemappedColor.g, inverseTonemappedColor.g, sPP); + PostInverseTonemapByChannel(inputColor.b, tonemappedColor.b, inverseTonemappedColor.b, sPP); + } + else + { +#if 1 + const bool isHighlight = untonemappedColorLuminance >= minHighlightsColorOut; +#else + const bool isHighlight = (needsInverseTonemap ? Luminance(inverseTonemappedColor) : untonemappedColorLuminance) >= minHighlightsColorOut; +#endif + if (INVERT_TONEMAP_TYPE > 0 && !isHighlight) + { + inverseTonemappedColor = tonemappedByLuminanceColor * (minHighlightsColorOut / minHighlightsColorIn); + } + if (needsInverseTonemap && isHighlight) + { + inverseTonemappedColor = inputColor; + } + } + + if (INVERT_TONEMAP_TYPE > 0) + { + // If we only inverted highlights, the mid gray in and out should follow the same scale of the highlightd in/out change, otherwise the curves wouldn't connect. + // In the extremely unlikely case that "midGrayOut" was higher than "minHighlightsColorOut", this calculaton should still be ok. + midGrayOut = lerp(midGrayOut, midGrayIn * (minHighlightsColorOut / minHighlightsColorIn), localSDRTonemapHDRStrength); + // Shift back to the original linear color if we want to ignore the SDR tonemapper + if (localSDRTonemapHDRStrength != 1.f) + { + inverseTonemappedColor = lerp(inputColor, inverseTonemappedColor, localSDRTonemapHDRStrength); + minHighlightsColorOut = lerp(minHighlightsColorIn, minHighlightsColorOut, localSDRTonemapHDRStrength); + } + } + +#if ALLOW_EXPAND_GAMUT + // We do this before applying "midGrayScale" as otherwise the input values would be too low. This way the are very close to the pre tonemapping range. + if (HdrDllPluginConstants.HDRExtendGamut > 0.f) + { + // Pow by 2 to make the 0-1 setting slider more perceptually linear + inverseTonemappedColor = ExtendGamut(inverseTonemappedColor, pow(HdrDllPluginConstants.HDRExtendGamut, 2.0f)); + } +#endif + + const float midGrayScale = midGrayOut / midGrayIn; + + // Bring back the color to the same range as SDR by matching the mid gray level. + inverseTonemappedColor /= midGrayScale; + minHighlightsColorOut /= midGrayScale; + + float3 inverseTonemappedPostProcessedColor = RestorePostProcess(inverseTonemappedColor, postProcessColorRatio, postProcessColorOffset, tonemappedColor); +#if 0 // Enable this if you want the highlights should start to be affected by post processing. It doesn't seem like the right thing to do and having it off works just fine. + minHighlightsColorOut = RestorePostProcess(minHighlightsColorOut, postProcessColorRatio, postProcessColorOffset, tonemappedColor); +#endif + + // Secondary user driven saturation. This is already placed in LUTs but it's only applied on LUTs normalization (in HDR). + float saturation = linearNormalization(HdrDllPluginConstants.HDRSaturation, 0.f, 2.f, 0.5f, 1.5f); +#if defined(APPLY_MERGED_COLOR_GRADING_LUT) && ENABLE_LUT + saturation = lerp(saturation, 1.f, HdrDllPluginConstants.ColorGradingStrength * HdrDllPluginConstants.LUTCorrectionStrength); +#endif + inverseTonemappedPostProcessedColor = Saturation(inverseTonemappedPostProcessedColor, saturation); + + // Secondary user driven contrast + const float secondaryContrast = linearNormalization(HdrDllPluginConstants.HDRSecondaryContrast, 0.f, 2.f, 0.5f, 1.5f); +#if 0 // By luminance (no hue shift) (looks off) + float inverseTonemappedPostProcessedColorLuminance = Luminance(inverseTonemappedPostProcessedColor); + inverseTonemappedPostProcessedColor *= safeDivision(pow(inverseTonemappedPostProcessedColorLuminance / MidGray, secondaryContrast) * MidGray, inverseTonemappedPostProcessedColorLuminance); +#else // By channel (also increases saturation) + inverseTonemappedPostProcessedColor = pow(abs(inverseTonemappedPostProcessedColor) / MidGray, secondaryContrast) * MidGray * sign(inverseTonemappedPostProcessedColor); #endif + + inverseTonemappedPostProcessedColor *= paperWhite; + minHighlightsColorOut *= paperWhite; + + const float maxOutputLuminance = HdrDllPluginConstants.HDRPeakBrightnessNits / WhiteNits_sRGB; +#if 0 // Old method (looks more dim) + // The highlights shoulder (compression) curve should never start beyond 33.33% of the max output brightness (found empircally). + float highlightsShoulderStart = min(maxOutputLuminance * (1.f / 3.f), minHighlightsColorOut); +#else // New method (looks better but struggles more with high paper white on low peak brightness configurations) + // Never compress highlights before the top 2/3 of the image, even if it means we have two separate mid tones sections, + // one from the SDR tonemapped and one pure linear (hopefully the discontinuous curve won't be noticeable on gradients). + float highlightsShoulderStart = max(maxOutputLuminance * (1.f / 3.f), minHighlightsColorOut); +#endif + highlightsShoulderStart = (INVERT_TONEMAP_TYPE > 0) ? lerp(0.f, highlightsShoulderStart, localSDRTonemapHDRStrength) : 0.f; + + outputColor = DICETonemap(inverseTonemappedPostProcessedColor, maxOutputLuminance, highlightsShoulderStart, HDRHighlightsModulation); + +#else // ENABLE_TONEMAP && ENABLE_REPLACED_TONEMAP + + outputColor = finalOriginalColor * (HdrDllPluginConstants.HDRGamePaperWhiteNits / ReferenceWhiteNits_BT2408); // Don't use "HDRGamePaperWhiteNits" directly as it'd be too bright on an untonemapped image + +#endif // ENABLE_TONEMAP && ENABLE_REPLACED_TONEMAP + +#if CLAMP_INPUT_OUTPUT + outputColor = clamp(outputColor, 0.f, FLT16_MAX); // Avoid extremely high numbers turning into NaN in FP16 +#endif // CLAMP_INPUT_OUTPUT + } + else // SDR + { + outputColor = finalOriginalColor; + +#if !SDR_LINEAR_INTERMEDIARY + // Note that gamma was never applied if LUTs were disabled, but we don't care about that as the affected shaders permutations were never used +#if SDR_USE_GAMMA_2_2 + outputColor = pow(outputColor, 1.f / 2.2f); +#else + // Do sRGB gamma even if we'd be playing on gamma 2.2 screens, as the game was already calibrated for 2.2 gamma despite using the wrong formula + outputColor = gamma_linear_to_sRGB(outputColor); #endif // SDR_USE_GAMMA_2_2 - -#endif // ENABLE_HDR - - PSOutput psOutput; - psOutput.SV_Target.rgb = colour; - psOutput.SV_Target.a = 1.f; +#endif // SDR_LINEAR_INTERMEDIARY + +#if CLAMP_INPUT_OUTPUT + outputColor = saturate(outputColor); +#endif // CLAMP_INPUT_OUTPUT + } + PSOutput psOutput; + psOutput.SV_Target.rgb = outputColor; + psOutput.SV_Target.a = 1.f; return psOutput; } diff --git a/shaders/HDRComposite/RootSignature.hlsl b/shaders/HDRComposite/RootSignature.hlsl new file mode 100644 index 00000000..7b2934c6 --- /dev/null +++ b/shaders/HDRComposite/RootSignature.hlsl @@ -0,0 +1,88 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "RootConstants(num32BitConstants=3, b0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=6), " \ + "SRV(t1, space=6), " \ + "SRV(t2, space=6, flags=DATA_VOLATILE), " \ + "SRV(t3, space=6), " \ + "SRV(t4, space=6), " \ + "SRV(t5, space=6), " \ + "SRV(t7, space=6), " \ + "SRV(t8, space=6), " \ + "SRV(t9, space=6), " \ + "SRV(t10, space=6), " \ + "SRV(t11, space=6), " \ + "SRV(t12, space=6), " \ + "SRV(t13, space=6), " \ + "SRV(t14, space=6), " \ + "SRV(t15, space=6), " \ + "SRV(t16, space=6), " \ + "SRV(t17, space=6), " \ + "SRV(t18, space=6), " \ + "SRV(t19, space=6), " \ + "SRV(t20, space=6), " \ + "SRV(t21, space=6), " \ + "SRV(t22, space=6), " \ + "SRV(t23, space=6), " \ + "SRV(t24, space=6), " \ + "SRV(t25, space=6), " \ + "SRV(t26, space=6), " \ + "UAV(u0, space=6), " \ + "UAV(u1, space=6), " \ + "SRV(t27, space=6), " \ + "SRV(t28, space=6) " \ + "), " \ + \ + "DescriptorTable( " \ + "Sampler(s0, numDescriptors=10, space=6), " \ + "Sampler(s10, numDescriptors=2, space=6) " \ + "), " \ + \ + "SRV(t6, space=6), " \ + "CBV(b0, space=6), " \ + "CBV(b1, space=6), " \ + \ + "DescriptorTable( " \ + "SRV(t2, space=7), " \ + "SRV(t3, space=7), " \ + "SRV(t5, space=7, flags=DATA_VOLATILE), " \ + "SRV(t6, space=7, flags=DATA_VOLATILE), " \ + "UAV(u0, space=7), " \ + "UAV(u1, space=7), " \ + "UAV(u2, space=7), " \ + "UAV(u3, space=7), " \ + "SRV(t7, numDescriptors=12, space=7, flags=DATA_VOLATILE) " \ + "), " \ + \ + "SRV(t0, space=7), " \ + "SRV(t1, space=7), " \ + "SRV(t4, space=7), " \ + "CBV(b0, space=7), " \ + "CBV(b1, space=7), " \ + "CBV(b2, space=7), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=9), " \ + "SRV(t1, space=9), " \ + "SRV(t2, space=9), " \ + "SRV(t3, space=9), " \ + "SRV(t4, space=9) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s12, filter=FILTER_MIN_MAG_MIP_POINT, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s13, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s14, filter=FILTER_MIN_MAG_MIP_LINEAR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s15, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s16, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s17, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s18, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s19, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s20, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_LESS, space=6), " \ + "StaticSampler(s21, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_GREATER, space=6), " \ + "StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=9) " diff --git a/shaders/PostSharpen/PostSharpen_FF9A_ps.hlsl b/shaders/PostSharpen/PostSharpen_FF9A_ps.hlsl deleted file mode 100644 index 81105716..00000000 --- a/shaders/PostSharpen/PostSharpen_FF9A_ps.hlsl +++ /dev/null @@ -1,77 +0,0 @@ -#define ENABLE_HDR 1 - -cbuffer _13_15 : register(b0, space7) -{ - float4 _15_m0[3269] : packoffset(c0); -}; - -cbuffer _18_20 : register(b0, space0) -{ - float4 _20_m0[2] : packoffset(c0); -}; - -Texture2D TonemappedColorTexture : register(t0, space8); // Possibly in gamma space in SDR -SamplerState Sampler0 : register(s13, space6); -SamplerState Sampler1 : register(s15, space6); // Likely nearest neighbor - -static float4 TEXCOORD; -static float4 SV_Target; - -struct SPIRV_Cross_Input -{ - float4 TEXCOORD : TEXCOORD0; -}; - -struct SPIRV_Cross_Output -{ - float4 SV_Target : SV_Target0; -}; - -void frag_main() -{ - float3 inColor = TonemappedColorTexture.Sample(Sampler0, float2(TEXCOORD.x, TEXCOORD.y)).xyz; - uint4 sharpenParams = asuint(_20_m0[0u]); - float sharpenIntensity = asfloat(sharpenParams.z); - float3 outColor = inColor; -#if !ENABLE_HDR //TODO: implement - if (sharpenIntensity > 0.f) //TODO: should this check for "sharpenIntensity < 1.f"? It seems like its the inverse intensity - { - float _70 = ((_15_m0[161u].z * TEXCOORD.x) * asfloat(sharpenParams.x)) + 0.5f; - float _72 = ((_15_m0[161u].w * TEXCOORD.y) * asfloat(sharpenParams.y)) + 0.5f; - float _76 = frac(_70); - float _77 = frac(_72); - float _87 = ((((((_76 * 2.0f) + (-3.0f)) * _76) + (-3.0f)) * _76) + 5.0f) * 0.16666667163372039794921875f; - float _89 = _76 * 3.0f; - float _98 = ((((((3.0f - _89) + _76) * _76) + 3.0f) * _76) + 1.0f) * 0.16666667163372039794921875f; - float _99 = _76 * _76; - float _113 = _77 * _77; - float _114 = _77 * 3.0f; - float _125 = ((((((_77 * 2.0f) + (-3.0f)) * _77) + (-3.0f)) * _77) + 5.0f) * 0.16666667163372039794921875f; - float _136 = ((((((3.0f - _114) + _77) * _77) + 3.0f) * _77) + 1.0f) * 0.16666667163372039794921875f; - float _139 = floor(_70) + (-0.5f); - float _142 = floor(_72) + (-0.5f); - float _144 = (_139 + (((((_99 * (_89 + (-6.0f))) + 4.0f) * 0.16666667163372039794921875f) / _87) + (-1.0f))) / _15_m0[161u].z; - float _145 = (_142 + (((((_113 * (_114 + (-6.0f))) + 4.0f) * 0.16666667163372039794921875f) / _125) + (-1.0f))) / _15_m0[161u].w; - float _147 = (_139 + ((((_99 * 0.16666667163372039794921875f) * _76) / _98) + 1.0f)) / _15_m0[161u].z; - float _149 = (_142 + ((((_113 * 0.16666667163372039794921875f) * _77) / _136) + 1.0f)) / _15_m0[161u].w; - float3 _152 = TonemappedColorTexture.SampleLevel(Sampler1, float2(_144, _145), 0.0f); - float3 _157 = TonemappedColorTexture.SampleLevel(Sampler1, float2(_147, _145), 0.0f); - float3 _162 = TonemappedColorTexture.SampleLevel(Sampler1, float2(_144, _149), 0.0f); - float3 _167 = TonemappedColorTexture.SampleLevel(Sampler1, float2(_147, _149), 0.0f); - float3 sharpenedColor = (((_167 * _98) + (_162 * _87)) * _136) + (((_157 * _98) + (_152 * _87)) * _125); - outColor = ((inColor - sharpenedColor) * sharpenIntensity) + sharpenedColor; - //outColor = lerp(sharpenedColor, inColor, sharpenIntensity); - } -#endif - SV_Target.xyz = outColor; - SV_Target.w = 1.0f; -} - -SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input) -{ - TEXCOORD = stage_input.TEXCOORD; - frag_main(); - SPIRV_Cross_Output stage_output; - stage_output.SV_Target = SV_Target; - return stage_output; -} diff --git a/shaders/PostSharpen/PostSharpen_ps.hlsl b/shaders/PostSharpen/PostSharpen_ps.hlsl new file mode 100644 index 00000000..4a5268fc --- /dev/null +++ b/shaders/PostSharpen/PostSharpen_ps.hlsl @@ -0,0 +1,118 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +cbuffer _13_15 : register(b0, space7) +{ + float4 _15_m0[3269] : packoffset(c0); +}; + + +struct PushConstantWrapper_PostSharpen +{ + float4 params0; + float3 params1; +}; + + +cbuffer CPushConstantWrapper_PostSharpen : register(b0, space0) +{ + PushConstantWrapper_PostSharpen PcwPostSharpen : packoffset(c0); +}; + +Texture2D TonemappedColorTexture : register(t0, space8); // Possibly in gamma space in SDR +SamplerState Sampler0 : register(s13, space6); // Likely bilinear +SamplerState Sampler1 : register(s15, space6); // Likely nearest neighbor + +struct PSInput +{ + float4 TEXCOORD : TEXCOORD0; + float4 SV_Position : SV_Position0; +}; + +struct PSOutput +{ + float4 SV_Target : SV_Target0; +}; + +#if SDR_LINEAR_INTERMEDIARY + #define GAMMA_TO_LINEAR(x) x + #define LINEAR_TO_GAMMA(x) x +#elif SDR_USE_GAMMA_2_2 + #define GAMMA_TO_LINEAR(x) pow(x, 2.2f) + #define LINEAR_TO_GAMMA(x) pow(x, 1.f / 2.2f) +#else + #define GAMMA_TO_LINEAR(x) gamma_sRGB_to_linear(x) + #define LINEAR_TO_GAMMA(x) gamma_linear_to_sRGB(x) +#endif + + +[RootSignature(ShaderRootSignature)] +PSOutput PS(PSInput psInput) +{ + float3 outColor; + + if (HdrDllPluginConstants.PostSharpen == false) // Disable post sharpen + { + outColor = TonemappedColorTexture.Sample(Sampler0, psInput.TEXCOORD.xy).rgb; + } + else + { + float3 inColor = TonemappedColorTexture.Sample(Sampler0, psInput.TEXCOORD.xy).rgb; + outColor = inColor; + float4 sharpenParams = PcwPostSharpen.params0; + float sharpenIntensity = sharpenParams.z; + if (sharpenIntensity > 0.f && sharpenIntensity != 1.f) + { + // Sharpening is best done in linear space, even if Bethesda made in gamma space + if (HdrDllPluginConstants.DisplayMode <= 0) + { + inColor = GAMMA_TO_LINEAR(inColor); + } + float _70 = ((_15_m0[161u].z * psInput.TEXCOORD.x) * sharpenParams.x) + 0.5f; + float _72 = ((_15_m0[161u].w * psInput.TEXCOORD.y) * sharpenParams.y) + 0.5f; + float _76 = frac(_70); + float _77 = frac(_72); + float _87 = ((((((_76 * 2.f) + (-3.f)) * _76) + (-3.f)) * _76) + 5.f) * (1.f / 6.f); + float _89 = _76 * 3.f; + float _98 = ((((((3.f - _89) + _76) * _76) + 3.f) * _76) + 1.f) * (1.f / 6.f); + float _99 = _76 * _76; + float _113 = _77 * _77; + float _114 = _77 * 3.f; + float _125 = ((((((_77 * 2.f) + (-3.f)) * _77) + (-3.f)) * _77) + 5.f) * (1.f / 6.f); + float _136 = ((((((3.f - _114) + _77) * _77) + 3.f) * _77) + 1.f) * (1.f / 6.f); + float _139 = floor(_70) + (-0.5f); + float _142 = floor(_72) + (-0.5f); + float _144 = (_139 + (((((_99 * (_89 + (-6.f))) + 4.f) * (1.f / 6.f)) / _87) + (-1.f))) / _15_m0[161u].z; + float _145 = (_142 + (((((_113 * (_114 + (-6.f))) + 4.f) * (1.f / 6.f)) / _125) + (-1.f))) / _15_m0[161u].w; + float _147 = (_139 + ((((_99 * (1.f / 6.f)) * _76) / _98) + 1.f)) / _15_m0[161u].z; + float _149 = (_142 + ((((_113 * (1.f / 6.f)) * _77) / _136) + 1.f)) / _15_m0[161u].w; + float3 _152 = TonemappedColorTexture.Sample(Sampler1, float2(_144, _145)); + float3 _157 = TonemappedColorTexture.Sample(Sampler1, float2(_147, _145)); + float3 _162 = TonemappedColorTexture.Sample(Sampler1, float2(_144, _149)); + float3 _167 = TonemappedColorTexture.Sample(Sampler1, float2(_147, _149)); + if (HdrDllPluginConstants.DisplayMode <= 0) + { + _152 = GAMMA_TO_LINEAR(_152); + _157 = GAMMA_TO_LINEAR(_157); + _162 = GAMMA_TO_LINEAR(_162); + _167 = GAMMA_TO_LINEAR(_167); + } + float3 unsharpenedColor = (((_167 * _98) + (_162 * _87)) * _136) + (((_157 * _98) + (_152 * _87)) * _125); + // Controls the amount of a custom blurred bilinear filtering vs HW bilinear (which is blurry if there's upscaling), + // by lerping beyond 1 in the opposite direction of the blurred image, we apply sharpening. + outColor = lerp(unsharpenedColor, inColor, sharpenIntensity); + if (HdrDllPluginConstants.DisplayMode <= 0) + { + outColor = LINEAR_TO_GAMMA(outColor); + } + } + } + + PSOutput psOutput; + + psOutput.SV_Target.rgb = outColor; + psOutput.SV_Target.a = 1.f; + + return psOutput; +} diff --git a/shaders/PostSharpen/RootSignature.hlsl b/shaders/PostSharpen/RootSignature.hlsl new file mode 100644 index 00000000..40cd95d7 --- /dev/null +++ b/shaders/PostSharpen/RootSignature.hlsl @@ -0,0 +1,83 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "RootConstants(num32BitConstants=7, b0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=6), " \ + "SRV(t1, space=6), " \ + "SRV(t2, space=6, flags=DATA_VOLATILE), " \ + "SRV(t3, space=6), " \ + "SRV(t4, space=6), " \ + "SRV(t5, space=6), " \ + "SRV(t7, space=6), " \ + "SRV(t8, space=6), " \ + "SRV(t9, space=6), " \ + "SRV(t10, space=6), " \ + "SRV(t11, space=6), " \ + "SRV(t12, space=6), " \ + "SRV(t13, space=6), " \ + "SRV(t14, space=6), " \ + "SRV(t15, space=6), " \ + "SRV(t16, space=6), " \ + "SRV(t17, space=6), " \ + "SRV(t18, space=6), " \ + "SRV(t19, space=6), " \ + "SRV(t20, space=6), " \ + "SRV(t21, space=6), " \ + "SRV(t22, space=6), " \ + "SRV(t23, space=6), " \ + "SRV(t24, space=6), " \ + "SRV(t25, space=6), " \ + "SRV(t26, space=6), " \ + "UAV(u0, space=6), " \ + "UAV(u1, space=6), " \ + "SRV(t27, space=6), " \ + "SRV(t28, space=6) " \ + "), " \ + \ + "DescriptorTable( " \ + "Sampler(s0, numDescriptors=10, space=6), " \ + "Sampler(s10, numDescriptors=2, space=6) " \ + "), " \ + \ + "SRV(t6, space=6), " \ + "CBV(b0, space=6), " \ + "CBV(b1, space=6), " \ + \ + "DescriptorTable( " \ + "SRV(t2, space=7), " \ + "SRV(t3, space=7), " \ + "SRV(t5, space=7, flags=DATA_VOLATILE), " \ + "SRV(t6, space=7, flags=DATA_VOLATILE), " \ + "UAV(u0, space=7), " \ + "UAV(u1, space=7), " \ + "UAV(u2, space=7), " \ + "UAV(u3, space=7), " \ + "SRV(t7, numDescriptors=12, space=7, flags=DATA_VOLATILE) " \ + "), " \ + \ + "SRV(t0, space=7), " \ + "SRV(t1, space=7), " \ + "SRV(t4, space=7), " \ + "CBV(b0, space=7), " \ + "CBV(b1, space=7), " \ + "CBV(b2, space=7), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s12, filter=FILTER_MIN_MAG_MIP_POINT, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s13, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s14, filter=FILTER_MIN_MAG_MIP_LINEAR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s15, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s16, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s17, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s18, addressU=TEXTURE_ADDRESS_MIRROR, addressV=TEXTURE_ADDRESS_MIRROR, addressW=TEXTURE_ADDRESS_MIRROR, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s19, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=4, comparisonFunc=COMPARISON_NEVER, space=6), " \ + "StaticSampler(s20, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_LESS, space=6), " \ + "StaticSampler(s21, filter=FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_GREATER, space=6) " diff --git a/shaders/ScaleformComposite/RootSignature.hlsl b/shaders/ScaleformComposite/RootSignature.hlsl new file mode 100644 index 00000000..964ac10d --- /dev/null +++ b/shaders/ScaleformComposite/RootSignature.hlsl @@ -0,0 +1,14 @@ +#include "../shared.hlsl" + +#define ShaderRootSignature \ + "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " \ + \ + "RootConstants(num32BitConstants=2, b0), " \ + \ + "DescriptorTable( " \ + "SRV(t0, space=8, flags=DESCRIPTORS_VOLATILE), " \ + "UAV(u0, space=8, flags=DESCRIPTORS_VOLATILE) " \ + "), " \ + \ + "RootConstants(num32BitConstants=" HDR_PLUGIN_CONSTANTS_SIZE ", b3), " \ + "StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, addressW=TEXTURE_ADDRESS_CLAMP, maxAnisotropy=1, comparisonFunc=COMPARISON_NEVER, space=8) " diff --git a/shaders/ScaleformComposite/ScaleformComposite_FFAA_ps.hlsl b/shaders/ScaleformComposite/ScaleformComposite_FFAA_ps.hlsl deleted file mode 100644 index 12e8d572..00000000 --- a/shaders/ScaleformComposite/ScaleformComposite_FFAA_ps.hlsl +++ /dev/null @@ -1,91 +0,0 @@ -// Also in "tonemap" shaders. -#define ENABLE_HDR 1 -#define HDR_UI_PAPER_WHITE 2.5f -// Hack: change the alpha value at which the UI blends in in HDR, to increase readability. Range is 0 to 1, with 1 having no effect. -#define HDR_UI_BLEND_POW 0.775f -#define HDR_GAMMA_CORRECTION 1 - -struct PushConstantWrapper_ScaleformCompositeLayout -{ - int Unknown1; - int Unknown2; -}; - -cbuffer stub_PushConstantWrapper_ScaleformCompositeLayout : register(b0) -{ - PushConstantWrapper_ScaleformCompositeLayout Layout : packoffset(c0); -}; - -Texture2D inputTexture : register(t0, space8); -SamplerState inputSampler : register(s0, space8); - -float gamma_linear_to_sRGB(float channel) -{ - [flatten] - if (channel <= 0.0031308f) - { - channel = channel * 12.92f; - } - else - { - channel = 1.055f * pow(channel, 1.0f / 2.4f) - 0.055f; - } - return channel; -} - -float3 gamma_linear_to_sRGB(float3 Color) -{ - return float3(gamma_linear_to_sRGB(Color.r), - gamma_linear_to_sRGB(Color.g), - gamma_linear_to_sRGB(Color.b)); -} - -float gamma_sRGB_to_linear(float channel) -{ - [flatten] - if (channel <= 0.04045f) - { - channel = channel / 12.92f; - } - else - { - channel = pow((channel + 0.055f) / 1.055f, 2.4f); - } - return channel; -} - -float3 gamma_sRGB_to_linear(float3 Color) -{ - return float3(gamma_sRGB_to_linear(Color.r), - gamma_sRGB_to_linear(Color.g), - gamma_sRGB_to_linear(Color.b)); -} - -struct PSInputs -{ - float4 uv : TEXCOORD0; - float4 pos : SV_Position; -}; - -float4 PS(PSInputs inputs) : SV_Target -{ - float4 UIColor = inputTexture.Sample(inputSampler, float2(inputs.uv.x, inputs.uv.y)); - float UIIntensity = asfloat(Layout.Unknown1); - - UIColor.xyz = gamma_sRGB_to_linear(UIColor.xyz); - UIColor.xyz = UIColor.xyz * UIIntensity; -#if !ENABLE_HDR - UIColor.xyz = gamma_linear_to_sRGB(UIColor.xyz); -#else -#if HDR_GAMMA_CORRECTION - UIColor.xyz = pow(gamma_linear_to_sRGB(UIColor.xyz), 2.2f); -#endif - UIColor.xyz *= HDR_UI_PAPER_WHITE; - // Scale alpha to emulate sRGB gamma blending (we blend in linear space in HDR), - // this won't ever be perfect but it's close enough for most cases. - // We do a saturate to avoid pow of -0, which might lead to unexpected results. - //UIColor.a = pow(saturate(UIColor.a), HDR_UI_BLEND_POW); //TODO: base the percentage of application of "HDR_UI_BLEND_POW" based on how black/dark the UI color is. -#endif // ENABLE_HDR - - return UIColor; -} diff --git a/shaders/ScaleformComposite/ScaleformComposite_ps.hlsl b/shaders/ScaleformComposite/ScaleformComposite_ps.hlsl new file mode 100644 index 00000000..1b6d69dc --- /dev/null +++ b/shaders/ScaleformComposite/ScaleformComposite_ps.hlsl @@ -0,0 +1,165 @@ +#include "../shared.hlsl" +#include "../color.hlsl" +#include "RootSignature.hlsl" + +#define USE_REPLACED_COMPOSITION (FORCE_VANILLA_LOOK ? 1 : 1) +#define OPTIMIZE_REPLACED_COMPOSITION_BLENDS (FORCE_VANILLA_LOOK ? 0 : 0) +#define CLIP_HDR_BACKGROUND 0 +// Hack: change the alpha value at which the UI blends in in HDR, to increase readability. Range is 0 to 1, with 1 having no effect. +// We found the best value empirically and it seems to match gamma 2.2. +// Note that this make the look more towards SDR sRGB gamma blends when the background is white and the UI is dark, +// but in the opposite case, it will have the inverse effect (or something like that). +#define HDR_UI_BLEND_POW (1.f / 2.2f) +// Let's only correct up to a percentage to avoid corrections in the other direction +// (e.g. the game sometimes forgets some UI widgets in the view that had a very low alpha, +// and without or alpha pow modifications, it becomes much more noticeable). +#define HDR_UI_BLEND_POW_ALPHA 0.5f + +#if SDR_USE_GAMMA_2_2 + #define GAMMA_TO_LINEAR(x) pow(x, 2.2f) + #define LINEAR_TO_GAMMA(x) pow(x, 1.f / 2.2f) +#else + #define GAMMA_TO_LINEAR(x) gamma_sRGB_to_linear(x) + #define LINEAR_TO_GAMMA(x) gamma_linear_to_sRGB(x) +#endif + +struct PushConstantWrapper_ScaleformCompositeLayout +{ + float UIIntensity; // 1.0f under most cases + float Unknown2; // 2.4f (probably the pow value of their broken sRGB formula) +}; + +ConstantBuffer ScaleformCompositeLayout : register(b0); + +Texture2D UITexture : register(t0, space8); +SamplerState UISampler : register(s0, space8); +#if USE_REPLACED_COMPOSITION +RWTexture2D FinalColorTexture : register(u0, space8); +#endif // USE_REPLACED_COMPOSITION + +struct PSInputs +{ + float4 uv : TEXCOORD0; + float4 pos : SV_Position; +}; + +[RootSignature(ShaderRootSignature)] +float4 PS(PSInputs psInputs) : SV_Target +{ + float4 UIColor = UITexture.Sample(UISampler, psInputs.uv.xy); + + // NOTE: any kind of modulation we do on the UI might not be acknowledged by DLSS FG, + // as it has a copy of the UI buffer that it uses to determine how much to reconstruct pixels. + + // We do a saturate because the original UI texture was a INT/UNORM so it couldn't have had values beyond 0-1. And this also avoids negatives powers in the code below. + UIColor = saturate(UIColor); + + // Theoretically all UI would be in sRGB though it seems like it was designed on gamma 2.2 screens, and even if it wasn't, that's how it looks in the game + UIColor.rgb = GAMMA_TO_LINEAR(UIColor.rgb); + + // This multiplication is probably used by Bethesda to dim the UI when applying an AutoHDR pass at the very end (they don't have real HDR) + UIColor.rgb *= ScaleformCompositeLayout.UIIntensity; + + const bool isHDR = HdrDllPluginConstants.DisplayMode > 0; + bool isLinear = true; + float LinearUIPaperWhite = 1.f; + +#if !SDR_LINEAR_INTERMEDIARY + if (isHDR) +#endif // SDR_LINEAR_INTERMEDIARY + { + LinearUIPaperWhite = isHDR ? (HdrDllPluginConstants.HDRUIPaperWhiteNits / WhiteNits_sRGB) : 1.f; + +#if !USE_REPLACED_COMPOSITION || OPTIMIZE_REPLACED_COMPOSITION_BLENDS + + // Scale alpha to emulate sRGB gamma blending (we blend in linear space in HDR), + // this won't ever be perfect but it's close enough for most cases. +#if DEVELOPMENT && 0 // Quick testing + float HDRUIBlendPow = 1.f - HdrDllPluginConstants.DevSetting02; +#else + float HDRUIBlendPow = HDR_UI_BLEND_POW; +#endif // DEVELOPMENT +#if 1 + // Base the alpha pow application percentage on the color luminance. + // Generally speaking dark colors (with a low alpha) are meant as darkneing (transparent) backgrounds, + // while brighter/whiter colors are meant to replace the background color directly (opaque), + // so we could take that into account to avoid cases where the alpha pow would make stuff look worse. + HDRUIBlendPow = lerp(HDRUIBlendPow, 1.f, saturate(Luminance(UIColor.xyz))); +#else + HDRUIBlendPow = lerp(1.f, HDRUIBlendPow, HDR_UI_BLEND_POW_ALPHA); +#endif + UIColor.a = pow(UIColor.a, HDRUIBlendPow); + +#endif // !USE_REPLACED_COMPOSITION || OPTIMIZE_REPLACED_COMPOSITION_BLENDS + } +#if !SDR_LINEAR_INTERMEDIARY + else + { + UIColor.rgb = LINEAR_TO_GAMMA(UIColor.rgb); + isLinear = false; + } +#endif // SDR_LINEAR_INTERMEDIARY + +#if USE_REPLACED_COMPOSITION + if (all(UIColor == 0.f)) // UI will have no influence at all in this case, skip all the conversions and writes + { + discard; + return 0; + } + const float3 backgroundColor = FinalColorTexture[psInputs.pos.xy].rgb; // This is always in linear unless "SDR_LINEAR_INTERMEDIARY" was false and we were in SDR + float3 outputColor; +#if !OPTIMIZE_REPLACED_COMPOSITION_BLENDS + // Do this even if "UIColor.a" is 1, as we still need to tonemap the HDR background + if (isLinear) + { + float GamePaperWhite = isHDR ? (HdrDllPluginConstants.HDRGamePaperWhiteNits / WhiteNits_sRGB) : 1.f; + + // 1) Emulate SDR gamma space blends: + + const float3 normalizedBackgroundColor = backgroundColor / GamePaperWhite; + const float3 SDRBackgroundColor = saturate(normalizedBackgroundColor); + const float3 excessBackgroundColor = (normalizedBackgroundColor - SDRBackgroundColor) * GamePaperWhite; + + const float3 UIColorGammaSpace = LINEAR_TO_GAMMA(UIColor.rgb); + const float3 SDRBackgroundColorGammaSpace = LINEAR_TO_GAMMA(SDRBackgroundColor); + const float3 DarkenedSDRBackgroundColorGammaSpace = SDRBackgroundColorGammaSpace * (1.f - UIColor.a); + outputColor = GAMMA_TO_LINEAR(UIColorGammaSpace + DarkenedSDRBackgroundColorGammaSpace); + + // 2) Restore the paper white multipliers: + + // Find out how much the UI has changed the non darkened background color (in gamma space to keep ratios the same). + float3 UIInfluence = select(SDRBackgroundColorGammaSpace == 0.f, 1.f, 1.f - (SDRBackgroundColorGammaSpace / (UIColorGammaSpace + SDRBackgroundColorGammaSpace))); + // Lerp the UI influence to 1 if the UI alpha is higher, as that means the background had been darkened by that amount, and thus had reduced influence in the final color. + UIInfluence = lerp(UIInfluence, 1.f, UIColor.a); + outputColor *= lerp(GamePaperWhite, LinearUIPaperWhite, UIInfluence); + + // 3) Then add any color in excess in linear space, as there's no other way really: + + // Apply the Reinhard tonemapper on any background color in excess, to avoid it burning it through the UI. + // NOTE: If this is not enough we could already apply to the entire "backgroundColor" before blending it with the UI. + float3 tonemappedBackgroundColor = abs(excessBackgroundColor) / (1.f + abs(excessBackgroundColor)) * sign(excessBackgroundColor); + // In SDR, we clip any HDR color passing through the UI, as long as the UI has ANY kind of influence on the output. + // The reason is that the game wouldn't have ever had any colors beyond 0-1 due to having int UNORM textures, so we want to replicate the same look. + tonemappedBackgroundColor *= isHDR ? 1.f : 0.f; +#if CLIP_HDR_BACKGROUND // If backgrounds were ever too bright, we can just clip them + tonemappedBackgroundColor = 0.f; +#endif // !CLIP_HDR_BACKGROUND + outputColor += lerp(tonemappedBackgroundColor, excessBackgroundColor, 1.f - UIColor.a) * (1.f - UIColor.a); + } + else +#endif // !OPTIMIZE_REPLACED_COMPOSITION_BLENDS + { + // Pre-multiplied alpha formula + outputColor = UIColor.rgb + (backgroundColor * (1.f - UIColor.a)); + } + + FinalColorTexture[psInputs.pos.xy].rgb = outputColor; + + // The Luma plugin binds a null render target on the engine side. All writes beyond this point are discarded regardless + // of whether a "discard" statement is used. + discard; + return 0.f; +#else + return UIColor; +#endif // USE_REPLACED_COMPOSITION +} diff --git a/shaders/Unused/ps_2532921200.hlsl b/shaders/Unused/ps_2532921200.hlsl deleted file mode 100644 index 3b091822..00000000 --- a/shaders/Unused/ps_2532921200.hlsl +++ /dev/null @@ -1,33 +0,0 @@ -Texture2D _8 : register(t0, space8); -SamplerState _11 : register(s0, space8); - -static float4 TEXCOORD; -static float4 SV_Target; - -struct SPIRV_Cross_Input -{ - float4 TEXCOORD : TEXCOORD0; -}; - -struct SPIRV_Cross_Output -{ - float4 SV_Target : SV_Target0; -}; - -void frag_main() -{ - float4 _31 = _8.Sample(_11, float2(TEXCOORD.x, TEXCOORD.y)); - SV_Target.x = _31.x; - SV_Target.y = _31.y; - SV_Target.z = _31.z; - SV_Target.w = _31.w; -} - -SPIRV_Cross_Output main(SPIRV_Cross_Input stage_input) -{ - TEXCOORD = stage_input.TEXCOORD; - frag_main(); - SPIRV_Cross_Output stage_output; - stage_output.SV_Target = SV_Target; - return stage_output; -} diff --git a/shaders/color.hlsl b/shaders/color.hlsl new file mode 100644 index 00000000..cd4fb169 --- /dev/null +++ b/shaders/color.hlsl @@ -0,0 +1,401 @@ +#pragma once + +// sRGB SDR white is meant to be mapped to 80 nits (not 100, even if some game engine (UE) and consoles (PS5) interpret it as such). +static const float WhiteNits_sRGB = 80.f; +static const float ReferenceWhiteNits_BT2408 = 203.f; + +// SDR mid gray. +// This is based on the commonly used value, though perception space mid gray in sRGB or Gamma 2.2 would theoretically be ~0.2155 +static const float MidGray = 0.18f; + +// Start of the highlights shoulder (empirical) +static const float MinHighlightsColor = pow(2.f / 3.f, 2.2f); +static const float MaxShadowsColor = pow(1.f / 3.f, 2.2f); + +// SMPTE ST 2084 (Perceptual Quantization) is only defined until this amount of nits. +// This is also the max each color channel can have in HDR10. +static const float PQMaxNits = 10000.0f; +// SMPTE ST 2084 is defined as using BT.2020 white point. +static const float PQMaxWhitePoint = PQMaxNits / WhiteNits_sRGB; + +// These have been calculated to be as accurate as possible +static const float3x3 BT709_2_BT2020 = float3x3( + 0.62722527980804443359375f, 0.329476892948150634765625f, 0.04329781234264373779296875f, + 0.0690418779850006103515625f, 0.919605672359466552734375f, 0.011352437548339366912841796875f, + 0.01639117114245891571044921875f, 0.0880887508392333984375f, 0.89552009105682373046875f); + +static const float3x3 BT2020_2_BT709 = float3x3( + 1.6609637737274169921875f, -0.58811271190643310546875f, -0.072851054370403289794921875f, + -0.124477200210094451904296875f, 1.1328194141387939453125f, -0.00834227167069911956787109375f, + -0.0181571580469608306884765625f, -0.10066641867160797119140625f, 1.118823528289794921875f); + +static const half3x3 BT709_2_BT2020_half = half3x3( + 0.62744140625h, 0.32958984375h, 0.043304443359375h, + 0.06903076171875h, 0.91943359375h, 0.0113525390625h, + 0.016387939453125h, 0.08807373046875h, 0.8955078125h); + +static const half3x3 BT2020_2_BT709_half = half3x3( + 1.6611328125h, -0.587890625h, -0.0728759765625h, + -0.12445068359375h, 1.1328125h, -0.00833892822265625h, + -0.018157958984375h, -0.10064697265625h, 1.119140625h); + +static const float3x3 BT709_2_AP0D65 = float3x3( + 0.43379461765289306640625, 0.376462161540985107421875, 0.189743220806121826171875, + 0.088556401431560516357421875, 0.809415638446807861328125, 0.102027960121631622314453125, + 0.01774938963353633880615234375, 0.109539218246936798095703125, 0.8727114200592041015625); + +static const float3x3 AP0D65_2_BT709 = float3x3( + 2.5532894134521484375, -1.13030064105987548828125, -0.422988712787628173828125, + -0.2771895825862884521484375, 1.3780276775360107421875, -0.100838042795658111572265625, + -0.0171376205980777740478515625, -0.14997617900371551513671875, 1.167113780975341796875); + +static const float PQ_constant_M1 = 0.1593017578125f; +static const float PQ_constant_M2 = 78.84375f; +static const float PQ_constant_C1 = 0.8359375f; +static const float PQ_constant_C2 = 18.8515625f; +static const float PQ_constant_C3 = 18.6875f; + +float3 BT709_To_BT2020(float3 color) +{ + return mul(BT709_2_BT2020, color); +} + +float3 BT2020_To_BT709(float3 color) +{ + return mul(BT2020_2_BT709, color); +} + +half3 BT709_To_BT2020_half(half3 color) +{ + return mul(BT709_2_BT2020_half, color); +} + +half3 BT2020_To_BT709_half(half3 color) +{ + return mul(BT2020_2_BT709_half, color); +} + +float3 BT709_To_AP0D65(float3 color) +{ + return mul(BT709_2_AP0D65, color); +} + +float3 AP0D65_To_BT709(float3 color) +{ + return mul(AP0D65_2_BT709, color); +} + +float gamma_linear_to_sRGB(float channel) +{ + [flatten] + if (channel <= 0.0031308f) + { + channel = channel * 12.92f; + } + else + { + channel = 1.055f * pow(channel, 1.f / 2.4f) - 0.055f; + } + return channel; +} + +float3 gamma_linear_to_sRGB(float3 Color) +{ + return float3(gamma_linear_to_sRGB(Color.r), + gamma_linear_to_sRGB(Color.g), + gamma_linear_to_sRGB(Color.b)); +} + +float gamma_sRGB_to_linear(float channel) +{ + [flatten] + if (channel <= 0.04045f) + { + channel = channel / 12.92f; + } + else + { + channel = pow((channel + 0.055f) / 1.055f, 2.4f); + } + return channel; +} + +float3 gamma_sRGB_to_linear(float3 Color) +{ + return float3(gamma_sRGB_to_linear(Color.r), + gamma_sRGB_to_linear(Color.g), + gamma_sRGB_to_linear(Color.b)); +} + +// PQ (Perceptual Quantizer - ST.2084) encode/decode used for HDR10 BT.2100 +float3 Linear_to_PQ(float3 LinearColor) +{ + float3 colorPow = pow(LinearColor, PQ_constant_M1); + float3 numerator = PQ_constant_C1 + PQ_constant_C2 * colorPow; + float3 denominator = 1.f + PQ_constant_C3 * colorPow; + float3 pq = pow(numerator / denominator, PQ_constant_M2); + return pq; +} + +float3 Linear_to_PQ(float3 LinearColor, const float PQMaxValue) +{ + LinearColor /= PQMaxValue; + return Linear_to_PQ(LinearColor); +} + +float PQ_to_Linear(float ST2084Color) +{ + float colorPow = pow(ST2084Color, 1.f / PQ_constant_M2 ); + float numerator = max(colorPow - PQ_constant_C1, 0.f); + float denominator = PQ_constant_C2 - (PQ_constant_C3 * colorPow); + float linearColor = pow(numerator / denominator, 1.f / PQ_constant_M1); + return linearColor; +} + +float3 PQ_to_Linear(float3 ST2084Color) +{ + return float3(PQ_to_Linear(ST2084Color.r), + PQ_to_Linear(ST2084Color.g), + PQ_to_Linear(ST2084Color.b)); +} + +float3 PQ_to_Linear(float3 ST2084Color, const float PQMaxValue) +{ + float3 linearColor = PQ_to_Linear(ST2084Color); + linearColor *= PQMaxValue; + return linearColor; +} + +// PQ approximation for speeeeeeeeed +float3 Linear_to_PQ_approx(float3 LinearColor) +{ + LinearColor = max(LinearColor, 0.f); + return pow(LinearColor , 1.f / 8.f); +} + +float3 PQ_approx_to_Linear(float3 PQApproxColor) +{ + return PQApproxColor + * PQApproxColor + * PQApproxColor + * PQApproxColor + * PQApproxColor + * PQApproxColor + * PQApproxColor + * PQApproxColor; +} + +float Luminance(float3 color) +{ + // Fixed from "wrong" values: 0.2125 0.7154 0.0721f + return dot(color, float3(0.2125072777271270751953125f, 0.71535003185272216796875f, 0.07214272022247314453125f)); +} + +float3 Saturation(float3 color, float saturation) +{ + float luminance = Luminance(color); + return lerp(luminance, color, saturation); +} + + +//RGB linear BT.709/sRGB -> OKLab's LMS +static const float3x3 srgb_to_oklms = { + 0.4122214708f, 0.5363325363f, 0.0514459929f, + 0.2119034982f, 0.6806995451f, 0.1073969566f, + 0.0883024619f, 0.2817188376f, 0.6299787005f}; + +//OKLab's L'M'S' -> OKLab +static const float3x3 oklms__to_oklab = { + 0.2104542553f, 0.7936177850f, -0.0040720468f, + 1.9779984951f, -2.4285922050f, 0.4505937099f, + 0.0259040371f, 0.7827717662f, -0.8086757660f}; + +//OKLab -> OKLab's L'M'S' +//the 1s get optimized away by the compiler +static const float3x3 oklab_to_oklms_ = { + 1.f, 0.3963377774f, 0.2158037573f, + 1.f, -0.1055613458f, -0.0638541728f, + 1.f, -0.0894841775f, -1.2914855480f}; + +//OKLab's LMS -> RGB linear BT.709/sRGB +static const float3x3 oklms_to_srgb = { + 4.0767416621f, -3.3077115913f, 0.2309699292f, + -1.2684380046f, 2.6097574011f, -0.3413193965f, + -0.0041960863f, -0.7034186147f, 1.7076147010f}; + +// sRGB/BT.709 +float3 linear_srgb_to_oklab(float3 rgb) { + float3 lms = mul(srgb_to_oklms, rgb); + + // Not sure whether the pow(abs())*sign() is technically correct, but if we pass in scRGB negative colors, this breaks, + // and we think this might work fine (we could convert to BT.2020 first otherwise) + //L'M'S' + float3 lms_ = pow(abs(lms), 1.f/3.f) * sign(lms); + + return mul(oklms__to_oklab, lms_); +} + +// sRGB/BT.709 +float3 oklab_to_linear_srgb(float3 lab) { + //L'M'S' + float3 lms_ = mul(oklab_to_oklms_, lab); + + float3 lms = lms_ * lms_ * lms_; + + return mul(oklms_to_srgb, lms); +} + +float3 oklab_to_oklch(float3 lab) { + float L = lab[0]; + float a = lab[1]; + float b = lab[2]; + return float3( + L, + sqrt((a*a) + (b*b)), + atan2(b, a) + ); +} + +float3 oklch_to_oklab(float3 lch) { + float L = lch[0]; + float C = lch[1]; + float h = lch[2]; + return float3( + L, + C * cos(h), + C * sin(h) + ); +} + +float3 oklch_to_linear_srgb(float3 lch) { + return oklab_to_linear_srgb( + oklch_to_oklab(lch) + ); +} + +float3 linear_srgb_to_oklch(float3 rgb) { + return oklab_to_oklch( + linear_srgb_to_oklab(rgb) + ); +} + +// This is almost a perfect approximation of sRGB gamma, but it clips any color below 0.055. +float3 gamma_linear_to_sRGB_Bethesda_Optimized(float3 Color, float InverseGamma = 1.f / 2.4f) +{ + return (pow(Color, InverseGamma) * 1.055f) - 0.055f; +} + + // Original exact inverse formula, this is heavily broken, especially in its inverse form +float3 gamma_sRGB_to_linear_Bethesda_Optimized(float3 Color, float Gamma = 2.4f) +{ + return (pow(Color, Gamma) / 1.055f) + 0.055f; +} + +//L'M'S'->ICtCp +static const float3x3 PQ_LMS_2_ICtCp = { + 0.5f, 0.5f, 0.f, + 1.61376953125f, -3.323486328125f, 1.709716796875f, + 4.378173828125f, -4.24560546875f, -0.132568359375f}; + +//ICtCp->L'M'S' +//the 1s get optimized away by the compiler +static const float3x3 ICtCp_2_PQ_LMS = { + 1.f, 0.008609036915004253387451171875f, 0.11102962493896484375f, + 1.f, -0.008609036915004253387451171875f, -0.11102962493896484375f, + 1.f, 0.560031354427337646484375f, -0.3206271827220916748046875f}; + +//RGB BT.709->LMS +static const float3x3 BT709_2_LMS = { + 0.295654296875f, 0.623291015625f, 0.0810546875f, + 0.156005859375f, 0.7275390625f, 0.116455078125f, + 0.03515625f, 0.15673828125f, 0.807861328125f}; + +//LMS->RGB BT.709 +static const float3x3 LMS_2_BT709 = { + 6.171343326568603515625f, -5.318845272064208984375f, 0.14753799140453338623046875f, + -1.3213660717010498046875f, 2.5573856830596923828125f, -0.23607718944549560546875f, + -0.012195955030620098114013671875f, -0.2647107541561126708984375f, 1.27721846103668212890625f}; + +//ICtCp->L'M'S' +float3 ICtCp_to_PQ_LMS(float3 Colour) +{ + return mul(ICtCp_2_PQ_LMS, Colour); +} + +//L'M'S'->ICtCp +float3 PQ_LMS_to_ICtCp(float3 Colour) +{ + return mul(PQ_LMS_2_ICtCp, Colour); +} + +//RGB BT.709->LMS +float3 BT709_to_LMS(float3 Colour) +{ + return mul(BT709_2_LMS, Colour); +} + +//LMS->RGB BT.709 +float3 LMS_to_BT709(float3 Colour) +{ + return mul(LMS_2_BT709, Colour); +} + +float3 BT709_to_ICtCp(float3 Colour) +{ + // Keep division by "PQMaxWhitePoint" here (BT709_to_LMS()) instead of in "Linear_to_PQ()" for floating point accuracy + float3 LMS = BT709_to_LMS(Colour / PQMaxWhitePoint); + float3 PQ_LMS = Linear_to_PQ(LMS); + return PQ_LMS_to_ICtCp(PQ_LMS); +} + +float3 ICtCp_to_BT709(float3 Colour) +{ + float3 PQ_LMS = ICtCp_to_PQ_LMS(Colour); + // max should be save as LMS should be only positive + float3 LMS = max(PQ_to_Linear(PQ_LMS), 0.f); + float3 RGB = LMS_to_BT709(LMS); + return RGB * PQMaxWhitePoint; +} + + +static const float3x3 BT709_2_AP1D65 = { + 0.61685097217559814453125, 0.33406293392181396484375, 0.049086071550846099853515625, + 0.069866396486759185791015625, 0.91741669178009033203125, 0.012716926634311676025390625, + 0.020549066364765167236328125, 0.107642211019992828369140625, 0.871808707714080810546875}; + +static const float3x3 AP1D65_2_BT709 = { + 1.69267940521240234375, -0.606218039989471435546875, -0.086461342871189117431640625, + -0.1285739839076995849609375, 1.13793361186981201171875, -0.009359653107821941375732421875, + -0.02402246557176113128662109375, -0.12621171772480010986328125, 1.150234222412109375}; + +static const float3x3 AP1D65_2_XYZ = { + 0.647292673587799072265625, 0.13440339267253875732421875, 0.1684710681438446044921875, + 0.26599824428558349609375, 0.676089823246002197265625, 0.0579119287431240081787109375, + -0.0054470631293952465057373046875, 0.00407283008098602294921875, 1.0897972583770751953125}; + +static const float3x3 WIDE_2_AP1D65 = { + 0.83451688289642333984375, 0.16025958955287933349609375, 0.005223505198955535888671875, + 0.02554519288241863250732421875, 0.973101556301116943359375, 0.0013532745651900768280029296875, + 0.001925828866660594940185546875, 0.03037279658019542694091796875, 0.967701375484466552734375}; + +// Expand bright saturated BT.709 colors onto BT.2020 to achieve a fake HDR look. +// Input (and output) needs to be in sRGB linear space. +// Calling this with a value of 0 still results in changes (avoid doing so, it might produce invalid colors). +// Calling this with values above 1 yields diminishing returns. +float3 ExtendGamut(float3 Color, float ExtendGamutAmount = 1.f) +{ + float3 ColorAP1 = mul(BT709_2_AP1D65, Color); + float3 ColorExpand = mul(WIDE_2_AP1D65, Color); + + float LumaAP1 = dot(ColorAP1, AP1D65_2_XYZ[1]); + float3 ChromaAP1 = ColorAP1 / LumaAP1; + + float3 ChromaAP1Minus1 = ChromaAP1 - 1.f; + float ChromaDistSqr = dot(ChromaAP1Minus1, ChromaAP1Minus1); + float ExtendGamutAlpha = (1.f - exp2(-4.f * ChromaDistSqr)) * (1.f - exp2(-4.f * ExtendGamutAmount * LumaAP1 * LumaAP1)); + + ColorAP1 = lerp(ColorAP1, ColorExpand, ExtendGamutAlpha); + + Color = mul(AP1D65_2_BT709, ColorAP1); + return Color; +} diff --git a/shaders/compile_all_shaders.bat b/shaders/compile_all_shaders.bat deleted file mode 100644 index fce915f5..00000000 --- a/shaders/compile_all_shaders.bat +++ /dev/null @@ -1,61 +0,0 @@ -@echo off - -set dxc=..\tools\dxc_2023_08_14\bin\x64\dxc.exe - -for /f "delims=" %%x in (target_folder.txt) do set target_folder=%%x - -if "%target_folder%" == "" ( - echo target folder isn't set in "target_folder.txt"! - echo single line with the folder with no quotation marks and a trailing \ - echo example: C:\Games\Starfield\Data\shadersfx\ - pause - goto :eof -) - -if not exist "%target_folder%" ( - echo target folder doesn't exist! - echo creating it... - mkdir "%target_folder%" -) - -"%dxc%" "HDRComposite\HDRComposite_ps.hlsl" ^ - -T ps_6_6 -E PS -D APPLY_MERGED_COLOR_GRADING_LUT -Fo ^ - "%target_folder%\HDRComposite\HDRComposite_E00FF1A_ps.bin" - -"%dxc%" "HDRComposite\HDRComposite_ps.hlsl" ^ - -T ps_6_6 -E PS -Fo ^ - "%target_folder%\HDRComposite\HDRComposite_600FF1A_ps.bin" - -"%dxc%" "HDRComposite\HDRComposite_ps.hlsl" ^ - -T ps_6_6 -E PS -D APPLY_BLOOM -Fo ^ - "%target_folder%\HDRComposite\HDRComposite_700FF1A_ps.bin" - -"%dxc%" "HDRComposite\HDRComposite_ps.hlsl" ^ - -T ps_6_6 -E PS -D APPLY_BLOOM -D APPLY_MERGED_COLOR_GRADING_LUT -Fo ^ - "%target_folder%\HDRComposite\HDRComposite_F00FF1A_ps.bin" - -"%dxc%" "ScaleformComposite\ScaleformComposite_FFAA_ps.hlsl" ^ - -T ps_6_6 -E PS -Fo ^ - "%target_folder%\ScaleformComposite\ScaleformComposite_FFAA_ps.bin" - -"%dxc%" "ColorGradingMerge\ColorGradingMerge_FF81_cs.hlsl" ^ - -T cs_6_6 -E main -Fo ^ - "%target_folder%\ColorGradingMerge\ColorGradingMerge_FF81_cs.bin" - -"%dxc%" "BinkMovie\BinkMovie_FFAB_ps.hlsl" ^ - -T ps_6_6 -E PS -Fo ^ - "%target_folder%\BinkMovie\BinkMovie_FFAB_ps.bin" - -"%dxc%" "FilmGrain\FilmGrain_FF75_ps.hlsl" ^ - -T ps_6_6 -E main -Fo ^ - "%target_folder%\FilmGrain\FilmGrain_FF75_ps.bin" - -"%dxc%" "PostSharpen\PostSharpen_FF9A_ps.hlsl" ^ - -T ps_6_6 -E main -Fo ^ - "%target_folder%\PostSharpen\PostSharpen_FF9A_ps.bin" - -"%dxc%" "ContrastAdaptiveSharpening\ContrastAdaptiveSharpening_100FF94_cs.hlsl" ^ - -T ps_6_6 -E main -Fo ^ - "%target_folder%\ContrastAdaptiveSharpening\ContrastAdaptiveSharpening_100FF94_cs.bin" - -pause \ No newline at end of file diff --git a/shaders/compile_all_shaders.ps1 b/shaders/compile_all_shaders.ps1 new file mode 100644 index 00000000..847c2b07 --- /dev/null +++ b/shaders/compile_all_shaders.ps1 @@ -0,0 +1,148 @@ +$ErrorActionPreference = "Stop" + + +$ShaderOutputDirectory = Get-Content "${PSScriptRoot}\target_folder.txt" +$DistDirectory = "${PSScriptRoot}\..\Plugin\dist\Data\shadersfx\" +$ShaderOutputEmbedPDB = $false + + +$main = +{ + #HDRComposite + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "FF1A" + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "600FF1A" -Defines "APPLY_TONEMAPPING", "APPLY_CINEMATICS" + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "700FF1A" -Defines "APPLY_BLOOM", "APPLY_TONEMAPPING", "APPLY_CINEMATICS" + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "800FF1A" -Defines "APPLY_MERGED_COLOR_GRADING_LUT" + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "E00FF1A" -Defines "APPLY_TONEMAPPING", "APPLY_CINEMATICS", "APPLY_MERGED_COLOR_GRADING_LUT" + Compile-Shader -Type "ps" -TechniqueName "HDRComposite" -TechniqueId "F00FF1A" -Defines "APPLY_BLOOM", "APPLY_TONEMAPPING", "APPLY_CINEMATICS", "APPLY_MERGED_COLOR_GRADING_LUT" + + #Copy + Compile-Shader -Type "ps" -TechniqueName "Copy" -TechniqueId "400FF59" -Defines "OUTPUT_TO_R10G10B10A2" + Compile-Shader -Type "ps" -TechniqueName "Copy" -TechniqueId "2000FF59" -Defines "OUTPUT_TO_R16G16B16A16_SFLOAT" + + #FilmGrain + Compile-Shader -Type "ps" -TechniqueName "FilmGrain" -TechniqueId "FF75" + + #ColorGradingMerge + Compile-Shader -Type "cs" -TechniqueName "ColorGradingMerge" -TechniqueId "FF81" + + #ContrastAdaptiveSharpening + #Compile-Shader -Type "cs" -TechniqueName "ContrastAdaptiveSharpening" -TechniqueId "FF94" -Entry "main" + Compile-Shader -Type "cs" -TechniqueName "ContrastAdaptiveSharpening" -TechniqueId "100FF94" -Defines "USE_PACKED_MATH" -AdditionalParams "-enable-16bit-types", "-Wno-conversion" + Compile-Shader -Type "cs" -TechniqueName "ContrastAdaptiveSharpening" -TechniqueId "300FF94" -Defines "USE_PACKED_MATH", "USE_UPSCALING" -AdditionalParams "-enable-16bit-types", "-Wno-conversion" + + #PostSharpen + Compile-Shader -Type "ps" -TechniqueName "PostSharpen" -TechniqueId "FF9A" + + #ScaleformComposite + Compile-Shader -Type "ps" -TechniqueName "ScaleformComposite" -TechniqueId "FFAA" + + #BinkMovie + Compile-Shader -Type "ps" -TechniqueName "BinkMovie" -TechniqueId "FFAB" +} + + +function Run-DXC { + param ( + [Parameter(Mandatory = $true)] + [string]$Arguments + ) + + $processInfo = New-Object System.Diagnostics.ProcessStartInfo + $processInfo.FileName = "${PSScriptRoot}\..\tools\dxc_2023_08_14\bin\x64\dxc.exe" + $processInfo.Arguments = $Arguments + $processInfo.RedirectStandardError = $true + $processInfo.RedirectStandardOutput = $true + $processInfo.UseShellExecute = $false + $processInfo.CreateNoWindow = $true + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $processInfo + $process.Start() | Out-Null + $process.WaitForExit() + + # Output the result + $stdout = $process.StandardOutput.ReadToEnd() + $stderr = $process.StandardError.ReadToEnd() + + if ($process.ExitCode -ne 0) { + Write-Error "An error occurred during shader compilation:`n$stderr" + } + + if ($stdout.Length -gt 0) { + Write-Host $stdout + } +} + +function Compile-Shader { + param ( + [Parameter(Mandatory = $true)] + [string]$Type, + + [Parameter(Mandatory = $true)] + [string]$TechniqueName, + + [Parameter(Mandatory = $true)] + [string]$TechniqueId, + + [Parameter(Mandatory = $false)] + [string]$Entry = $Type.ToUpper(), + + [parameter(Mandatory = $false)] + [array]$Defines, + + [parameter(Mandatory = $false)] + [array]$AdditionalParams + ) + + $inputHlslName = "${TechniqueName}_${Type}.hlsl" + $outputBinName = "${TechniqueName}_${TechniqueId}_${Type}.bin" + $outputSigName = "${TechniqueName}_${TechniqueId}_rsg.bin" + + $inputHlslPath = "${PSScriptRoot}\${TechniqueName}\${inputHlslName}" + $stagedBinPath = "${PSScriptRoot}\${TechniqueName}\${outputBinName}" + $stagedSigPath = "${PSScriptRoot}\${TechniqueName}\${outputSigName}" + + Write-Host "Compiling ${outputBinName}..." + + # Build the shader in its staging directory + $args = "`"${inputHlslPath}`" -Fo `"${stagedBinPath}`" -T ${Type}_6_6 -E ${Entry} " + + if ($ShaderOutputEmbedPDB -eq $true) { + $args = $args + "-Qembed_debug -Zi " + } + + foreach ($define in $Defines) { + $args = $args + "-D ${define} " + } + + foreach ($param in $AdditionalParams) { + $args = $args + "${param} " + } + + Run-DXC -Arguments $args + + # Extract and strip away the DXIL root signature + # TODO: Can extractrootsignature and Qstrip_rootsignature be used in the same operation? + Run-DXC -Arguments "-dumpbin `"${stagedBinPath}`" -extractrootsignature -Fo `"${stagedSigPath}`"" + Run-DXC -Arguments "-dumpbin `"${stagedBinPath}`" -Qstrip_rootsignature -Fo `"${stagedBinPath}`"" + + # Copy the resulting bins to the dist directory. + New-Item -Force -ItemType Directory -Path "${DistDirectory}\${TechniqueName}" | Out-Null + Copy-Item -Force -Path $stagedBinPath -Destination "${DistDirectory}\${TechniqueName}\${outputBinName}" + Copy-Item -Force -Path $stagedSigPath -Destination "${DistDirectory}\${TechniqueName}\${outputSigName}" + + # Move the resulting bins to the game directory. Move-Item is to avoid partial reads when live shader editing + # is enabled. + New-Item -Force -ItemType Directory -Path "${ShaderOutputDirectory}\${TechniqueName}" | Out-Null + Move-Item -Force -Path $stagedBinPath -Destination "${ShaderOutputDirectory}\${TechniqueName}\${outputBinName}" + Move-Item -Force -Path $stagedSigPath -Destination "${ShaderOutputDirectory}\${TechniqueName}\${outputSigName}" +} + +try { + & $main +} +catch { + Write-Host -ForegroundColor Red $_ + Pause +} diff --git a/shaders/math.hlsl b/shaders/math.hlsl new file mode 100644 index 00000000..499e2332 --- /dev/null +++ b/shaders/math.hlsl @@ -0,0 +1,74 @@ +#pragma once + +#define FLT_MIN 1.175494351e-38f +#define FLT_MAX 3.402823466e+38F +#define FLT10_MAX 64512.f +#define FLT11_MAX 65024.f +#define FLT16_MAX 65504.f + +// From old to new range (just a remap function) +template +T linearNormalization(T input, T min, T max, T newMin, T newMax) +{ + return ((input - min) * ((newMax - newMin) / (max - min))) + newMin; +} + +// Returns 1 if "dividend" is 0 +float safeDivision(float quotient, float dividend) +{ + float result = quotient / dividend; + + if (dividend == 0.f) + { +#if 0 + result = FLT_MAX * sign(quotient); +#else + result = 1.f; +#endif + } + + return result; +} + +// Returns 1 if "dividend" is 0 +float3 safeDivision(float3 quotient, float3 dividend) +{ + return float3(safeDivision(quotient.x, dividend.x), + safeDivision(quotient.y, dividend.y), + safeDivision(quotient.z, dividend.z)); +} + +// Aplies exponential ("Photographic") luminance/luma compression. +// The pow can modulate the curve without changing the values around the edges. +float rangeCompress(float X, float Max = FLT_MAX, float Pow = 1.f) +{ + // Branches are for static parameters optimizations + if (Pow == 1.f && Max == FLT_MAX) + { + // This does e^X. We expect X to be between 0 and 1. + return 1.f - exp(-X); + } + if (Pow == 1.f && Max != FLT_MAX) + { + const float fLostRange = exp(-Max); + const float fRestoreRangeScale = 1.f / (1.f - fLostRange); + return (1.f - exp(-X)) * fRestoreRangeScale; + } + if (Pow != 1.f && Max == FLT_MAX) + { + return (1.f - pow(exp(-X), Pow)); + } + const float lostRange = pow(exp(-Max), Pow); + const float restoreRangeScale = 1.f / (1.f - lostRange); + return (1.f - pow(exp(-X), Pow)) * restoreRangeScale; +} + +// Refurbished DICE HDR tonemapper (per channel or luminance) +float luminanceCompress(float InValue, float OutMaxValue, float ShoulderStart = 0.f, bool considerMaxValue = false, float InMaxValue = FLT_MAX, float ModulationPow = 1.f) +{ + const float compressableValue = InValue - ShoulderStart; + const float compressableRange = InMaxValue - ShoulderStart; + const float compressedRange = OutMaxValue - ShoulderStart; + const float possibleOutValue = ShoulderStart + compressedRange * rangeCompress(compressableValue / compressedRange, considerMaxValue ? (compressableRange / compressedRange) : FLT_MAX, ModulationPow); + return InValue <= ShoulderStart ? InValue : possibleOutValue; +} diff --git a/shaders/shared.hlsl b/shaders/shared.hlsl new file mode 100644 index 00000000..6aca88a4 --- /dev/null +++ b/shaders/shared.hlsl @@ -0,0 +1,71 @@ +#pragma once + +#include "structs.hlsl" + +// Turn on when developing to engage error checks and development setting variables +#define DEVELOPMENT 0 + +// Preset all defines to be as close as possible to the og game vanilla look +#define FORCE_VANILLA_LOOK 0 +#define CLAMP_INPUT_OUTPUT 0 +// If this is true, the code makes the assumption that Bethesda developed and calibrated the game on gamma 2.2 screens, as opposed to sRGB gamma. +// This implies there was a mismatch baked in the output colors, as they were using a ~sRGB similar formula, which would then be interpreted by screens as 2.2 gamma. +// By turning this on, we emulate the SDR look in HDR (and out SDR) by baking that assumption into our calculations. +// This makes sense to use given we fix up (normalize) the LUTs colors and their gamma mapping. +#define SDR_USE_GAMMA_2_2 (FORCE_VANILLA_LOOK ? 0 : 1) + +// If true, SDR will be kept in linear space until the final out. +// This is desired for output quality as we store colors on float buffers, which are based kept in linear space, +// it also simplifies the code and optmizes performance, but at the moment is changes the look of the Scaleform UI blend in. +#define SDR_LINEAR_INTERMEDIARY (FORCE_VANILLA_LOOK ? 0 : 1) +// Avoid applying gamma correction on colors beyond the 0-1 range, it makes them go crazy. +#define GAMMA_CORRECT_SDR_RANGE_ONLY 1 + +// Determines what kind of color space/gamut/gamma the merged/mixed LUT is in. +// 0) sRGB gamma mapping (Vanilla): it makes any intermediary sampled value (that doesn't exactly fall in the center of LUT texel) affected by gamma, and that's not good. +// 1) Linear mapping: Makes LUTs sampling work in linear space, which is mathematically correct. This possibly shifts colors a lot, but it's correct, it's also necessary for HDR LUTs to work. +// 2) OKLAB mapping: this has a lot of advantages, like allowing the blackest LUT texel (coords 0 0 0) to also have a hue, so it can contribute to tinting the image even near black. +#define LUT_MAPPING_TYPE (FORCE_VANILLA_LOOK ? 0 : 1) +#define LUT_SIZE 16.f +#define LUT_SIZE_UINT (uint)LUT_SIZE +#define LUT_MAX_UINT (uint)LUT_SIZE - 1u +// If true, we do gamma correction directly in LUTs (in sRGB, out 2.2), if not, we do it after. +// Requires "SDR_USE_GAMMA_2_2". +// Cannot be set to false with "LUT_MAPPING_TYPE" == 2, as the point of doing LUTs mapping in OKLAB is for the blackest point to have no luminosity but still have a hue +// to help out with tinting the dakest 1/16 part of the image, thus if we convert back from OKLAB to Rec.709 to OKLAB, we'd lose the hue on black, due to having no luminance. +#define GAMMA_CORRECTION_IN_LUTS 1 +#define FORCE_SDR_LUTS 0 + +// Brings the range roughly from 80 nits to 203 nits (~2.5) +#define HDR_REFERENCE_PAPER_WHITE_MUTLIPLIER (ReferenceWhiteNits_BT2408 / WhiteNits_sRGB) + +// Custom push constants uploaded by the HDR DLL plugin code. Do note that register space comes at a premium when adding members. Bit/byte packing is advised. +// Bools are set as uint to avoid padding inconsistencies between c++ and hlsl. +struct StructHdrDllPluginConstants +{ + int DisplayMode; // -1 SDR on scRGB HDR, 0 SDR (Rec.709 with 2.2 gamma, not sRGB), 1 HDR10 PQ BT.2020, 2 scRGB HDR + float HDRPeakBrightnessNits; // Set equal to the max nits your display can output + float HDRGamePaperWhiteNits; // 203 is the reference value (ReferenceWhiteNits_BT2408) + float HDRUIPaperWhiteNits; // 203 is the reference value (ReferenceWhiteNits_BT2408) + float HDRExtendGamut; // 0-1. 0 is neutral + float HDRSaturation; // 0-2. 1 is neutral + float HDRSecondaryContrast; // 0-2. 1 is neutral + float LUTCorrectionStrength; // 1 is full strength + float ColorGradingStrength; // 1 is full strength + float GammaCorrection; // Application percentage of "SDR_USE_GAMMA_2_2" correction from LUTs. 0 to 1. 1 is "neutral" + float SDRSecondaryBrightness; // 0-2. Only meant for SDR. 1 is neutral + uint FilmGrainType; // 1 is default + float FilmGrainCap; // 24 is default + uint PostSharpen; // true is default + uint IsAtEndOfFrame; + uint RuntimeMS; + float DevSetting01; // 0-1 variable for development. Default 0 + float DevSetting02; // 0-1 variable for development. Default 0 + float DevSetting03; // 0-1 variable for development. Default 0 + float DevSetting04; // 0-1 variable for development. Default 0.5 + float DevSetting05; // 0-1 variable for development. Default 0.5 +}; + +#define HDR_PLUGIN_CONSTANTS_SIZE "19" + +ConstantBuffer HdrDllPluginConstants : register(b3, space0); diff --git a/shaders/structs.hlsl b/shaders/structs.hlsl new file mode 100644 index 00000000..6be1610b --- /dev/null +++ b/shaders/structs.hlsl @@ -0,0 +1,248 @@ +#pragma once + +//HDRComposite start +struct ResolutionBlock +{ + float2 f2_0; + float2 f2_1; + float2 f2_2; + float2 f2_3; + int4 i4_0; + float2 f2_4; + float2 f2_5; + float2 f2_6; + float2 f2_7; + float2 f2_8; + int2 i2_0; + int4 i4_1; + float f_0; + int i_0; + int i_1; + int i_2; +}; + +struct CameraBlock +{ + float3 f3_0; + int i_1; + float4x4 f4x4_0; + float4x4 f4x4_1; + float4x4 f4x4_2; + float4x4 f4x4_3; + float4x4 f4x4_4; + float4x4 f4x4_5; + float3 f3_1; + int i_0; + float4x4 f4x4_6; + float4x4 f4x4_7; + float4x4 f4x4_8; + float4 f4_0; + float4 f4_1; + float4 f4_2; + float4 f4_3; + float2 f2_0; + float f_0; + float f_1; +}; + +struct CameraBlockArray +{ + CameraBlock cb0; + CameraBlock cb1; + CameraBlock cb2; + ResolutionBlock rb0; + ResolutionBlock rb1; + ResolutionBlock rb2; + ResolutionBlock rb3; + ResolutionBlock rb4; +}; + +struct SPerSceneConstants +{ + CameraBlockArray cba; +// WindData; +// CameraExposureData; +// GlobalLightData; +// GlobalShadowData; +// ReflectionProbeDescData; +// ReflectionProbeExposureData; +// SIndirectLightingData; +// ProbeRenderData; +// PlanetConstantsData; +// float pcs0; +// int pcs1; +// int pcs2; +// float pcs3; +// TiledBinning_idTech7FrameData; +// float pcs4; +// float pcs5; +// float pcs6; +// float pcs7; +// float pcs8; +// float pcs9; +// float pcs10; +// float pcs11; +// float pcs12; +// int pcs13; +// int pcs14; +// int pcs15; +// HairConstantData; +// FogParams; +// VolumetricLightingApplyParameters; +// PrecomputeTransmittanceParameters; +// HeightfieldData; +// MomentBasedOITSettings; +// TiledLightingDebug; +// GPUDebugGeometrySettings; +// TonemappingParams; +// EffectsAlphaThresholdParams; +}; + +struct TonemappingParams +{ + float AcesParam0; + float AcesParam1; + float HableParam0; + float HableParam1; + float HableParam2; + float HableParam3; + float HableParam4; + int param7; //unused +}; + +struct PushConstantWrapper_HDRComposite +{ + uint HdrCmpDatIndex; //index for HDRCompositeData + uint Tmo; //tone mapping operator + float BloomMultiplier; +}; + +struct FrameDebug { int2 u1; int2 u2; int2 u3; int u4; int u5; float u6; int u7; int u8; int u9; int u10; int u11; int u12; int u13; }; +struct FrameData { int u1; int u2; float2 u3; float u4; float u5; float u6; float Gamma; FrameDebug u8; float4 u9; float u10; float u11; int u12; int u13; }; + +struct HDRCompositeData +{ + float4 HighlightsColorFilter; + float4 ColorFilter; + float HableSaturation; + float BrightnessMultiplier; + float ContrastIntensity; + int i_0; //unused +}; + +//HDRComposite shader structs start +struct Hable_params +{ + float y0; + float y1; +}; + +struct Hable_dstParams +{ + float W; +}; + +struct Hable_toeSegment +{ + float lnA; + float B; +}; + +struct Hable_midSegment +{ + float offsetX; + float lnA; +}; + +struct Hable_shoulderSegment +{ + float offsetX; + float offsetY; + float lnA; + float B; +}; + +struct HableParams +{ + Hable_params params; + Hable_dstParams dstParams; + Hable_toeSegment toeSegment; + Hable_midSegment midSegment; + Hable_shoulderSegment shoulderSegment; + float invScale; + float toeEnd; + float shoulderStart; +}; + +struct HableItmParams +{ + float offsetX; + float offsetY; + float scaleX; + float scaleY; + float lnA; + float B; +}; + +struct HableEvalParams +{ + float params_x0; + float params_x1; + float params_overshootX; + float params_overshootY; + float toeSegment_lnA_optimised; + float toeSegment_optimised; + float toeSegment_B; + float midSegment_offsetX; + float midSegment_lnA_optimised; + float shoulderSegment_lnA; + float shoulderSegment_B_optimised; +}; + +struct SDRTonemapByLuminancePP +{ + float minHighlightsColorIn; + float minHighlightsColorOut; + bool needsInverseTonemap; +}; + +//HDRComposite shader structs end +//HDRComposite end + +//ColorGradingMerge start +struct PushConstantWrapper_ColorGradingMerge +{ + float LUT1Percentage; + float LUT2Percentage; + float LUT3Percentage; + float LUT4Percentage; + float neutralLUTPercentage; +}; +//ColorGradingMerge end + +//ContrastAdaptiveSharpening start + +struct CASConst0 +{ + float rcpScalingFactorX; + float rcpScalingFactorY; + float otherScalingFactorX; //0.5 * inputSizeInPixelsX * (1.0 / outputSizeInPixelsX) - 0.5 + float otherScalingFactorY; //0.5 * inputSizeInPixelsY * (1.0 / outputSizeInPixelsY) - 0.5 +}; + +struct CASConst1 +{ + float sharp; + uint sharpAsHalf; //needs to be unpacked + float rcpScalingFactorXTimes8; + int unused; +}; + +struct ContrastAdaptiveSharpeningData +{ + CASConst0 upscalingConst0; + CASConst1 upscalingConst1; + uint4 rectLimits0; + uint4 rectLimits1; +}; +//ContrastAdaptiveSharpening end diff --git a/update-submodule.bat b/update-submodule.bat new file mode 100644 index 00000000..f82cf7a5 --- /dev/null +++ b/update-submodule.bat @@ -0,0 +1,2 @@ +git submodule update --init --recursive -f +git submodule update --remote -f \ No newline at end of file