diff options
| author | SulfurNitride <SulfurNitride@users.noreply.github.com> | 2026-04-12 17:54:45 -0500 |
|---|---|---|
| committer | SulfurNitride <SulfurNitride@users.noreply.github.com> | 2026-04-12 17:54:45 -0500 |
| commit | a0355c9b897281d0bfea48bec9d490724ecabd96 (patch) | |
| tree | 42c56ea4f4829a6115f688956858ada3e59fd9ef /libs | |
| parent | fa43a71f9d05b3673d42296a80decb2228d68f83 (diff) | |
Add NIF previewer plugin with Linux-specific fixes
Vendored from github.com/Parapets/mo2-preview_nif and adapted for Linux:
- BSA texture resolution via MO2 virtual tree with case-insensitive
fallback walk (Linux FS is case-sensitive; NIFs reference textures
with arbitrary case against files on disk)
- Process-wide cached BSA candidate list, keyed by profile path,
priority-sorted, filtering disabled mods
- Path backslash normalization before loose-file lookup
- Polygon offset on SLSF1_Decal-flagged shapes to break z-ties with
coincident base meshes (road decals, moss overlays)
- Opaque framebuffer via glColorMask alpha lock so alpha-blended shapes
can't bleed the dialog background through the preview area
- QMouseEvent::globalPosition().toPoint() for Qt6 compatibility
Preview dialog behavior (organizercore.cpp):
- Switch previewFile and previewFileWithAlternatives from stack-allocated
exec() to heap + ApplicationModal + show() + WA_DeleteOnClose.
- Parent passed as nullptr so preview lifetime is decoupled from the
stack-allocated ModInfoDialog that spawns it. Nested exec() inside
the enclosing dialog's exec() was softlocking on close.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'libs')
33 files changed, 4198 insertions, 0 deletions
diff --git a/libs/preview_nif/.github/workflows/build.yml b/libs/preview_nif/.github/workflows/build.yml new file mode 100644 index 0000000..4bb1166 --- /dev/null +++ b/libs/preview_nif/.github/workflows/build.yml @@ -0,0 +1,28 @@ +name: Build NIF Preview Plugin + +on: + push: + branches: main + pull_request: + types: [opened, synchronize, reopened] + +jobs: + build: + runs-on: windows-2022 + steps: + - name: Build NIF Preview Plugin + uses: ModOrganizer2/build-with-mob-action@master + with: + mo2-third-parties: fmt libbsarch + mo2-dependencies: cmake_common uibase + - name: Upload Build + uses: actions/upload-artifact@v3 + with: + name: preview_nif + path: | + ./build/modorganizer_super/${{ github.event.repository.name }}/vsbuild/src/RelWithDebInfo/preview_nif.dll + - uses: actions/upload-artifact@v3 + with: + name: preview_nif + path: | + ./build/modorganizer_super/${{ github.event.repository.name }}/**/data/shaders/* diff --git a/libs/preview_nif/.gitmodules b/libs/preview_nif/.gitmodules new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/libs/preview_nif/.gitmodules diff --git a/libs/preview_nif/CMakeLists.txt b/libs/preview_nif/CMakeLists.txt new file mode 100644 index 0000000..7db3db2 --- /dev/null +++ b/libs/preview_nif/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.22) + +project(preview_nif CXX) + +include(FetchContent) + +# gli (texture loader — header-only, needs glm) +FetchContent_Declare( + gli + GIT_REPOSITORY https://github.com/g-truc/gli.git + GIT_TAG master +) +set(GLI_TEST_ENABLE OFF CACHE BOOL "Build gli unit tests") + +# nifly (NIF parser) +FetchContent_Declare( + nifly + GIT_REPOSITORY https://github.com/ousnius/nifly.git + GIT_TAG main +) + +FetchContent_MakeAvailable(gli nifly) + +# mo2_install_target compatibility shim (upstream uses mo2_install_target; +# Fluorine defines mo2_install_plugin). +if(NOT COMMAND mo2_install_target AND COMMAND mo2_install_plugin) + function(mo2_install_target target) + mo2_install_plugin(${target}) + endfunction() +endif() + +add_subdirectory(src) + +target_link_libraries(preview_nif PRIVATE nifly gli) diff --git a/libs/preview_nif/CMakePresets.json b/libs/preview_nif/CMakePresets.json new file mode 100644 index 0000000..d00c664 --- /dev/null +++ b/libs/preview_nif/CMakePresets.json @@ -0,0 +1,72 @@ +{ + "version": 3, + "configurePresets": [ + { + "name": "windows-2022", + "generator": "Visual Studio 17 2022", + "binaryDir": "${sourceDir}/vsbuild", + "cacheVariables": { + "CMAKE_BUILD_TYPE": { + "type": "STRING", + "value": "Release" + }, + "DEPENDENCIES_DIR": { + "type": "PATH", + "value": "${sourceDir}/../.." + }, + "BOOST_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../boost_1_83_0" + }, + "BOOST_LIBRARYDIR": { + "type": "PATH", + "value": "${sourceDir}/../../boost_1_83_0/lib64-msvc-14.3/lib" + }, + "FMT_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../fmt-8.1.1" + }, + "SPDLOG_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../spdlog-v1.10.0" + }, + "LOOT_PATH": { + "type": "PATH", + "value": "${sourceDir}/../../libloot-0.22.1-win64" + }, + "LZ4_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../lz4-v1.9.4" + }, + "QT_ROOT": { + "type": "PATH", + "value": "C:/Qt/6.5.3/msvc2019_64" + }, + "ZLIB_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../zlib-v1.3" + }, + "PYTHON_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../python-3.11.5" + }, + "SEVENZ_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../7zip-23.01" + }, + "LIBBSARCH_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../libbsarch-0.0.9-release-x64" + }, + "BOOST_DI_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../di" + }, + "GTEST_ROOT": { + "type": "PATH", + "value": "${sourceDir}/../../googletest" + } + } + } + ] +}
\ No newline at end of file diff --git a/libs/preview_nif/LICENSE b/libs/preview_nif/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/libs/preview_nif/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/libs/preview_nif/README.md b/libs/preview_nif/README.md new file mode 100644 index 0000000..126825c --- /dev/null +++ b/libs/preview_nif/README.md @@ -0,0 +1,2 @@ +# modorganizer-preview_nif +NIF preview plugin for Mod Organizer diff --git a/libs/preview_nif/data/shaders/NIFSKOPE LICENSE.md b/libs/preview_nif/data/shaders/NIFSKOPE LICENSE.md new file mode 100644 index 0000000..d038fbe --- /dev/null +++ b/libs/preview_nif/data/shaders/NIFSKOPE LICENSE.md @@ -0,0 +1,27 @@ +NIFSKOPE LICENSE + +Copyright (c) 2005-2014, NIF File Format Library and Tools. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the NIF File Format Library and Tools project may not be + used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/preview_nif/data/shaders/default.vert b/libs/preview_nif/data/shaders/default.vert new file mode 100644 index 0000000..90cccd3 --- /dev/null +++ b/libs/preview_nif/data/shaders/default.vert @@ -0,0 +1,50 @@ +#version 120 + +uniform mat4 modelViewMatrix; +uniform mat4 mvpMatrix; +uniform mat3 normalMatrix; +uniform vec3 lightDirection; +uniform vec4 ambientColor; +uniform vec4 diffuseColor; + +attribute vec3 position; +attribute vec3 normal; +attribute vec3 tangent; +attribute vec3 bitangent; +attribute vec2 texCoord; +attribute vec4 color; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec3 N; +varying vec3 t; +varying vec3 b; +varying vec3 v; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + +void main( void ) +{ + gl_Position = mvpMatrix * vec4(position, 1.0); + TexCoord = texCoord; + + N = normalize(normalMatrix * normal); + t = normalize(normalMatrix * tangent); + b = normalize(normalMatrix * bitangent); + v = vec3(modelViewMatrix * vec4(position, 1.0)); + + mat3 tbnMatrix = mat3(b.x, t.x, N.x, + b.y, t.y, N.y, + b.z, t.z, N.z); + + ViewDir = tbnMatrix * -v; + LightDir = tbnMatrix * lightDirection; + + A = ambientColor; + C = color; + D = diffuseColor; +} diff --git a/libs/preview_nif/data/shaders/fo4_default.frag b/libs/preview_nif/data/shaders/fo4_default.frag new file mode 100644 index 0000000..2b1d6b8 --- /dev/null +++ b/libs/preview_nif/data/shaders/fo4_default.frag @@ -0,0 +1,341 @@ +#version 120 +#extension GL_ARB_shader_texture_lod : require + +uniform sampler2D BaseMap; +uniform sampler2D NormalMap; +uniform sampler2D GlowMap; +uniform sampler2D BacklightMap; +uniform sampler2D SpecularMap; +uniform sampler2D GreyscaleMap; +uniform sampler2D EnvironmentMap; +uniform samplerCube CubeMap; + +uniform vec3 specColor; +uniform float specStrength; +uniform float specGlossiness; // "Smoothness" in FO4; 0-1 +uniform float fresnelPower; + +uniform float paletteScale; + +uniform vec3 glowColor; +uniform float glowMult; + +uniform float alpha; + +uniform vec3 tintColor; + +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform bool hasEmit; +uniform bool hasGlowMap; +uniform bool hasSoftlight; +uniform bool hasBacklight; +uniform bool hasRimlight; +uniform bool hasTintColor; +uniform bool hasCubeMap; +uniform bool hasEnvMask; +uniform bool hasSpecularMap; +uniform bool greyscaleColor; +uniform bool doubleSided; + +uniform float subsurfaceRolloff; +uniform float rimPower; +uniform float backlightPower; + +uniform float envReflection; + +uniform mat4 modelViewMatrixInverse; +uniform mat4 worldMatrix; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + +varying vec3 N; +varying vec3 t; +varying vec3 b; + +#ifndef M_PI + #define M_PI 3.1415926535897932384626433832795 +#endif + +#define FLT_EPSILON 1.192092896e-07F // smallest such that 1.0 + FLT_EPSILON != 1.0 + +float OrenNayar( vec3 L, vec3 V, vec3 N, float roughness, float NdotL ) +{ + //float NdotL = dot(N, L); + float NdotV = dot(N, V); + float LdotV = dot(L, V); + + float rough2 = roughness * roughness; + + float A = 1.0 - 0.5 * (rough2 / (rough2 + 0.57)); + float B = 0.45 * (rough2 / (rough2 + 0.09)); + + float a = min( NdotV, NdotL ); + float b = max( NdotV, NdotL ); + b = (sign(b) == 0.0) ? FLT_EPSILON : sign(b) * max( 0.01, abs(b) ); // For fudging the smoothness of C + float C = sqrt( (1.0 - a * a) * (1.0 - b * b) ) / b; + + float gamma = LdotV - NdotL * NdotV; + float L1 = A + B * max( gamma, FLT_EPSILON ) * C; + + return L1 * max( NdotL, FLT_EPSILON ); +} + +float OrenNayarFull( vec3 L, vec3 V, vec3 N, float roughness, float NdotL ) +{ + //float NdotL = dot(N, L); + float NdotV = dot(N, V); + float LdotV = dot(L, V); + + float angleVN = acos(max(NdotV, FLT_EPSILON)); + float angleLN = acos(max(NdotL, FLT_EPSILON)); + + float alpha = max(angleVN, angleLN); + float beta = min(angleVN, angleLN); + float gamma = LdotV - NdotL * NdotV; + + float roughnessSquared = roughness * roughness; + float roughnessSquared9 = (roughnessSquared / (roughnessSquared + 0.09)); + + // C1, C2, and C3 + float C1 = 1.0 - 0.5 * (roughnessSquared / (roughnessSquared + 0.33)); + float C2 = 0.45 * roughnessSquared9; + + if( gamma >= 0.0 ) { + C2 *= sin(alpha); + } else { + C2 *= (sin(alpha) - pow((2.0 * beta) / M_PI, 3.0)); + } + + float powValue = (4.0 * alpha * beta) / (M_PI * M_PI); + float C3 = 0.125 * roughnessSquared9 * powValue * powValue; + + // Avoid asymptote at pi/2 + float asym = M_PI / 2.0; + float lim1 = asym + 0.01; + float lim2 = asym - 0.01; + + float ab2 = (alpha + beta) / 2.0; + + if ( beta >= asym && beta < lim1 ) + beta = lim1; + else if ( beta < asym && beta >= lim2 ) + beta = lim2; + + if ( ab2 >= asym && ab2 < lim1 ) + ab2 = lim1; + else if ( ab2 < asym && ab2 >= lim2 ) + ab2 = lim2; + + // Reflection + float A = gamma * C2 * tan(beta); + float B = (1.0 - abs(gamma)) * C3 * tan(ab2); + + float L1 = max(FLT_EPSILON, NdotL) * (C1 + A + B); + + // Interreflection + float twoBetaPi = 2.0 * beta / M_PI; + float L2 = 0.17 * max(FLT_EPSILON, NdotL) * (roughnessSquared / (roughnessSquared + 0.13)) * (1.0 - gamma * twoBetaPi * twoBetaPi); + + return L1 + L2; +} + +// Schlick's Fresnel approximation +float fresnelSchlick( float VdotH, float F0 ) +{ + float base = 1.0 - VdotH; + float exp = pow( base, fresnelPower ); + return clamp( exp + F0 * (1.0 - exp), 0.0, 1.0 ); +} + +// The Torrance-Sparrow visibility factor, G +float VisibDiv( float NdotL, float NdotV, float VdotH, float NdotH ) +{ + float denom = max( VdotH, FLT_EPSILON ); + float numL = min( NdotV, NdotL ); + float numR = 2.0 * NdotH; + if ( denom >= (numL * numR) ) { + numL = (numL == NdotV) ? 1.0 : (NdotL / NdotV); + return (numL * numR) / denom; + } + return 1.0 / NdotV; +} + +// this is a normalized Phong model used in the Torrance-Sparrow model +vec3 TorranceSparrow(float NdotL, float NdotH, float NdotV, float VdotH, vec3 color, float power, float F0) +{ + // D: Normalized phong model + float D = ((power + 2.0) / (2.0 * M_PI)) * pow( NdotH, power ); + + // G: Torrance-Sparrow visibility term divided by NdotV + float G_NdotV = VisibDiv( NdotL, NdotV, VdotH, NdotH ); + + // F: Schlick's approximation + float F = fresnelSchlick( VdotH, F0 ); + + // Torrance-Sparrow: + // (F * G * D) / (4 * NdotL * NdotV) + // Division by NdotV is done in VisibDiv() + // and division by NdotL is removed since + // outgoing radiance is determined by: + // BRDF * NdotL * L() + float spec = (F * G_NdotV * D) / 4.0; + + return color * spec * M_PI; +} + +vec3 tonemap(vec3 x) +{ + float _A = 0.15; + float _B = 0.50; + float _C = 0.10; + float _D = 0.20; + float _E = 0.02; + float _F = 0.30; + + return ((x*(_A*x+_C*_B)+_D*_E)/(x*(_A*x+_B)+_D*_F))-_E/_F; +} + +vec4 colorLookup( float x, float y ) { + + return texture2D( GreyscaleMap, vec2( clamp(x, 0.0, 1.0), clamp(y, 0.0, 1.0) ) ); +} + +void main( void ) +{ + vec2 offset = TexCoord * uvScale + uvOffset; + + vec4 baseMap = texture2D( BaseMap, offset ); + vec4 normalMap = texture2D( NormalMap, offset ); + vec4 specMap = texture2D( SpecularMap, offset ); + vec4 glowMap = texture2D( GlowMap, offset ); + + vec3 normal = normalize(normalMap.rgb * 2.0 - 1.0); + // Calculate missing blue channel + normal.b = sqrt(1.0 - dot(normal.rg, normal.rg)); + if ( !gl_FrontFacing && doubleSided ) { + normal *= -1.0; + } + // For _msn (Test with FSF1_Face) + //normal.z = sqrt( 1.0 - dot( normal.xy, normal.xy ) ); + + vec3 L = normalize(LightDir); + vec3 V = normalize(ViewDir); + vec3 R = reflect(-L, normal); + vec3 H = normalize( L + V ); + + float NdotL = dot(normal, L); + float NdotL0 = max( NdotL, FLT_EPSILON ); + float NdotH = max( dot(normal, H), FLT_EPSILON ); + float NdotV = max( dot(normal, V), FLT_EPSILON ); + float VdotH = max( dot(V, H), FLT_EPSILON ); + float NdotNegL = max( dot(normal, -L), FLT_EPSILON ); + + vec3 reflected = reflect( V, normal ); + vec3 reflectedVS = b * reflected.x + t * reflected.y + N * reflected.z; + vec3 reflectedWS = vec3( worldMatrix * (modelViewMatrixInverse * vec4( reflectedVS, 0.0 )) ); + + vec4 color; + vec3 albedo = baseMap.rgb * C.rgb; + vec3 diffuse = A.rgb + D.rgb * NdotL0; + if ( greyscaleColor ) { + vec4 luG = colorLookup( baseMap.g, paletteScale - (1 - C.r) ); + + albedo = luG.rgb; + } + + // Emissive + vec3 emissive = vec3(0.0); + if ( hasEmit ) { + emissive += glowColor * glowMult; + + if ( hasGlowMap ) { + emissive *= glowMap.rgb; + } + } + + // Specular + float g = 1.0; + float s = 1.0; + float smoothness = clamp( specGlossiness, 0.0, 1.0 ); + float specMask = 1.0; + vec3 spec = vec3(0.0); + if ( hasSpecularMap ) { + g = specMap.g; + s = specMap.r; + smoothness = g * smoothness; + float fSpecularPower = exp2( smoothness * 10 + 1 ); + specMask = s * specStrength; + + spec = TorranceSparrow( NdotL0, NdotH, NdotV, VdotH, vec3(specMask), fSpecularPower, 0.2 ) * NdotL0 * D.rgb * specColor; + } + + // Environment + vec4 cube = textureCubeLod( CubeMap, reflectedWS, 8.0 - smoothness * 8.0 ); + vec4 env = texture2D( EnvironmentMap, offset ); + if ( hasCubeMap ) { + cube.rgb *= envReflection * specStrength; + if ( hasEnvMask ) { + cube.rgb *= env.r; + } else { + cube.rgb *= s; + } + + spec += cube.rgb * diffuse; + } + + vec3 backlight = vec3(0.0); + if ( backlightPower > 0.0 ) { + backlight = albedo * NdotNegL * clamp( backlightPower, 0.0, 1.0 ); + + emissive += backlight * D.rgb; + } + + vec3 rim = vec3(0.0); + if ( hasRimlight ) { + rim = vec3(pow((1.0 - NdotV), rimPower)); + rim *= smoothstep( -0.2, 1.0, dot(-L, V) ); + + //emissive += rim * D.rgb * specMask; + } + + // Diffuse + float diff = OrenNayarFull( L, V, normal, 1.0 - smoothness, NdotL ); + diffuse = vec3(diff); + + vec3 soft = vec3(0.0); + float wrap = NdotL; + if ( hasSoftlight || subsurfaceRolloff > 0.0 ) { + wrap = (wrap + subsurfaceRolloff) / (1.0 + subsurfaceRolloff); + soft = albedo * max( 0.0, wrap ) * smoothstep( 1.0, 0.0, sqrt(diff) ); + + diffuse += soft; + } + + if ( hasTintColor ) { + albedo *= tintColor; + } + + // Diffuse + color.rgb = diffuse * albedo * D.rgb; + // Ambient + color.rgb += A.rgb * albedo; + // Specular + color.rgb += spec; + color.rgb += A.rgb * specMask * fresnelSchlick( VdotH, 0.2 ) * (1.0 - NdotV) * D.rgb; + // Emissive + color.rgb += emissive; + + color.rgb = tonemap( color.rgb ) / tonemap( vec3(1.0) ); + color.a = C.a * baseMap.a; + + gl_FragColor = color; + gl_FragColor.a *= alpha; +} diff --git a/libs/preview_nif/data/shaders/fo4_effectshader.frag b/libs/preview_nif/data/shaders/fo4_effectshader.frag new file mode 100644 index 0000000..31b241f --- /dev/null +++ b/libs/preview_nif/data/shaders/fo4_effectshader.frag @@ -0,0 +1,148 @@ +#version 120 + +uniform sampler2D BaseMap; +uniform sampler2D GreyscaleMap; +uniform samplerCube CubeMap; +uniform sampler2D NormalMap; +uniform sampler2D SpecularMap; + +uniform bool doubleSided; + +uniform bool hasSourceTexture; +uniform bool hasGreyscaleMap; +uniform bool hasCubeMap; +uniform bool hasNormalMap; +uniform bool hasEnvMask; + +uniform bool greyscaleAlpha; +uniform bool greyscaleColor; + +uniform bool useFalloff; +uniform bool hasRGBFalloff; + +uniform bool hasWeaponBlood; + +uniform vec4 glowColor; +uniform float glowMult; + +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform vec4 falloffParams; +uniform float falloffDepth; + +uniform float lightingInfluence; +uniform float envReflection; + +uniform mat4 modelViewMatrixInverse; +uniform mat4 worldMatrix; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + +varying vec3 N; +varying vec3 t; +varying vec3 b; +varying vec3 v; + +vec4 colorLookup( float x, float y ) { + + return texture2D( GreyscaleMap, vec2( clamp(x, 0.0, 1.0), clamp(y, 0.0, 1.0)) ); +} + +void main( void ) +{ + vec2 offset = TexCoord * uvScale + uvOffset; + + vec4 baseMap = texture2D( BaseMap, offset ); + vec4 normalMap = texture2D( NormalMap, offset ); + vec4 specMap = texture2D( SpecularMap, offset ); + + vec3 normal = normalize(normalMap.rgb * 2.0 - 1.0); + // Calculate missing blue channel + normal.b = sqrt(1.0 - dot(normal.rg, normal.rg)); + if ( !gl_FrontFacing && doubleSided ) { + normal *= -1.0; + } + + vec3 L = normalize(LightDir); + vec3 V = normalize(ViewDir); + vec3 R = reflect(-L, normal); + vec3 H = normalize( L + V ); + + float NdotL = max( dot(normal, L), 0.000001 ); + float NdotH = max( dot(normal, H), 0.000001 ); + float NdotV = max( dot(normal, V), 0.000001 ); + float LdotH = max( dot(L, H), 0.000001 ); + float NdotNegL = max( dot(normal, -L), 0.000001 ); + + vec3 reflected = reflect( V, normal ); + vec3 reflectedVS = b * reflected.x + t * reflected.y + N * reflected.z; + vec3 reflectedWS = vec3( worldMatrix * (modelViewMatrixInverse * vec4( reflectedVS, 0.0 )) ); + + if ( greyscaleAlpha ) + baseMap.a = 1.0; + + vec4 baseColor = glowColor; + if ( !greyscaleColor ) + baseColor.rgb *= glowMult; + + // Falloff + float falloff = 1.0; + if ( useFalloff || hasRGBFalloff ) { + falloff = smoothstep( falloffParams.x, falloffParams.y, abs(dot(normal, V)) ); + falloff = mix( max(falloffParams.z, 0.0), min(falloffParams.w, 1.0), falloff ); + + if ( useFalloff ) + baseMap.a *= falloff; + + if ( hasRGBFalloff ) + baseMap.rgb *= falloff; + } + + float alphaMult = baseColor.a * baseColor.a; + + vec4 color; + color.rgb = baseMap.rgb * C.rgb * baseColor.rgb; + color.a = alphaMult * C.a * baseMap.a; + + if ( greyscaleColor ) { + vec4 luG = colorLookup( texture2D( BaseMap, offset ).g, baseColor.r * C.r * falloff ); + + color.rgb = luG.rgb; + } + + if ( greyscaleAlpha ) { + vec4 luA = colorLookup( texture2D( BaseMap, offset ).a, color.a ); + + color.a = luA.a; + } + + vec3 diffuse = A.rgb + (D.rgb * NdotL); + color.rgb = mix( color.rgb, color.rgb * D.rgb, lightingInfluence ); + + // Specular + float g = 1.0; + float s = 1.0; + if ( hasEnvMask ) { + g = specMap.r; + s = specMap.g; + } + + // Environment + vec4 cube = textureCube( CubeMap, reflectedWS ); + if ( hasCubeMap ) { + cube.rgb *= envReflection * s; + cube.rgb = mix( cube.rgb, cube.rgb * D.rgb, lightingInfluence ); + + color.rgb += cube.rgb * falloff; + } + + gl_FragColor.rgb = color.rgb; + gl_FragColor.a = color.a; +} diff --git a/libs/preview_nif/data/shaders/sk_default.frag b/libs/preview_nif/data/shaders/sk_default.frag new file mode 100644 index 0000000..7cd0dcf --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_default.frag @@ -0,0 +1,180 @@ +#version 120 + +uniform sampler2D BaseMap; +uniform sampler2D NormalMap; +uniform sampler2D GlowMap; +uniform sampler2D HeightMap; +uniform sampler2D LightMask; +uniform sampler2D BacklightMap; +uniform sampler2D EnvironmentMap; +uniform samplerCube CubeMap; + +uniform vec3 specColor; +uniform float specStrength; +uniform float specGlossiness; + +uniform bool hasGlowMap; +uniform vec3 glowColor; +uniform float glowMult; + +uniform float alpha; + +uniform vec3 tintColor; + +uniform bool hasHeightMap; +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform bool hasEmit; +uniform bool hasSoftlight; +uniform bool hasBacklight; +uniform bool hasRimlight; +uniform bool hasTintColor; +uniform bool hasCubeMap; +uniform bool hasEnvMask; + +uniform float softlight; +uniform float rimPower; + +uniform float envReflection; + +uniform mat4 modelViewMatrixInverse; +uniform mat4 worldMatrix; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + +varying vec3 N; +varying vec3 t; +varying vec3 b; + +vec3 tonemap(vec3 x) +{ + float _A = 0.15; + float _B = 0.50; + float _C = 0.10; + float _D = 0.20; + float _E = 0.02; + float _F = 0.30; + + return ((x*(_A*x+_C*_B)+_D*_E)/(x*(_A*x+_B)+_D*_F))-_E/_F; +} + +vec3 toGrayscale(vec3 color) +{ + return vec3(dot(vec3(0.3, 0.59, 0.11), color)); +} + +void main( void ) +{ + vec2 offset = TexCoord * uvScale + uvOffset; + + vec3 E = normalize(ViewDir); + + if ( hasHeightMap ) { + float height = texture2D( HeightMap, offset ).r; + offset += E.xy * (height * 0.08 - 0.04); + } + + vec4 baseMap = texture2D( BaseMap, offset ); + vec4 normalMap = texture2D( NormalMap, offset ); + vec4 glowMap = texture2D( GlowMap, offset ); + + vec3 normal = normalize(normalMap.rgb * 2.0 - 1.0); + + vec3 L = normalize(LightDir); + vec3 R = reflect(-L, normal); + vec3 H = normalize( L + E ); + + float NdotL = max( dot(normal, L), 0.0 ); + float NdotH = max( dot(normal, H), 0.0 ); + float EdotN = max( dot(normal, E), 0.0 ); + float NdotNegL = max( dot(normal, -L), 0.0 ); + + vec3 reflected = reflect( -E, normal ); + vec3 reflectedVS = b * reflected.x + t * reflected.y + N * reflected.z; + vec3 reflectedWS = vec3( worldMatrix * (modelViewMatrixInverse * vec4( reflectedVS, 0.0 )) ); + + + vec4 color; + vec3 albedo = baseMap.rgb * C.rgb; + vec3 diffuse = A.rgb + (D.rgb * NdotL); + + + // Environment + if ( hasCubeMap ) { + vec4 cube = textureCube( CubeMap, reflectedWS ); + cube.rgb *= envReflection; + + if ( hasEnvMask ) { + vec4 env = texture2D( EnvironmentMap, offset ); + cube.rgb *= env.r; + } else { + cube.rgb *= normalMap.a; + } + + + albedo += cube.rgb; + } + + // Emissive & Glow + vec3 emissive = vec3(0.0); + if ( hasEmit ) { + emissive += glowColor * glowMult; + + if ( hasGlowMap ) { + emissive *= glowMap.rgb; + } + } + + // Specular + vec3 spec = clamp( specColor * specStrength * normalMap.a * pow(NdotH, specGlossiness), 0.0, 1.0 ); + spec *= D.rgb; + + vec3 backlight = vec3(0.0); + if ( hasBacklight ) { + backlight = texture2D( BacklightMap, offset ).rgb; + backlight *= NdotNegL; + + emissive += backlight * D.rgb; + } + + vec4 mask = vec4(0.0); + if ( hasRimlight || hasSoftlight ) { + mask = texture2D( LightMask, offset ); + } + + vec3 rim = vec3(0.0); + if ( hasRimlight ) { + rim = mask.rgb * pow(vec3((1.0 - EdotN)), vec3(rimPower)); + rim *= smoothstep( -0.2, 1.0, dot(-L, E) ); + + emissive += rim * D.rgb; + } + + vec3 soft = vec3(0.0); + if ( hasSoftlight ) { + float wrap = (dot(normal, L) + softlight) / (1.0 + softlight); + + soft = max( wrap, 0.0 ) * mask.rgb * smoothstep( 1.0, 0.0, NdotL ); + soft *= sqrt( clamp( softlight, 0.0, 1.0 ) ); + + emissive += soft * D.rgb; + } + + if ( hasTintColor ) { + albedo *= tintColor; + } + + color.rgb = albedo * (diffuse + emissive) + spec; + color.rgb = tonemap( color.rgb ) / tonemap( vec3(1.0) ); + color.a = C.a * baseMap.a; + + gl_FragColor = color; + gl_FragColor.a *= alpha; +} diff --git a/libs/preview_nif/data/shaders/sk_effectshader.frag b/libs/preview_nif/data/shaders/sk_effectshader.frag new file mode 100644 index 0000000..3a22388 --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_effectshader.frag @@ -0,0 +1,101 @@ +#version 120 + +uniform sampler2D BaseMap; +uniform sampler2D GreyscaleMap; + +uniform bool doubleSided; + +uniform bool hasSourceTexture; +uniform bool hasGreyscaleMap; +uniform bool greyscaleAlpha; +uniform bool greyscaleColor; + +uniform bool useFalloff; +uniform bool vertexColors; +uniform bool vertexAlpha; + +uniform bool hasWeaponBlood; + +uniform vec4 glowColor; +uniform float glowMult; + +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform vec4 falloffParams; +uniform float falloffDepth; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 C; + +varying vec3 N; +varying vec3 v; + +vec4 colorLookup( float x, float y ) { + + return texture2D( GreyscaleMap, vec2( clamp(x, 0.0, 1.0), clamp(y, 0.0, 1.0)) ); +} + +void main( void ) +{ + vec4 baseMap = texture2D( BaseMap, TexCoord.st * uvScale + uvOffset ); + + vec4 color; + + vec3 normal = N; + + // Reconstructed normal + //normal = normalize(cross(dFdy(v.xyz), dFdx(v.xyz))); + + //if ( !doubleSided && !gl_FrontFacing ) { return; } + + vec3 E = normalize(ViewDir); + + float tmp2 = falloffDepth; // Unused right now + + // Falloff + float falloff = 1.0; + if ( useFalloff ) { + float startO = min(falloffParams.z, 1.0); + float stopO = max(falloffParams.w, 0.0); + + // TODO: When X and Y are both 0.0 or both 1.0 the effect is reversed. + falloff = smoothstep( falloffParams.y, falloffParams.x, abs(E.b)); + + falloff = mix( max(falloffParams.w, 0.0), min(falloffParams.z, 1.0), falloff ); + } + + float alphaMult = glowColor.a * glowColor.a; + + color.rgb = baseMap.rgb; + color.a = baseMap.a; + + if ( hasWeaponBlood ) { + color.rgb = vec3( 1.0, 0.0, 0.0 ) * baseMap.r; + color.a = baseMap.a * baseMap.g; + } + + color.rgb *= C.rgb * glowColor.rgb; + color.a *= C.a * falloff * alphaMult; + + if ( greyscaleColor ) { + // Only Red emissive channel is used + float emRGB = glowColor.r; + + vec4 luG = colorLookup( baseMap.g, C.g * falloff * emRGB ); + + color.rgb = luG.rgb; + } + + if ( greyscaleAlpha ) { + vec4 luA = colorLookup( baseMap.a, C.a * falloff * alphaMult ); + + color.a = luA.a; + } + + gl_FragColor.rgb = color.rgb * glowMult; + gl_FragColor.a = color.a; +} diff --git a/libs/preview_nif/data/shaders/sk_effectshader.vert b/libs/preview_nif/data/shaders/sk_effectshader.vert new file mode 100644 index 0000000..3204cba --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_effectshader.vert @@ -0,0 +1,46 @@ +#version 120 + +uniform mat4 modelViewMatrix; +uniform mat4 mvpMatrix; +uniform mat3 normalMatrix; +uniform vec3 lightDirection; +uniform vec4 ambientColor; +uniform vec4 diffuseColor; + +attribute vec3 position; +attribute vec3 normal; +attribute vec3 tangent; +attribute vec3 bitangent; +attribute vec2 texCoord; +attribute vec4 color; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 C; + +varying vec3 N; +varying vec3 t; +varying vec3 b; +varying vec3 v; + +void main( void ) +{ + gl_Position = mvpMatrix * vec4(position, 1); + TexCoord = texCoord; + + N = normalize(normalMatrix * normal); + t = normalize(normalMatrix * tangent); + b = normalize(normalMatrix * bitangent); + v = vec3(modelViewMatrix * vec4(position, 1)); + + mat3 tbnMatrix = mat3(b.x, t.x, N.x, + b.y, t.y, N.y, + b.z, t.z, N.z); + + ViewDir = tbnMatrix * -v.xyz; + LightDir = tbnMatrix * lightDirection.xyz; + + C = color; +} diff --git a/libs/preview_nif/data/shaders/sk_msn.frag b/libs/preview_nif/data/shaders/sk_msn.frag new file mode 100644 index 0000000..3ebbf93 --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_msn.frag @@ -0,0 +1,194 @@ +#version 120 + +uniform sampler2D BaseMap; +uniform sampler2D NormalMap; +uniform sampler2D SpecularMap; +uniform sampler2D LightMask; +uniform sampler2D TintMask; +uniform sampler2D DetailMask; +uniform sampler2D BacklightMap; + +uniform vec3 specColor; +uniform float specStrength; +uniform float specGlossiness; + +uniform vec3 glowColor; +uniform float glowMult; + +uniform float alpha; + +uniform vec3 tintColor; + +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform bool hasEmit; +uniform bool hasSoftlight; +uniform bool hasBacklight; +uniform bool hasRimlight; +uniform bool hasSpecularMap; +uniform bool hasDetailMask; +uniform bool hasTintMask; +uniform bool hasTintColor; + +uniform float softlight; +uniform float rimPower; + +uniform mat4 viewMatrix; + +varying vec3 v; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + + +vec3 tonemap(vec3 x) +{ + float _A = 0.15; + float _B = 0.50; + float _C = 0.10; + float _D = 0.20; + float _E = 0.02; + float _F = 0.30; + + return ((x*(_A*x+_C*_B)+_D*_E)/(x*(_A*x+_B)+_D*_F))-_E/_F; +} + +vec3 toGrayscale(vec3 color) +{ + return vec3(dot(vec3(0.3, 0.59, 0.11), color)); +} + +float overlay( float base, float blend ) +{ + float result; + if ( base < 0.5 ) { + result = 2.0 * base * blend; + } else { + result = 1.0 - 2.0 * (1.0 - blend) * (1.0 - base); + } + return result; +} + +vec3 overlay( vec3 ba, vec3 bl ) +{ + return vec3( overlay(ba.r, bl.r), overlay(ba.g, bl.g), overlay( ba.b, bl.b ) ); +} + +void main( void ) +{ + vec2 offset = TexCoord.st * uvScale + uvOffset; + + vec4 baseMap = texture2D( BaseMap, offset ); + vec4 normalMap = texture2D( NormalMap, offset ); + + vec3 normal = normalMap.rgb * 2.0 - 1.0; + + // Convert model space to view space + // Swizzled G/B values! + normal = normalize( vec3( viewMatrix * vec4( normal.rbg, 0.0 ))); + + // Face Normals + //vec3 X = dFdx(v); + //vec3 Y = dFdy(v); + //vec3 constructedNormal = normalize(cross(X,Y)); + + + vec3 L = normalize(LightDir); + vec3 E = normalize(ViewDir); + vec3 R = reflect(-L, normal); + vec3 H = normalize( L + E ); + + float NdotL = max( dot(normal, L), 0.0 ); + float NdotH = max( dot(normal, H), 0.0 ); + float EdotN = max( dot(normal, E), 0.0 ); + float NdotNegL = max( dot(normal, -L), 0.0 ); + + + vec4 color; + vec3 albedo = baseMap.rgb * C.rgb; + vec3 diffuse = A.rgb + (D.rgb * NdotL); + + + // Emissive + vec3 emissive = vec3(0.0); + if ( hasEmit ) { + emissive += glowColor * glowMult; + } + + // Specular + + float s = texture2D( SpecularMap, offset ).r; + if ( !hasSpecularMap || hasBacklight ) { + s = normalMap.a; + } + + vec3 spec = clamp( specColor * specStrength * s * pow(NdotH, specGlossiness), 0.0, 1.0 ); + spec *= D.rgb; + + + vec3 backlight = vec3(0.0); + if ( hasBacklight ) { + backlight = texture2D( BacklightMap, offset ).rgb; + backlight *= NdotNegL; + + emissive += backlight * D.rgb; + } + + vec4 mask = vec4(0.0); + if ( hasRimlight || hasSoftlight ) { + mask = texture2D( LightMask, offset ); + } + + vec3 rim = vec3(0.0); + if ( hasRimlight ) { + rim = mask.rgb * pow(vec3((1.0 - EdotN)), vec3(rimPower)); + rim *= smoothstep( -0.2, 1.0, dot(-L, E) ); + + emissive += rim * D.rgb; + } + + vec3 soft = vec3(0.0); + if ( hasSoftlight ) { + float wrap = (dot(normal, L) + softlight) / (1.0 + softlight); + + soft = max( wrap, 0.0 ) * mask.rgb * smoothstep( 1.0, 0.0, NdotL ); + soft *= sqrt( clamp( softlight, 0.0, 1.0 ) ); + + emissive += soft * D.rgb; + } + + vec3 detail = vec3(0.0); + if ( hasDetailMask ) { + detail = texture2D( DetailMask, offset ).rgb; + + albedo = overlay( albedo, detail ); + } + + vec3 tint = vec3(0.0); + if ( hasTintMask ) { + tint = texture2D( TintMask, offset ).rgb; + + albedo = overlay( albedo, tint ); + } + + if ( hasDetailMask ) { + albedo += albedo; + } + + if ( hasTintColor ) { + albedo *= tintColor; + } + + color.rgb = albedo * (diffuse + emissive) + spec; + color.rgb = tonemap( color.rgb ) / tonemap( vec3(1.0) ); + color.a = C.a * baseMap.a; + + gl_FragColor = color; + gl_FragColor.a *= alpha; +} diff --git a/libs/preview_nif/data/shaders/sk_msn.vert b/libs/preview_nif/data/shaders/sk_msn.vert new file mode 100644 index 0000000..755605f --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_msn.vert @@ -0,0 +1,41 @@ +#version 120 + +uniform mat4 modelViewMatrix; +uniform mat4 mvpMatrix; +uniform mat3 normalMatrix; +uniform vec3 lightDirection; +uniform vec4 ambientColor; +uniform vec4 diffuseColor; + +attribute vec3 position; +attribute vec3 normal; +attribute vec3 tangent; +attribute vec3 bitangent; +attribute vec2 texCoord; +attribute vec4 color; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec3 v; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + + +void main( void ) +{ + gl_Position = mvpMatrix * vec4(position, 1); + TexCoord = texCoord; + + v = vec3(modelViewMatrix * vec4(position, 1)); + + ViewDir = -v.xyz; + LightDir = lightDirection; + + A = ambientColor; + C = color; + D = diffuseColor; +} diff --git a/libs/preview_nif/data/shaders/sk_multilayer.frag b/libs/preview_nif/data/shaders/sk_multilayer.frag new file mode 100644 index 0000000..fc4afdb --- /dev/null +++ b/libs/preview_nif/data/shaders/sk_multilayer.frag @@ -0,0 +1,216 @@ +#version 120 + +uniform sampler2D BaseMap; +uniform sampler2D NormalMap; +uniform sampler2D LightMask; +uniform sampler2D BacklightMap; +uniform sampler2D InnerMap; +uniform sampler2D EnvironmentMap; +uniform samplerCube CubeMap; + +uniform vec3 specColor; +uniform float specStrength; +uniform float specGlossiness; + +uniform vec3 glowColor; +uniform float glowMult; + +uniform float alpha; + +uniform vec2 uvScale; +uniform vec2 uvOffset; + +uniform bool hasEmit; +uniform bool hasSoftlight; +uniform bool hasBacklight; +uniform bool hasRimlight; +uniform bool hasCubeMap; +uniform bool hasEnvMask; + +uniform float softlight; +uniform float rimPower; + +uniform vec2 innerScale; +uniform float innerThickness; +uniform float outerRefraction; +uniform float outerReflection; + +uniform mat4 modelViewMatrixInverse; +uniform mat4 worldMatrix; + +varying vec2 TexCoord; +varying vec3 LightDir; +varying vec3 ViewDir; + +varying vec4 A; +varying vec4 C; +varying vec4 D; + +varying vec3 N; +varying vec3 t; +varying vec3 b; + + +vec3 tonemap(vec3 x) +{ + float _A = 0.15; + float _B = 0.50; + float _C = 0.10; + float _D = 0.20; + float _E = 0.02; + float _F = 0.30; + + return ((x*(_A*x+_C*_B)+_D*_E)/(x*(_A*x+_B)+_D*_F))-_E/_F; +} + +vec3 toGrayscale(vec3 color) +{ + return vec3(dot(vec3(0.3, 0.59, 0.11), color)); +} + +// Compute inner layer�s texture coordinate and transmission depth +// vTexCoord: Outer layer�s texture coordinate +// vInnerScale: Tiling of inner texture +// vViewTS: View vector in tangent space +// vNormalTS: Normal in tangent space (sampled normal map) +// fLayerThickness: Distance from outer layer to inner layer +vec3 ParallaxOffsetAndDepth( vec2 vTexCoord, vec2 vInnerScale, vec3 vViewTS, vec3 vNormalTS, float fLayerThickness ) +{ + // Tangent space reflection vector + vec3 vReflectionTS = reflect( -vViewTS, vNormalTS ); + // Tangent space transmission vector (reflect about surface plane) + vec3 vTransTS = vec3( vReflectionTS.xy, -vReflectionTS.z ); + + // Distance along transmission vector to intersect inner layer + float fTransDist = fLayerThickness / abs(vTransTS.z); + + // Texel size + // Bethesda's version does indeed seem to assume 1024, which is why they + // introduced the additional parameter. + vec2 vTexelSize = vec2( 1.0/(1024.0 * vInnerScale.x), 1.0/(1024.0 * vInnerScale.y) ); + + // Inner layer�s texture coordinate due to parallax + vec2 vOffset = vTexelSize * fTransDist * vTransTS.xy; + vec2 vOffsetTexCoord = vTexCoord + vOffset; + + // Return offset texture coordinate in xy and transmission dist in z + return vec3( vOffsetTexCoord, fTransDist ); +} + +void main( void ) +{ + vec2 offset = TexCoord * uvScale + uvOffset; + + vec4 baseMap = texture2D( BaseMap, offset ); + vec4 normalMap = texture2D( NormalMap, offset ); + + vec3 normal = normalize(normalMap.rgb * 2.0 - 1.0); + + // Sample the non-parallax offset alpha channel of the inner map + // Used to modulate the innerThickness + float innerMapAlpha = texture2D( InnerMap, offset ).a; + + + vec3 L = normalize(LightDir); + vec3 E = normalize(ViewDir); + vec3 R = reflect(-L, normal); + vec3 H = normalize( L + E ); + + float NdotL = max( dot(normal, L), 0.0 ); + float NdotH = max( dot(normal, H), 0.0 ); + float EdotN = max( dot(normal, E), 0.0 ); + float NdotNegL = max( dot(normal, -L), 0.0 ); + + + // Mix between the face normal and the normal map based on the refraction scale + vec3 mixedNormal = mix( vec3(0.0, 0.0, 1.0), normal, clamp( outerRefraction, 0.0, 1.0 ) ); + vec3 parallax = ParallaxOffsetAndDepth( offset, innerScale, E, mixedNormal, innerThickness * innerMapAlpha ); + + // Sample the inner map at the offset coords + vec4 innerMap = texture2D( InnerMap, parallax.xy * innerScale ); + + vec3 reflected = reflect( -E, normal ); + vec3 reflectedVS = b * reflected.x + t * reflected.y + N * reflected.z; + vec3 reflectedWS = vec3( worldMatrix * (modelViewMatrixInverse * vec4( reflectedVS, 0.0 )) ); + + + vec4 color; + vec3 albedo; + vec3 diffuse = A.rgb + (D.rgb * NdotL); + vec3 inner = innerMap.rgb * C.rgb; + vec3 outer = baseMap.rgb * C.rgb; + + + // Mix inner/outer layer based on fresnel + float outerMix = max( 1.0 - EdotN, baseMap.a ); + albedo = mix( inner, outer, outerMix ); + + + // Environment + if ( hasCubeMap ) { + vec4 cube = textureCube( CubeMap, reflectedWS ); + cube.rgb *= outerReflection; + + if ( hasEnvMask ) { + vec4 env = texture2D( EnvironmentMap, offset ); + cube.rgb *= env.r; + } else { + cube.rgb *= normalMap.a; + } + + albedo += cube.rgb; + } + + // Specular + vec3 spec = clamp( specColor * specStrength * normalMap.a * pow(NdotH, specGlossiness), 0.0, 1.0 ); + spec *= D.rgb; + + // Emissive + // Mixed with outer map + vec3 emissive = vec3(0.0); + if ( hasEmit ) { + emissive += glowColor * glowMult; + } + + // Backlight + // Mixed with inner and outer map + vec3 backlight = vec3(0.0); + if ( hasBacklight ) { + backlight = texture2D( BacklightMap, offset ).rgb; + backlight *= NdotNegL; + + emissive += backlight * D.rgb; + } + + // TODO: Test rim and soft light mixing with inner/outer layer + + vec4 mask = vec4(0.0); + if ( hasRimlight || hasSoftlight ) { + mask = texture2D( LightMask, offset ); + } + + vec3 rim = vec3(0.0); + if ( hasRimlight ) { + rim = mask.rgb * pow(vec3((1.0 - EdotN)), vec3(rimPower)); + rim *= smoothstep( -0.2, 1.0, dot(-L, E) ); + + emissive += rim * D.rgb; + } + + vec3 soft = vec3(0.0); + if ( hasSoftlight ) { + float wrap = (dot(normal, L) + softlight) / (1.0 + softlight); + + soft = max( wrap, 0.0 ) * mask.rgb * smoothstep( 1.0, 0.0, NdotL ); + soft *= sqrt( clamp( softlight, 0.0, 1.0 ) ); + + emissive += soft * D.rgb; + } + + color.rgb = albedo * (diffuse + emissive) + spec; + color.rgb = tonemap( color.rgb ) / tonemap( vec3(1.0) ); + color.a = C.a * baseMap.a; + + gl_FragColor = color; + gl_FragColor.a *= alpha; +} diff --git a/libs/preview_nif/plugindefinition.json b/libs/preview_nif/plugindefinition.json new file mode 100644 index 0000000..d0d25c2 --- /dev/null +++ b/libs/preview_nif/plugindefinition.json @@ -0,0 +1,42 @@ +{ + "Name": "Preview NIF", + "Author": "Parapets", + "Description": "Supports previewing NIF files", + "DocsUrl": "", + "GithubUrl": "https://github.com/Exit-9B/modorganizer-preview_nif", + "NexusUrl": "https://www.nexusmods.com/skyrimspecialedition/mods/69813", + "Versions": [ + { + "Version": "0.2.0b", + "Released": "2023-11-27", + "MinSupport": "2.5.0", + "MaxSupport": "2.5.0", + "MinWorking": "2.5.0", + "MaxWorking": "", + "DownloadUrl": "https://github.com/Exit-9B/modorganizer-preview_nif/releases/download/v0.2.0/preview_nif-0.2.0.7z", + "PluginPath": [ + "preview_nif.dll", + "data" + ], + "LocalePath": [], + "DataPath": [], + "ReleaseNotes": [] + }, + { + "Version": "0.1.8.1b", + "Released": "2022-06-24", + "MinSupport": "2.4.3", + "MaxSupport": "2.4.4", + "MinWorking": "2.4.3", + "MaxWorking": "2.4.5a3", + "DownloadUrl": "https://github.com/Exit-9B/modorganizer-preview_nif/releases/download/v0.1.8/preview_nif-0.1.8.1.7z", + "PluginPath": [ + "preview_nif.dll", + "data" + ], + "LocalePath": [], + "DataPath": [], + "ReleaseNotes": [] + } + ] +} diff --git a/libs/preview_nif/src/CMakeLists.txt b/libs/preview_nif/src/CMakeLists.txt new file mode 100644 index 0000000..28bb30f --- /dev/null +++ b/libs/preview_nif/src/CMakeLists.txt @@ -0,0 +1,36 @@ +cmake_minimum_required(VERSION 3.22) + +find_package(Qt6 CONFIG REQUIRED COMPONENTS Widgets OpenGL OpenGLWidgets) +find_package(fmt CONFIG REQUIRED) + +file(GLOB preview_nif_SOURCES CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/*.h +) + +add_library(preview_nif SHARED ${preview_nif_SOURCES}) + +mo2_configure_plugin(preview_nif NO_SOURCES WARNINGS OFF) + +target_include_directories(preview_nif PRIVATE + ${CMAKE_SOURCE_DIR}/libs/uibase/include/uibase/game_features + ${CMAKE_SOURCE_DIR}/libs/libbsarch/include/libbsarch +) + +target_link_libraries(preview_nif PRIVATE + mo2::uibase + libbsarch + Qt6::Widgets + Qt6::OpenGL + Qt6::OpenGLWidgets + fmt::fmt +) + +mo2_install_plugin(preview_nif) + +# Stage shader files next to the plugin under plugins/data/shaders/. +install( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../data/shaders + DESTINATION plugins/data + FILES_MATCHING PATTERN "*.vert" PATTERN "*.frag" +) diff --git a/libs/preview_nif/src/Camera.cpp b/libs/preview_nif/src/Camera.cpp new file mode 100644 index 0000000..0a9ce73 --- /dev/null +++ b/libs/preview_nif/src/Camera.cpp @@ -0,0 +1,50 @@ +#include "Camera.h" + +#include <cmath> + +void Camera::setDistance(float distance) +{ + m_Distance = qBound(MinDistance, distance, MaxDistance); + cameraMoved(); +} + +void Camera::setLookAt(QVector3D lookAt) +{ + m_LookAt = lookAt; + cameraMoved(); +} + +void Camera::pan(QVector3D distance) +{ + m_LookAt += distance; + cameraMoved(); +} + +void Camera::rotate(float yaw, float pitch) +{ + m_Yaw = repeat(m_Yaw + yaw, 0.0f, 360.0f); + m_Pitch = repeat(m_Pitch + pitch, 0.0f, 360.0f); + + cameraMoved(); +} + +void Camera::zoomDistance(float distance) +{ + m_Distance += distance; + m_Distance = qBound(MinDistance, m_Distance, MaxDistance); + + cameraMoved(); +} + +void Camera::zoomFactor(float factor) +{ + m_Distance *= factor; + m_Distance = qBound(MinDistance, m_Distance, MaxDistance); + + cameraMoved(); +} + +float Camera::repeat(float value, float min, float max) +{ + return fmod(fmod(value, max - min) + (max - min), max - min) + min; +} diff --git a/libs/preview_nif/src/Camera.h b/libs/preview_nif/src/Camera.h new file mode 100644 index 0000000..3d685ea --- /dev/null +++ b/libs/preview_nif/src/Camera.h @@ -0,0 +1,37 @@ +#pragma once + +#include <QObject> +#include <QVector3D> + +class Camera : public QObject +{ + Q_OBJECT + +public: + QVector3D lookAt() { return m_LookAt; } + float pitch() { return m_Pitch; } + float yaw() { return m_Yaw; } + float distance() { return m_Distance; } + + void setDistance(float distance); + void setLookAt(QVector3D lookAt); + + void pan(QVector3D delta); + void rotate(float yaw, float pitch); + void zoomDistance(float distance); + void zoomFactor(float factor); + +private: + inline static constexpr float MinDistance = 1.0f; + inline static constexpr float MaxDistance = 5000.0f; + + static float repeat(float value, float min, float max); + + QVector3D m_LookAt; + float m_Pitch = 0.0f; + float m_Yaw = 0.0f; + float m_Distance = 100.0f; + +signals: + void cameraMoved(); +}; diff --git a/libs/preview_nif/src/NifExtensions.h b/libs/preview_nif/src/NifExtensions.h new file mode 100644 index 0000000..cd529e5 --- /dev/null +++ b/libs/preview_nif/src/NifExtensions.h @@ -0,0 +1,236 @@ +#pragma once + +#include <QOpenGLFunctions> +#include <NifFile.hpp> +#include <cstdint> +#include <cstring> + +struct SLSF1 +{ + SLSF1() = delete; + + enum BSLightingShaderFlags1 : std::uint32_t + { + Specular = 1U << 0, + Skinned = 1U << 1, + TempRefraction = 1U << 2, + VertexAlpha = 1U << 3, + GreyscaleToPaletteColor = 1U << 4, + GreyscaleToPaletteAlpha = 1U << 5, + UseFalloff = 1U << 6, + EnvironmentMapping = 1U << 7, + ReceiveShadows = 1U << 8, + CastShadows = 1U << 9, + FacegenDetailMap = 1U << 10, + Parallax = 1U << 11, + ModelSpaceNormals = 1U << 12, + NonProjectiveShadows = 1U << 13, + Landscape = 1U << 14, + Refraction = 1U << 15, + FireRefraction = 1U << 16, + EyeEnvironmentMapping = 1U << 17, + HairSoftLighting = 1U << 18, + ScreendoorAlphaFade = 1U << 19, + LocalmapHideSecret = 1U << 20, + FaceGenRGBTint = 1U << 21, + OwnEmit = 1U << 22, + ProjectedUV = 1U << 23, + MultipleTextures = 1U << 24, + RemappableTextures = 1U << 25, + Decal = 1U << 26, + DynamicDecal = 1U << 27, + ParallaxOcclusion = 1U << 28, + ExternalEmittance = 1U << 29, + SoftEffect = 1U << 30, + ZBufferTest = 1U << 31, + }; +}; + +struct SLSF2 +{ + SLSF2() = delete; + + enum BSLightingShaderFlags2 : std::uint32_t + { + ZBufferWrite = 1U << 0, + LODLandscape = 1U << 1, + LODObjects = 1U << 2, + NoFade = 1U << 3, + DoubleSided = 1U << 4, + VertexColors = 1U << 5, + GlowMap = 1U << 6, + AssumeShadowmask = 1U << 7, + PackedTangent = 1U << 8, + MultiIndexSnow = 1U << 9, + VertexLighting = 1U << 10, + UniformScale = 1U << 11, + FitSlope = 1U << 12, + Billboard = 1U << 13, + NoLODLandBlend = 1U << 14, + EnvMapLightFade = 1U << 15, + Wireframe = 1U << 16, + WeaponBlood = 1U << 17, + HideOnLocalMap = 1U << 18, + PremultAlpha = 1U << 19, + CloudLOD = 1U << 20, + AnisotropicLighting = 1U << 21, + NoTransparencyMultisampling = 1U << 22, + Unused01 = 1U << 23, + MultiLayerParallax = 1U << 24, + SoftLighting = 1U << 25, + RimLighting = 1U << 26, + BackLighting = 1U << 27, + Unused02 = 1U << 28, + TreeAnim = 1U << 29, + EffectLighting = 1U << 30, + HDLODObjects = 1U << 31, + }; +}; + +struct TriShape +{ + TriShape() = delete; + + enum NiAVObjectFlags : std::uint32_t + { + Hidden = 1U << 0, + SelectiveUpdate = 1U << 1, + SelectiveUpdateTransforms = 1U << 2, + SelectiveUpdateController = 1U << 3, + SelectiveUpdateRigid = 1U << 4, + DisplayUIObject = 1U << 5, + DisableSorting = 1U << 6, + SelectiveUpdateTransformsOverride = 1U << 7, + SaveExternalGeomData = 1U << 9, + NoDecals = 1U << 10, + AlwaysDraw = 1U << 11, + MeshLODFO4 = 1U << 12, + FixedBound = 1U << 13, + TopFadeNode = 1U << 14, + IgnoreFade = 1U << 15, + NoAnimSyncX = 1U << 16, + NoAnimSyncY = 1U << 17, + NoAnimSyncZ = 1U << 18, + NoAnimSyncS = 1U << 19, + NoDismember = 1U << 20, + NoDismemberValidity = 1U << 21, + RenderUse = 1U << 22, + MaterialsApplied = 1U << 23, + HighDetail = 1U << 24, + ForceUpdate = 1U << 25, + PreProcessedNode = 1U << 26, + MeshLODSkyrim = 1U << 27, + }; +}; + +struct NiAlphaPropertyFlags +{ +public: + NiAlphaPropertyFlags(std::uint16_t flags = 0) + { + std::memcpy(this, &flags, sizeof(NiAlphaPropertyFlags)); + } + + bool isAlphaBlendEnabled() + { + return m_AlphaBlendEnable; + } + + GLenum sourceBlendingFactor() + { + return getBlendMode(m_SrcBlendMode); + } + + GLenum destinationBlendingFactor() + { + return getBlendMode(m_DstBlendMode); + } + + bool isAlphaTestEnabled() + { + return m_AlphaTestEnable; + } + + GLenum alphaTestMode() + { + return getTestMode(m_AlphaTestMode); + } + + bool isTriangleSortDisabled() + { + return m_NoSort; + } + +private: + static std::uint32_t getBlendMode(std::uint16_t flags) + { + switch (flags) { + case 0: return GL_ONE; + case 1: return GL_ZERO; + case 2: return GL_SRC_COLOR; + case 3: return GL_ONE_MINUS_SRC_COLOR; + case 4: return GL_DST_COLOR; + case 5: return GL_ONE_MINUS_DST_COLOR; + case 6: return GL_SRC_ALPHA; + case 7: return GL_ONE_MINUS_SRC_ALPHA; + case 8: return GL_DST_ALPHA; + case 9: return GL_ONE_MINUS_DST_ALPHA; + default: return GL_ONE; + }; + } + + static std::uint32_t getTestMode(std::uint16_t flags) + { + switch (flags) { + case 0: return GL_ALWAYS; + case 1: return GL_LESS; + case 2: return GL_EQUAL; + case 3: return GL_LEQUAL; + case 4: return GL_GREATER; + case 5: return GL_NOTEQUAL; + case 6: return GL_GEQUAL; + case 7: return GL_NEVER; + default: return GL_ALWAYS; + } + }; + + std::uint16_t m_AlphaBlendEnable : 1; + std::uint16_t m_SrcBlendMode : 4; + std::uint16_t m_DstBlendMode : 4; + std::uint16_t m_AlphaTestEnable : 1; + std::uint16_t m_AlphaTestMode : 3; + std::uint16_t m_NoSort : 1; +}; +static_assert(sizeof(NiAlphaPropertyFlags) == 2); + +inline nifly::MatTransform GetShapeTransformToGlobal( + nifly::NifFile* nifFile, + nifly::NiShape* niShape) +{ + nifly::MatTransform xform = niShape->GetTransformToParent(); + nifly::NiNode* parent = nifFile->GetParentNode(niShape); + while (parent) { + xform = parent->GetTransformToParent().ComposeTransforms(xform); + parent = nifFile->GetParentNode(parent); + } + + return xform; +} + +inline nifly::BoundingSphere GetBoundingSphere( + nifly::NifFile* nifFile, + nifly::NiShape* niShape) +{ + if (auto vertices = nifFile->GetVertsForShape(niShape)) { + auto bounds = nifly::BoundingSphere(*vertices); + + auto xform = GetShapeTransformToGlobal(nifFile, niShape); + + bounds.center = xform.ApplyTransform(bounds.center); + bounds.radius = xform.ApplyTransformToDist(bounds.radius); + return bounds; + } + else { + return nifly::BoundingSphere(); + } +} diff --git a/libs/preview_nif/src/NifWidget.cpp b/libs/preview_nif/src/NifWidget.cpp new file mode 100644 index 0000000..d224d04 --- /dev/null +++ b/libs/preview_nif/src/NifWidget.cpp @@ -0,0 +1,254 @@ +#include "NifWidget.h" +#include "NifExtensions.h" + +#include <QMouseEvent> +#include <QWheelEvent> +#include <QOpenGLContext> +#include <QOpenGLFunctions_2_1> +#include <QOpenGLVersionFunctionsFactory> +using OpenGLFunctions = QOpenGLFunctions_2_1; + +NifWidget::NifWidget( + std::shared_ptr<nifly::NifFile> nifFile, + MOBase::IOrganizer* moInfo, + bool debugContext, + QWidget* parent, + Qt::WindowFlags f) + : QOpenGLWidget(parent, f), + m_NifFile{ nifFile }, + m_MOInfo{ moInfo }, + m_TextureManager{ std::make_unique<TextureManager>(moInfo) }, + m_ShaderManager{ std::make_unique<ShaderManager>(moInfo) } +{ + QSurfaceFormat format; + // CompatibilityProfile — CoreProfile only exists for 3.2+, so the old + // CoreProfile+2.1 combo was getting silently downgraded, leaving Qt + // to pick a driver path we don't control. Compatibility 2.1 is the + // actual legal pair for the fixed-function bits this widget uses. + format.setVersion(2, 1); + format.setProfile(QSurfaceFormat::CompatibilityProfile); + format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); + format.setSwapInterval(1); + format.setDepthBufferSize(24); + // RGBX framebuffer — no alpha channel so compositor can't see through. + format.setAlphaBufferSize(0); + + if (debugContext) { + format.setOption(QSurfaceFormat::DebugContext); + m_Logger = new QOpenGLDebugLogger(this); + } + + setFormat(format); +} + +NifWidget::~NifWidget() +{ + cleanup(); +} + +void NifWidget::mousePressEvent(QMouseEvent* event) +{ + m_MousePos = event->globalPosition().toPoint(); +} + +void NifWidget::mouseMoveEvent(QMouseEvent* event) +{ + auto pos = event->globalPosition().toPoint(); + auto delta = pos - m_MousePos; + m_MousePos = pos; + + switch (event->buttons()) { + case Qt::LeftButton: + { + m_Camera->rotate(delta.x() * 0.5, delta.y() * 0.5); + } break; + case Qt::MiddleButton: + { + float viewDX = m_Camera->distance() / m_ViewportWidth; + float viewDY = m_Camera->distance() / m_ViewportHeight; + + QMatrix4x4 r; + r.rotate(-m_Camera->yaw(), 0.0f, 1.0f, 0.0f); + r.rotate(-m_Camera->pitch(), 1.0f, 0.0f, 0.0f); + + auto pan = r * QVector4D(-delta.x() * viewDX, delta.y() * viewDY, 0.0f, 0.0f); + + m_Camera->pan(QVector3D(pan)); + } break; + case Qt::RightButton: + { + if (event->modifiers() == Qt::ShiftModifier) { + m_Camera->zoomDistance(delta.y() * 0.1f); + } + } break; + } +} + +void NifWidget::wheelEvent(QWheelEvent* event) +{ + m_Camera->zoomFactor(1.0f - (event->angleDelta().y() / 120.0f * 0.38f)); +} + +void NifWidget::initializeGL() +{ + if (m_Logger) { + m_Logger->initialize(); + connect( + m_Logger, + &QOpenGLDebugLogger::messageLogged, + this, + [](const QOpenGLDebugMessage& debugMessage){ + auto msg = tr("OpenGL debug message: %1").arg(debugMessage.message()); + qDebug(qUtf8Printable(msg)); + }); + } + + auto shapes = m_NifFile->GetShapes(); + for (auto& shape : shapes) { + if (shape->flags & TriShape::Hidden) { + continue; + } + + m_GLShapes.emplace_back(m_NifFile.get(), shape, m_TextureManager.get()); + } + + m_Camera = SharedCamera; + if (m_Camera.isNull()) { + m_Camera = { new Camera(), &Camera::deleteLater }; + SharedCamera = m_Camera; + + float largestRadius = 0.0f; + for (auto& shape : shapes) { + auto bounds = GetBoundingSphere(m_NifFile.get(), shape); + + if (bounds.radius > largestRadius) { + largestRadius = bounds.radius; + + m_Camera->setDistance(bounds.radius * 2.4f); + m_Camera->setLookAt({ -bounds.center.x, bounds.center.z, bounds.center.y }); + } + } + } + + updateCamera(); + + connect( + m_Camera.get(), + &Camera::cameraMoved, + this, + [this](){ + updateCamera(); + update(); + }); + + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + + f->glEnable(GL_DEPTH_TEST); + f->glDepthFunc(GL_LEQUAL); + f->glClearColor(0.18, 0.18, 0.18, 1.0); + + // Persistent polygon offset state — actual per-shape bias is set in + // paintGL() by draw order so coplanar overlays tie-break deterministically. + f->glEnable(GL_POLYGON_OFFSET_FILL); +} + +void NifWidget::paintGL() +{ + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + + // Force the framebuffer to be fully opaque. Sequence: + // 1. Unmask alpha + clear → writes RGB=dark grey, A=1.0 + // 2. Mask alpha off → subsequent shape draws can't touch FB alpha + // Without this, alpha-blended shapes mutate FB alpha and Qt composites + // the dialog background through the preview area (see-through bug). + f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + f->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); + + for (auto& shape : m_GLShapes) { + // Small polygon offset only on decal-flagged shapes to break z-ties + // with their coincident base mesh. Progressive/large offsets push + // depth out of the valid [0,1] range at far camera distances, + // which culls decals (the moss/road at zoom-out bug). + if (shape.isDecal) { + f->glPolygonOffset(-1.0f, -1.0f); + } else { + f->glPolygonOffset(0.0f, 0.0f); + } + + auto program = m_ShaderManager->getProgram(shape.shaderType); + if (program && program->isLinked() && program->bind()) { + auto binder = QOpenGLVertexArrayObject::Binder(shape.vertexArray); + + auto& modelMatrix = shape.modelMatrix; + auto modelViewMatrix = m_ViewMatrix * modelMatrix; + auto mvpMatrix = m_ProjectionMatrix * modelViewMatrix; + + program->setUniformValue("worldMatrix", modelMatrix); + program->setUniformValue("viewMatrix", m_ViewMatrix); + program->setUniformValue("modelViewMatrix", modelViewMatrix); + program->setUniformValue("modelViewMatrixInverse", modelViewMatrix.inverted()); + program->setUniformValue("normalMatrix", modelViewMatrix.normalMatrix()); + program->setUniformValue("mvpMatrix", mvpMatrix); + program->setUniformValue("lightDirection", QVector3D(0, 0, 1)); + + shape.setupShaders(program); + + if (shape.indexBuffer && shape.indexBuffer->isCreated()) { + shape.indexBuffer->bind(); + f->glDrawElements(GL_TRIANGLES, shape.elements, GL_UNSIGNED_SHORT, nullptr); + shape.indexBuffer->release(); + } + + program->release(); + } + } +} + +void NifWidget::resizeGL(int w, int h) +{ + QMatrix4x4 m; + m.perspective(40.0f, static_cast<float>(w) / h, 0.1f, 10000.0f); + + m_ProjectionMatrix = m; + m_ViewportWidth = w; + m_ViewportHeight = h; +} + +void NifWidget::cleanup() +{ + // Must run from ~NifWidget (not from the QOpenGLContext::aboutToBeDestroyed + // signal), because the signal fires after derived-class members have + // already been torn down — iterating m_GLShapes from a signal slot then + // walks freed memory. Keep cleanup synchronous in the dtor. + if (!context()) { + return; + } + + makeCurrent(); + + for (auto& shape : m_GLShapes) { + shape.destroy(); + } + m_GLShapes.clear(); + + m_TextureManager->cleanup(); +} + +void NifWidget::updateCamera() +{ + QMatrix4x4 m; + m.translate(0.0f, 0.0f, -m_Camera->distance()); + m.rotate(m_Camera->pitch(), 1.0f, 0.0f, 0.0f); + m.rotate(m_Camera->yaw(), 0.0f, 1.0f, 0.0f); + m.translate(-m_Camera->lookAt()); + m *= QMatrix4x4{ + -1, 0, 0, 0, + 0, 0, 1, 0, + 0, 1, 0, 0, + 0, 0, 0, 1, + }; + m_ViewMatrix = m; +} diff --git a/libs/preview_nif/src/NifWidget.h b/libs/preview_nif/src/NifWidget.h new file mode 100644 index 0000000..34f2de0 --- /dev/null +++ b/libs/preview_nif/src/NifWidget.h @@ -0,0 +1,71 @@ +#pragma once + +#include "Camera.h" +#include "OpenGLShape.h" +#include "ShaderManager.h" +#include "TextureManager.h" + +#include <QOpenGLBuffer> +#include <QOpenGLDebugLogger> +#include <QOpenGLShaderProgram> +#include <QOpenGLVertexArrayObject> +#include <QOpenGLWidget> +#include <QSharedPointer> + +#include <imoinfo.h> +#include <NifFile.hpp> + +#include <memory> + +class NifWidget : public QOpenGLWidget +{ + Q_OBJECT + +public: + NifWidget( + std::shared_ptr<nifly::NifFile> nifFile, + MOBase::IOrganizer* organizer, + bool debugContext = false, + QWidget* parent = nullptr, + Qt::WindowFlags f = {0}); + + ~NifWidget(); + NifWidget(const NifWidget&) = delete; + NifWidget(NifWidget&&) = delete; + NifWidget& operator=(const NifWidget&) = delete; + NifWidget& operator=(NifWidget&&) = delete; + +protected: + void mousePressEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void wheelEvent(QWheelEvent* event) override; + + void initializeGL() override; + void paintGL() override; + void resizeGL(int w, int h) override; + +private: + void cleanup(); + void updateCamera(); + + inline static QWeakPointer<Camera> SharedCamera; + + std::shared_ptr<nifly::NifFile> m_NifFile; + MOBase::IOrganizer* m_MOInfo = nullptr; + + std::unique_ptr<TextureManager> m_TextureManager; + std::unique_ptr<ShaderManager> m_ShaderManager; + + QOpenGLDebugLogger* m_Logger = nullptr; + + std::vector<OpenGLShape> m_GLShapes; + + QSharedPointer<Camera> m_Camera; + + QMatrix4x4 m_ViewMatrix; + QMatrix4x4 m_ProjectionMatrix; + + int m_ViewportWidth; + int m_ViewportHeight; + QPoint m_MousePos; +}; diff --git a/libs/preview_nif/src/OpenGLShape.cpp b/libs/preview_nif/src/OpenGLShape.cpp new file mode 100644 index 0000000..ac7e678 --- /dev/null +++ b/libs/preview_nif/src/OpenGLShape.cpp @@ -0,0 +1,403 @@ +#include "OpenGLShape.h" +#include "NifExtensions.h" + +#include <QOpenGLContext> +#include <QOpenGLFunctions_2_1> +#include <QOpenGLVersionFunctionsFactory> + +template <typename T> +inline static QOpenGLBuffer* makeVertexBuffer(const std::vector<T>* data, GLuint attrib) +{ + QOpenGLBuffer* buffer = nullptr; + + if (data) { + buffer = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer); + if (buffer->create() && buffer->bind()) { + buffer->allocate(data->data(), data->size() * sizeof(T)); + + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + + f->glEnableVertexAttribArray(attrib); + + f->glVertexAttribPointer(attrib, sizeof(T) / sizeof(float), GL_FLOAT, + GL_FALSE, sizeof(T), nullptr); + + buffer->release(); + } + } + + return buffer; +} + +OpenGLShape::OpenGLShape(nifly::NifFile* nifFile, nifly::NiShape* niShape, + TextureManager* textureManager) +{ + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + + auto shader = nifFile->GetShader(niShape); + auto& version = nifFile->GetHeader().GetVersion(); + if (version.IsFO4()) { + if (shader && shader->HasType<nifly::BSEffectShaderProperty>()) { + shaderType = ShaderManager::FO4EffectShader; + } + else { + shaderType = ShaderManager::FO4Default; + } + } + else { + if (shader && shader->HasType<nifly::BSEffectShaderProperty>()) { + shaderType = ShaderManager::SKEffectShader; + } + else { + if (shader && shader->IsModelSpace()) { + shaderType = ShaderManager::SKMSN; + } + else if (shader && + shader->GetShaderType() == nifly::BSLSP_MULTILAYERPARALLAX) { + shaderType = ShaderManager::SKMultilayer; + } + else { + shaderType = ShaderManager::SKDefault; + } + } + } + + vertexArray = new QOpenGLVertexArrayObject(); + vertexArray->create(); + auto binder = QOpenGLVertexArrayObject::Binder(vertexArray); + + auto xform = GetShapeTransformToGlobal(nifFile, niShape); + modelMatrix = convertTransform(xform); + + f->glVertexAttrib2f(AttribTexCoord, 0.0f, 0.0f); + f->glVertexAttrib4f(AttribColor, 1.0f, 1.0f, 1.0f, 1.0f); + + // AMD GPU fails to render without vertex data + if (!niShape->HasNormals()) { + niShape->SetNormals(true); + if (auto geomData = niShape->GetGeomData()) { + geomData->RecalcNormals(); + } + } + + if (!niShape->HasTangents()) { + niShape->SetTangents(true); + if (auto geomData = niShape->GetGeomData()) { + geomData->CalcTangentSpace(); + } + } + + if (!niShape->HasUVs()) { + niShape->SetUVs(true); + } + + if (!niShape->HasVertexColors()) { + niShape->SetVertexColors(true); + } + + if (auto verts = nifFile->GetVertsForShape(niShape)) { + vertexBuffers[AttribPosition] = makeVertexBuffer(verts, AttribPosition); + } + + if (auto normals = nifFile->GetNormalsForShape(niShape)) { + vertexBuffers[AttribNormal] = makeVertexBuffer(normals, AttribNormal); + } + + if (auto tangents = nifFile->GetTangentsForShape(niShape)) { + vertexBuffers[AttribTangent] = makeVertexBuffer(tangents, AttribTangent); + } + + if (auto bitangents = nifFile->GetBitangentsForShape(niShape)) { + vertexBuffers[AttribBitangent] = makeVertexBuffer(bitangents, AttribBitangent); + } + + if (auto uvs = nifFile->GetUvsForShape(niShape)) { + vertexBuffers[AttribTexCoord] = makeVertexBuffer(uvs, AttribTexCoord); + } + + if (std::vector<nifly::Color4> colors; + nifFile->GetColorsForShape(niShape, colors)) { + vertexBuffers[AttribColor] = makeVertexBuffer(&colors, AttribColor); + } + + indexBuffer = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); + if (indexBuffer->create() && indexBuffer->bind()) { + + if (std::vector<nifly::Triangle> tris; niShape->GetTriangles(tris)) { + indexBuffer->allocate(tris.data(), tris.size() * sizeof(nifly::Triangle)); + } + + elements = niShape->GetNumTriangles() * 3; + indexBuffer->release(); + } + + if (shader) { + if (shader->HasTextureSet()) { + auto textureSetRef = shader->TextureSetRef(); + auto textureSet = nifFile->GetHeader().GetBlock(textureSetRef); + + for (std::size_t i = 0; i < textureSet->textures.size(); i++) { + auto texturePath = textureSet->textures[i].get(); + if (!texturePath.empty()) { + textures[i] = textureManager->getTexture(texturePath); + } + + if (textures[i] == nullptr) { + switch (i) { + case TextureSlot::BaseMap: + textures[i] = textureManager->getErrorTexture(); + break; + case TextureSlot::NormalMap: + textures[i] = textureManager->getFlatNormalTexture(); + break; + case TextureSlot::GlowMap: + if (shader->HasGlowmap()) { + textures[i] = textureManager->getBlackTexture(); + } + else { + textures[i] = textureManager->getWhiteTexture(); + } + break; + default: + textures[i] = nullptr; + break; + } + } + } + } + + specColor = convertVector3(shader->GetSpecularColor()); + specStrength = shader->GetSpecularStrength(); + specGlossiness = qBound(0.0f, shader->GetGlossiness(), 128.0f); + fresnelPower = shader->GetFresnelPower(); + paletteScale = shader->GetGrayscaleToPaletteScale(); + + hasGlowMap = shader->HasGlowmap(); + glowColor = convertColor(shader->GetEmissiveColor()); + glowMult = shader->GetEmissiveMultiple(); + + alpha = shader->GetAlpha(); + uvScale = convertVector2(shader->GetUVScale()); + uvOffset = convertVector2(shader->GetUVOffset()); + + hasEmit = shader->IsEmissive(); + hasSoftlight = shader->HasSoftlight(); + hasBacklight = shader->HasBacklight(); + hasRimlight = shader->HasRimlight(); + + softlight = shader->GetSoftlight(); + backlightPower = shader->GetBacklightPower(); + rimPower = shader->GetRimlightPower(); + doubleSided = shader->IsDoubleSided(); + envReflection = shader->GetEnvironmentMapScale(); + + if (auto alphaProperty = nifFile->GetAlphaProperty(niShape)) { + + NiAlphaPropertyFlags flags = alphaProperty->flags; + + alphaBlendEnable = flags.isAlphaBlendEnabled(); + srcBlendMode = flags.sourceBlendingFactor(); + dstBlendMode = flags.destinationBlendingFactor(); + alphaTestEnable = flags.isAlphaTestEnabled(); + alphaTestMode = flags.alphaTestMode(); + + alphaThreshold = alphaProperty->threshold / 255.0f; + } + + if (auto bslsp = dynamic_cast<nifly::BSLightingShaderProperty*>(shader)) { + zBufferTest = bslsp->shaderFlags1 & SLSF1::ZBufferTest; + zBufferWrite = bslsp->shaderFlags2 & SLSF2::ZBufferWrite; + // SLSF1_Decal = 0x04000000, SLSF1_Dynamic_Decal = 0x08000000. + // Bethesda marks decals (roads, blood splats, graffiti) with + // these flags. We use them to drive polygon offset so decals + // don't z-fight with the coincident base mesh. + isDecal = bslsp->shaderFlags1 & 0x0C000000; + + auto bslspType = bslsp->GetShaderType(); + if (bslspType == nifly::BSLSP_SKINTINT || bslspType == nifly::BSLSP_FACE) { + tintColor = convertVector3(bslsp->skinTintColor); + hasTintColor = true; + } + else if (bslspType == nifly::BSLSP_HAIRTINT) { + tintColor = convertVector3(bslsp->hairTintColor); + hasTintColor = true; + } + + if (bslspType == nifly::BSLSP_MULTILAYERPARALLAX) { + innerScale = convertVector2(bslsp->parallaxInnerLayerTextureScale); + innerThickness = bslsp->parallaxInnerLayerThickness; + outerRefraction = bslsp->parallaxRefractionScale; + outerReflection = bslsp->parallaxEnvmapStrength; + } + } + + if (auto effectShader = dynamic_cast<nifly::BSEffectShaderProperty*>(shader)) { + hasWeaponBlood = effectShader->shaderFlags2 & SLSF2::WeaponBlood; + } + } + else { + textures[BaseMap] = textureManager->getWhiteTexture(); + textures[NormalMap] = textureManager->getFlatNormalTexture(); + } +} + +void OpenGLShape::destroy() +{ + for (std::size_t i = 0; i < ATTRIB_COUNT; i++) { + if (vertexBuffers[i]) { + vertexBuffers[i]->destroy(); + delete vertexBuffers[i]; + vertexBuffers[i] = nullptr; + } + } + + if (indexBuffer) { + indexBuffer->destroy(); + delete indexBuffer; + indexBuffer = nullptr; + } + + if (vertexArray) { + vertexArray->destroy(); + vertexArray->deleteLater(); + } +} + +void OpenGLShape::setupShaders(QOpenGLShaderProgram* program) +{ + program->setUniformValue("BaseMap", BaseMap + 1); + program->setUniformValue("NormalMap", NormalMap + 1); + program->setUniformValue("GlowMap", GlowMap + 1); + program->setUniformValue("LightMask", LightMask + 1); + program->setUniformValue("hasGlowMap", hasGlowMap && textures[GlowMap] != nullptr); + program->setUniformValue("HeightMap", HeightMap + 1); + program->setUniformValue("hasHeightMap", textures[HeightMap] != nullptr); + program->setUniformValue("DetailMask", DetailMask + 1); + program->setUniformValue("hasDetailMask", textures[DetailMask] != nullptr); + program->setUniformValue("CubeMap", EnvironmentMap + 1); + program->setUniformValue("hasCubeMap", textures[EnvironmentMap] != nullptr); + program->setUniformValue("EnvironmentMap", EnvironmentMask + 1); + program->setUniformValue("hasEnvMask", textures[EnvironmentMask] != nullptr); + program->setUniformValue("TintMask", TintMask + 1); + program->setUniformValue("hasTintMask", textures[TintMask] != nullptr); + program->setUniformValue("InnerMap", InnerMap + 1); + program->setUniformValue("BacklightMap", BacklightMap + 1); + program->setUniformValue("SpecularMap", SpecularMap + 1); + program->setUniformValue("hasSpecularMap", textures[SpecularMap] != nullptr); + + for (int i = 0; i < textures.size(); i++) { + if (textures[i]) { + textures[i]->bind(i + 1); + } + } + + program->setUniformValue("ambientColor", QVector4D(0.2f, 0.2f, 0.2f, 1.0f)); + program->setUniformValue("diffuseColor", QVector4D(1.0f, 1.0f, 1.0f, 1.0f)); + + program->setUniformValue("alpha", alpha); + program->setUniformValue("tintColor", tintColor); + program->setUniformValue("uvScale", uvScale); + program->setUniformValue("uvOffset", uvOffset); + program->setUniformValue("specColor", specColor); + program->setUniformValue("specStrength", specStrength); + program->setUniformValue("specGlossiness", specGlossiness); + program->setUniformValue("fresnelPower", fresnelPower); + + program->setUniformValue("paletteScale", paletteScale); + + program->setUniformValue("hasEmit", hasEmit); + program->setUniformValue("hasSoftlight", hasSoftlight); + program->setUniformValue("hasBacklight", hasBacklight); + program->setUniformValue("hasRimlight", hasRimlight); + program->setUniformValue("hasTintColor", hasTintColor); + program->setUniformValue("hasWeaponBlood", hasWeaponBlood); + + program->setUniformValue("softlight", softlight); + program->setUniformValue("backlightPower", backlightPower); + program->setUniformValue("rimPower", rimPower); + program->setUniformValue("subsurfaceRolloff", subsurfaceRolloff); + program->setUniformValue("doubleSided", doubleSided); + + program->setUniformValue("envReflection", envReflection); + + if (shaderType == ShaderManager::SKMultilayer) { + program->setUniformValue("innerScale", innerScale); + program->setUniformValue("innerThickness", innerThickness); + program->setUniformValue("outerRefraction", outerRefraction); + program->setUniformValue("outerReflection", outerReflection); + } + + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + + for (std::size_t i = 0; i < ATTRIB_COUNT; i++) { + if (vertexBuffers[i]) { + f->glEnableVertexAttribArray(i); + } + else { + f->glDisableVertexAttribArray(i); + } + } + + f->glDepthMask(zBufferWrite ? GL_TRUE : GL_FALSE); + + if (zBufferTest) { + f->glEnable(GL_DEPTH_TEST); + } + else { + f->glDisable(GL_DEPTH_TEST); + } + + // Polygon offset bias is set per-shape by the draw loop in + // NifWidget::paintGL — don't touch it here. + + if (doubleSided) { + f->glDisable(GL_CULL_FACE); + } + else { + f->glEnable(GL_CULL_FACE); + f->glCullFace(GL_BACK); + } + + if (alphaBlendEnable) { + f->glEnable(GL_BLEND); + f->glBlendFunc(srcBlendMode, dstBlendMode); + } + else { + f->glDisable(GL_BLEND); + } + + if (alphaTestEnable) { + f->glEnable(GL_ALPHA_TEST); + f->glAlphaFunc(alphaTestMode, alphaThreshold); + } + else { + f->glDisable(GL_ALPHA_TEST); + } +} + +QVector2D OpenGLShape::convertVector2(nifly::Vector2 vector) +{ + return {vector.u, vector.v}; +} + +QVector3D OpenGLShape::convertVector3(nifly::Vector3 vector) +{ + return {vector.x, vector.y, vector.z}; +} + +QColor OpenGLShape::convertColor(nifly::Color4 color) +{ + return QColor::fromRgbF(color.r, color.g, color.b, color.a); +} + +QMatrix4x4 OpenGLShape::convertTransform(nifly::MatTransform transform) +{ + auto mat = transform.ToMatrix(); + return QMatrix4x4{ + mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], + mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15], + }; +} diff --git a/libs/preview_nif/src/OpenGLShape.h b/libs/preview_nif/src/OpenGLShape.h new file mode 100644 index 0000000..b53e96d --- /dev/null +++ b/libs/preview_nif/src/OpenGLShape.h @@ -0,0 +1,105 @@ +#pragma once + +#include "ShaderManager.h" +#include "TextureManager.h" + +#include <Geometry.hpp> +#include <NifFile.hpp> + +#include <QOpenGLBuffer> +#include <QOpenGLShaderProgram> +#include <QOpenGLTexture> +#include <QOpenGLVertexArrayObject> +#include <QWidget> + +enum TextureSlot +{ + BaseMap = 0, + NormalMap = 1, + GlowMap = 2, + LightMask = 2, + HeightMap = 3, + DetailMask = 3, + EnvironmentMap = 4, + EnvironmentMask = 5, + TintMask = 6, + InnerMap = 6, + BacklightMap = 7, + SpecularMap = 7, +}; + +struct OpenGLShape +{ +public: + OpenGLShape( + nifly::NifFile* nifFile, + nifly::NiShape* niShape, + TextureManager* textureManager); + + void destroy(); + void setupShaders(QOpenGLShaderProgram* program); + + static QVector2D convertVector2(nifly::Vector2 vector); + static QVector3D convertVector3(nifly::Vector3 vector); + static QColor convertColor(nifly::Color4 color); + static QMatrix4x4 convertTransform(nifly::MatTransform transform); + + ShaderManager::ShaderType shaderType = ShaderManager::SKDefault; + + QOpenGLVertexArrayObject* vertexArray = nullptr; + + QOpenGLBuffer* vertexBuffers[ATTRIB_COUNT] { nullptr }; + + QOpenGLBuffer* indexBuffer = nullptr; + GLsizei elements = 0; + + std::array<QOpenGLTexture*, 13> textures { nullptr }; + + QMatrix4x4 modelMatrix; + QVector3D specColor{ 1.0f, 1.0f, 1.0f }; + float specStrength = 1.0f ; + float specGlossiness = 1.0f; + float fresnelPower; + + float paletteScale; + + bool hasGlowMap = false; + QColor glowColor = QColorConstants::White; + float glowMult = 1.0f; + + float alpha = 1.0f; + QVector3D tintColor{ 1.0f, 1.0f, 1.0f }; + + QVector2D uvScale{ 1.0f, 1.0f }; + QVector2D uvOffset{ 0.0f, 0.0f }; + + bool hasEmit = false; + bool hasSoftlight = false; + bool hasBacklight = false; + bool hasRimlight = false; + bool hasTintColor = false; + bool hasWeaponBlood = false; + + bool doubleSided = false; + float softlight = 0.3f; + float backlightPower = 0.0f; + float rimPower = 2.0f; + float subsurfaceRolloff; + float envReflection = 1.0f; + + QVector2D innerScale; + float innerThickness; + float outerRefraction; + float outerReflection; + + bool zBufferWrite = true; + bool zBufferTest = true; + bool isDecal = false; + + bool alphaBlendEnable = false; + GLenum srcBlendMode = GL_ONE; + GLenum dstBlendMode = GL_ONE; + bool alphaTestEnable = false; + GLenum alphaTestMode = GL_GREATER; + float alphaThreshold = 0.0f; +}; diff --git a/libs/preview_nif/src/PreviewNif.cpp b/libs/preview_nif/src/PreviewNif.cpp new file mode 100644 index 0000000..8e7e03a --- /dev/null +++ b/libs/preview_nif/src/PreviewNif.cpp @@ -0,0 +1,114 @@ +#include <NifFile.hpp> + +#include "PreviewNif.h" +#include "NifExtensions.h" +#include "NifWidget.h" + +#include <QGridLayout> +#include <filesystem> +#include <sstream> +#include <string> + +bool PreviewNif::init(MOBase::IOrganizer* moInfo) +{ + m_MOInfo = moInfo; + return true; +} + +QString PreviewNif::name() const +{ + return "Preview NIF"; +} + +QString PreviewNif::author() const +{ + return "Parapets"; +} + +QString PreviewNif::description() const +{ + return "Supports previewing NIF files"; +} + +MOBase::VersionInfo PreviewNif::version() const +{ + return MOBase::VersionInfo(0, 2, 0, 0, MOBase::VersionInfo::RELEASE_BETA); +} + +QList<MOBase::PluginSetting> PreviewNif::settings() const +{ + return QList<MOBase::PluginSetting>(); +} + +bool PreviewNif::enabledByDefault() const +{ + return true; +} + +std::set<QString> PreviewNif::supportedExtensions() const +{ + return { "bto", "btr", "nif" }; +} + +QWidget* PreviewNif::genFilePreview(const QString& fileName, const QSize&) const +{ + auto path = std::filesystem::path(fileName.toStdString()); + auto nifFile = std::make_shared<nifly::NifFile>(path); + + if (!nifFile->IsValid()) { + qWarning(qUtf8Printable(tr("Failed to load file: %1").arg(fileName))); + return nullptr; + } + + return makeWidget(nifFile); +} + +QWidget* PreviewNif::genDataPreview(const QByteArray& fileData, + const QString& fileName, const QSize&) const +{ + std::string data(fileData.constData(), fileData.size()); + std::istringstream stream(std::move(data), std::ios::binary); + + auto nifFile = std::make_shared<nifly::NifFile>(); + if (nifFile->Load(stream) != 0 || !nifFile->IsValid()) { + qWarning(qUtf8Printable(tr("Failed to load file: %1").arg(fileName))); + return nullptr; + } + + return makeWidget(nifFile); +} + +QWidget* PreviewNif::makeWidget(std::shared_ptr<nifly::NifFile> nifFile) const +{ + auto layout = new QGridLayout(); + layout->setRowStretch(0, 1); + layout->setColumnStretch(0, 1); + + layout->addWidget(makeLabel(nifFile.get()), 1, 0, 1, 1); + + auto nifWidget = new NifWidget(nifFile, m_MOInfo); + layout->addWidget(nifWidget, 0, 0, 1, 1); + + auto widget = new QWidget(); + widget->setLayout(layout); + return widget; +} + +QLabel* PreviewNif::makeLabel(nifly::NifFile* nifFile) const +{ + int shapes = 0; + int faces = 0; + int verts = 0; + + for (auto& shape : nifFile->GetShapes()) { + shapes++; + faces += shape->GetNumTriangles(); + verts += shape->GetNumVertices(); + } + + auto text = tr("Verts: %1 | Faces: %2 | Shapes: %3").arg(verts).arg(faces).arg(shapes); + auto label = new QLabel(text); + label->setWordWrap(true); + label->setTextInteractionFlags(Qt::TextSelectableByMouse); + return label; +} diff --git a/libs/preview_nif/src/PreviewNif.h b/libs/preview_nif/src/PreviewNif.h new file mode 100644 index 0000000..cd5175d --- /dev/null +++ b/libs/preview_nif/src/PreviewNif.h @@ -0,0 +1,39 @@ +#pragma once + +#include <ipluginpreview.h> +#include <QLabel> +#include <NifFile.hpp> + +class PreviewNif : public MOBase::IPluginPreview +{ + Q_OBJECT + Q_INTERFACES(MOBase::IPlugin MOBase::IPluginPreview) + Q_PLUGIN_METADATA(IID "org.tannin.PreviewNif" FILE "previewnif.json") + +public: + PreviewNif() = default; + + // IPlugin Interface + + bool init(MOBase::IOrganizer* moInfo) override; + QString name() const override; + QString author() const override; + QString description() const override; + MOBase::VersionInfo version() const override; + QList<MOBase::PluginSetting> settings() const override; + bool enabledByDefault() const override; + + // IPluginPreview interface + + std::set<QString> supportedExtensions() const override; + bool supportsArchives() const override { return true; } + QWidget* genFilePreview(const QString& fileName, const QSize& maxSize) const override; + QWidget* genDataPreview(const QByteArray& fileData, const QString& fileName, + const QSize& maxSize) const override; + +private: + QWidget* makeWidget(std::shared_ptr<nifly::NifFile> nifFile) const; + QLabel* makeLabel(nifly::NifFile* nifFile) const; + + MOBase::IOrganizer* m_MOInfo; +}; diff --git a/libs/preview_nif/src/ShaderManager.cpp b/libs/preview_nif/src/ShaderManager.cpp new file mode 100644 index 0000000..2109b44 --- /dev/null +++ b/libs/preview_nif/src/ShaderManager.cpp @@ -0,0 +1,74 @@ +#include "ShaderManager.h" + +#include <QOpenGLContext> + +ShaderManager::ShaderManager(MOBase::IOrganizer* moInfo) : m_MOInfo{ moInfo } +{} + +QOpenGLShaderProgram* ShaderManager::getProgram(ShaderType type) +{ + if (type == None) { + return nullptr; + } + + if (m_Programs[type] == nullptr) { + m_Programs[type] = loadProgram(type); + } + + return m_Programs[type]; +} + +QOpenGLShaderProgram* ShaderManager::loadProgram(ShaderType type) +{ + QString vert; + QString frag; + + switch (type) { + case SKDefault: + vert = "default.vert"; + frag = "sk_default.frag"; + break; + case SKMSN: + vert = "sk_msn.vert"; + frag = "sk_msn.frag"; + break; + case SKMultilayer: + vert = "default.vert"; + frag = "sk_multilayer.frag"; + break; + case SKEffectShader: + vert = "sk_effectshader.vert"; + frag = "sk_effectshader.frag"; + break; + case FO4Default: + vert = "default.vert"; + frag = "fo4_default.frag"; + break; + case FO4EffectShader: + vert = "default.vert"; + frag = "fo4_effectshader.frag"; + break; + default: + return nullptr; + } + + auto game = m_MOInfo->managedGame(); + auto dataPath = MOBase::IOrganizer::getPluginDataPath(); + auto vertexShader = QString("%1/shaders/%2").arg(dataPath).arg(vert); + auto fragmentShader = QString("%1/shaders/%2").arg(dataPath).arg(frag); + + auto program = new QOpenGLShaderProgram(QOpenGLContext::currentContext()); + program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShader); + program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShader); + + program->bindAttributeLocation("position", AttribPosition); + program->bindAttributeLocation("normal", AttribNormal); + program->bindAttributeLocation("tangent", AttribTangent); + program->bindAttributeLocation("bitangent", AttribBitangent); + program->bindAttributeLocation("texCoord", AttribTexCoord); + program->bindAttributeLocation("color", AttribColor); + + program->link(); + + return program; +} diff --git a/libs/preview_nif/src/ShaderManager.h b/libs/preview_nif/src/ShaderManager.h new file mode 100644 index 0000000..3c38ba1 --- /dev/null +++ b/libs/preview_nif/src/ShaderManager.h @@ -0,0 +1,48 @@ +#pragma once + +#include <imoinfo.h> +#include <QOpenGLShaderProgram> + +enum VertexAttrib +{ + AttribPosition = 0, + AttribNormal = 1, + AttribTangent = 2, + AttribBitangent = 3, + AttribTexCoord = 4, + AttribColor = 5, + + ATTRIB_COUNT, +}; + +class ShaderManager +{ +public: + enum ShaderType + { + None = -1, + SKDefault, + SKMSN, + SKMultilayer, + SKEffectShader, + FO4Default, + FO4EffectShader, + + SHADER_COUNT, + }; + + ShaderManager(MOBase::IOrganizer* moInfo); + ~ShaderManager() = default; + ShaderManager(const ShaderManager&) = delete; + ShaderManager(ShaderManager&&) = delete; + ShaderManager& operator=(const ShaderManager&) = delete; + ShaderManager& operator=(ShaderManager&&) = delete; + + QOpenGLShaderProgram* getProgram(ShaderType type); + +private: + QOpenGLShaderProgram* loadProgram(ShaderType type); + + MOBase::IOrganizer* m_MOInfo; + QOpenGLShaderProgram* m_Programs[SHADER_COUNT] { nullptr }; +}; diff --git a/libs/preview_nif/src/TextureManager.cpp b/libs/preview_nif/src/TextureManager.cpp new file mode 100644 index 0000000..2135ec6 --- /dev/null +++ b/libs/preview_nif/src/TextureManager.cpp @@ -0,0 +1,448 @@ +#include "TextureManager.h" +#include "PreviewNif.h" + +#include <dataarchives.h> +#include <igamefeatures.h> +#include <imodinterface.h> +#include <imodlist.h> +#include <imoinfo.h> +#include <ipluginlist.h> +#include <iplugingame.h> + +#include <gli/gli.hpp> +#include <libbsarch.h> + +#include <QDir> +#include <QDirIterator> +#include <QFileInfo> +#include <QSet> + +#include <QOpenGLContext> +#include <QOpenGLFunctions_2_1> +#include <QOpenGLVersionFunctionsFactory> +#include <QVector4D> + +#include <exception> +#include <memory> + +TextureManager::TextureManager(MOBase::IOrganizer* moInfo) : m_MOInfo{moInfo} {} + +void TextureManager::cleanup() +{ + for (auto it = m_Textures.cbegin(); it != m_Textures.cend();) { + auto texture = it->second; + m_Textures.erase(it++); + delete texture; + } + + if (m_ErrorTexture) { + delete m_ErrorTexture; + m_ErrorTexture = nullptr; + } + + if (m_BlackTexture) { + delete m_BlackTexture; + m_BlackTexture = nullptr; + } + + if (m_WhiteTexture) { + delete m_WhiteTexture; + m_WhiteTexture = nullptr; + } + + if (m_FlatNormalTexture) { + delete m_FlatNormalTexture; + m_FlatNormalTexture = nullptr; + } +} + +QOpenGLTexture* TextureManager::getTexture(const std::string& texturePath) +{ + return getTexture(QString::fromStdString(texturePath)); +} + +QOpenGLTexture* TextureManager::getTexture(QString texturePath) +{ + if (texturePath.isEmpty()) { + return nullptr; + } + + auto key = texturePath.toLower().toStdWString(); + + auto cached = m_Textures.find(key); + if (cached != m_Textures.end()) { + return cached->second; + } + + auto texture = loadTexture(texturePath); + + m_Textures[key] = texture; + return texture; +} + +QOpenGLTexture* TextureManager::getErrorTexture() +{ + if (!m_ErrorTexture) { + m_ErrorTexture = makeSolidColor({1.0f, 0.0f, 1.0f, 1.0f}); + } + + return m_ErrorTexture; +} + +QOpenGLTexture* TextureManager::getBlackTexture() +{ + if (!m_BlackTexture) { + m_BlackTexture = makeSolidColor({0.0f, 0.0f, 0.0f, 1.0f}); + } + + return m_BlackTexture; +} + +QOpenGLTexture* TextureManager::getWhiteTexture() +{ + if (!m_WhiteTexture) { + m_WhiteTexture = makeSolidColor({1.0f, 1.0f, 1.0f, 1.0f}); + } + + return m_WhiteTexture; +} + +QOpenGLTexture* TextureManager::getFlatNormalTexture() +{ + if (!m_FlatNormalTexture) { + m_FlatNormalTexture = makeSolidColor({0.5f, 0.5f, 1.0f, 1.0f}); + } + + return m_FlatNormalTexture; +} + +QOpenGLTexture* TextureManager::loadTexture(QString texturePath) +{ + if (texturePath.isEmpty()) { + return nullptr; + } + + auto game = m_MOInfo->managedGame(); + + if (!game) { + return nullptr; + } + + // 1) Loose file via MO2's virtual tree (honors mod priority + Overwrite). + auto realPath = resolvePath(game, texturePath); + if (!realPath.isEmpty()) { + return makeTexture(gli::load(realPath.toStdString())); + } + + // 2) BSA fallback. Walk cached priority-sorted candidate list. + auto tryExtract = [&](const QString& bsaPath) -> QOpenGLTexture* { + using bsa_ptr = std::unique_ptr<void, decltype(&bsa_free)>; + auto bsa = bsa_ptr(bsa_create(), bsa_free); + + const std::wstring bsaPathW = bsaPath.toStdWString(); + const std::wstring texturePathW = texturePath.toStdWString(); + + bsa_result_message_t result = + bsa_load_from_file(bsa.get(), bsaPathW.c_str()); + if (result.code == BSA_RESULT_EXCEPTION) { + return nullptr; + } + + auto result_buffer = + bsa_extract_file_data_by_filename(bsa.get(), texturePathW.c_str()); + if (result_buffer.message.code == BSA_RESULT_EXCEPTION || + !result_buffer.buffer.data) { + return nullptr; + } + + auto buffer_free = [&bsa](bsa_result_buffer_t* buffer) { + bsa_file_data_free(bsa.get(), *buffer); + }; + using buffer_ptr = + std::unique_ptr<bsa_result_buffer_t, decltype(buffer_free)>; + auto buffer = buffer_ptr(&result_buffer.buffer, buffer_free); + + return makeTexture( + gli::load(static_cast<char*>(buffer->data), buffer->size)); + }; + + for (const QString& bsaPath : bsaCandidates()) { + if (auto* tex = tryExtract(bsaPath)) { + return tex; + } + } + + return nullptr; +} + +// Process-wide BSA candidate cache. Keyed by profile directory path so +// switching instances invalidates automatically. Built once, reused across +// every NIF preview until the profile changes. +namespace { + QString g_cachedProfileKey; + QStringList g_cachedBsaCandidates; +} + +const QStringList& TextureManager::bsaCandidates() +{ + QString profileKey; + if (auto profile = m_MOInfo->profile()) { + profileKey = profile->absolutePath(); + } + + if (profileKey == g_cachedProfileKey && !g_cachedBsaCandidates.isEmpty()) { + return g_cachedBsaCandidates; + } + + g_cachedBsaCandidates.clear(); + rebuildBsaCandidates(); + g_cachedProfileKey = profileKey; + return g_cachedBsaCandidates; +} + +void TextureManager::rebuildBsaCandidates() +{ + QSet<QString> seen; + + auto addCandidate = [&](const QString& p) { + QString norm = QDir::cleanPath(p); + if (!norm.isEmpty() && !seen.contains(norm)) { + seen.insert(norm); + g_cachedBsaCandidates.append(norm); + } + }; + + try { + auto game = m_MOInfo->managedGame(); + + if (auto* modList = m_MOInfo->modList()) { + auto profile = m_MOInfo->profile(); + QStringList modNames = + modList->allModsByProfilePriority(profile.get()); + + for (auto it = modNames.rbegin(); it != modNames.rend(); ++it) { + if (!(modList->state(*it) & MOBase::IModList::STATE_ACTIVE)) + continue; + + MOBase::IModInterface* mod = modList->getMod(*it); + if (!mod) continue; + + QDir modDir(mod->absolutePath()); + if (!modDir.exists()) continue; + + const QStringList bsas = + modDir.entryList(QStringList{"*.bsa", "*.ba2"}, + QDir::Files | QDir::NoDotAndDotDot); + for (const QString& name : bsas) { + addCandidate(modDir.absoluteFilePath(name)); + } + } + } + + // Vanilla/game archives from DataArchives ini list. + if (auto* features = m_MOInfo->gameFeatures()) { + if (auto gameArchives = + features->gameFeature<MOBase::DataArchives>()) { + auto profile = m_MOInfo->profile(); + auto archives = gameArchives->archives(profile.get()); + for (auto it = archives.rbegin(); it != archives.rend(); ++it) { + QString resolved = resolvePath(game, *it); + if (!resolved.isEmpty()) addCandidate(resolved); + } + } + } + } catch (...) { + } +} + + +QOpenGLTexture* TextureManager::makeTexture(const gli::texture& texture) +{ + if (texture.empty()) { + return nullptr; + } + + gli::gl GL(gli::gl::PROFILE_GL32); + const gli::gl::format format = GL.translate(texture.format(), texture.swizzles()); + GLenum target = GL.translate(texture.target()); + + auto f = QOpenGLVersionFunctionsFactory::get<QOpenGLFunctions_2_1>( + QOpenGLContext::currentContext()); + QOpenGLTexture* glTexture = + new QOpenGLTexture(static_cast<QOpenGLTexture::Target>(target)); + + glTexture->create(); + glTexture->bind(); + glTexture->setMipLevels(texture.levels()); + glTexture->setMipBaseLevel(0); + glTexture->setMipMaxLevel(texture.levels() - 1); + glTexture->setMinMagFilters(QOpenGLTexture::LinearMipMapLinear, + QOpenGLTexture::Linear); + glTexture->setSwizzleMask( + static_cast<QOpenGLTexture::SwizzleValue>(format.Swizzles[0]), + static_cast<QOpenGLTexture::SwizzleValue>(format.Swizzles[1]), + static_cast<QOpenGLTexture::SwizzleValue>(format.Swizzles[2]), + static_cast<QOpenGLTexture::SwizzleValue>(format.Swizzles[3])); + + glTexture->setWrapMode(QOpenGLTexture::Repeat); + + auto extent = texture.extent(); + const GLsizei faceTotal = texture.layers() * texture.faces(); + + glTexture->setSize(extent.x, extent.y, extent.z); + glTexture->setFormat(static_cast<QOpenGLTexture::TextureFormat>(format.Internal)); + glTexture->allocateStorage( + static_cast<QOpenGLTexture::PixelFormat>(format.External), + static_cast<QOpenGLTexture::PixelType>(format.Type)); + + for (std::size_t layer = 0; layer < texture.layers(); layer++) + for (std::size_t face = 0; face < texture.faces(); face++) + for (std::size_t level = 0; level < texture.levels(); level++) { + auto extent = texture.extent(level); + + target = + gli::is_target_cube(texture.target()) + ? static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face) + : target; + + // Qt's upload functions lag badly so we just use the GL API + switch (texture.target()) { + case gli::TARGET_1D: + if (gli::is_compressed(texture.format())) { + f->glCompressedTexSubImage1D( + target, level, 0, extent.x, format.Internal, + texture.size(level), texture.data(layer, face, level)); + } + else { + f->glTexSubImage1D(target, level, 0, extent.x, format.External, + format.Type, + texture.data(layer, face, level)); + } + break; + case gli::TARGET_1D_ARRAY: + case gli::TARGET_2D: + case gli::TARGET_CUBE: + if (gli::is_compressed(texture.format())) { + f->glCompressedTexSubImage2D( + target, level, 0, 0, extent.x, + texture.target() == gli::TARGET_1D_ARRAY ? layer : extent.y, + format.Internal, texture.size(level), + texture.data(layer, face, level)); + } + else { + f->glTexSubImage2D( + target, level, 0, 0, extent.x, + texture.target() == gli::TARGET_1D_ARRAY ? layer : extent.y, + format.External, format.Type, + texture.data(layer, face, level)); + } + break; + case gli::TARGET_2D_ARRAY: + case gli::TARGET_3D: + case gli::TARGET_CUBE_ARRAY: + if (gli::is_compressed(texture.format())) { + f->glCompressedTexSubImage3D( + target, level, 0, 0, 0, extent.x, extent.y, + texture.target() == gli::TARGET_3D ? extent.z : layer, + format.Internal, texture.size(level), + texture.data(layer, face, level)); + } + else { + f->glTexSubImage3D(target, level, 0, 0, 0, extent.x, extent.y, + texture.target() == gli::TARGET_3D ? extent.z + : layer, + format.External, format.Type, + texture.data(layer, face, level)); + } + break; + } + } + + glTexture->release(); + + return glTexture; +} + +QOpenGLTexture* TextureManager::makeSolidColor(QVector4D color) +{ + QOpenGLTexture* glTexture = new QOpenGLTexture(QOpenGLTexture::Target2D); + glTexture->create(); + glTexture->bind(); + + glTexture->setSize(1, 1); + glTexture->setFormat(QOpenGLTexture::RGBA32F); + glTexture->allocateStorage(QOpenGLTexture::RGBA, QOpenGLTexture::Float32); + + glTexture->setData(QOpenGLTexture::RGBA, QOpenGLTexture::Float32, &color); + + glTexture->release(); + + return glTexture; +} + +// Case-insensitive walk of a path relative to a root dir. Used because the +// Linux FS is case-sensitive but Bethesda NIFs reference textures with +// arbitrary case. We fix the case component-by-component against the real +// on-disk filenames. +static QString resolveCaseInsensitive(const QString& rootAbs, const QString& relPath) +{ + QStringList parts = QDir::cleanPath(relPath).split('/', Qt::SkipEmptyParts); + QString cursor = rootAbs; + for (const QString& part : parts) { + QDir cur(cursor); + if (!cur.exists()) return ""; + const QStringList entries = + cur.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); + QString match; + for (const QString& entry : entries) { + if (entry.compare(part, Qt::CaseInsensitive) == 0) { + match = entry; + break; + } + } + if (match.isEmpty()) return ""; + cursor = cur.absoluteFilePath(match); + } + return QFileInfo::exists(cursor) ? cursor : QString(); +} + +QString TextureManager::resolvePath(const MOBase::IPluginGame* game, QString path) +{ + // NIF texture paths use Windows backslashes. On Linux, IOrganizer's + // virtual tree keys on forward-slash paths, so normalize here before + // lookup. BSA lookups keep the raw backslash form separately. + QString normalized = path; + normalized.replace('\\', '/'); + + // MO2's virtual tree may return a path that matches case-insensitively + // against its internal index but doesn't match the real on-disk case. + // Verify existence — if the returned path doesn't actually exist, do a + // case-insensitive walk against the containing mod directory to recover + // the correct case. + auto virtPath = m_MOInfo->resolvePath(normalized); + if (!virtPath.isEmpty()) { + if (QFileInfo::exists(virtPath)) { + return virtPath; + } + // Path wasn't valid — walk up to find the mod root, then re-resolve + // case-insensitively under it. We detect the mod root by looking for + // the "textures/" segment (NIF texture paths are always rooted at + // textures/). + const int texIdx = virtPath.indexOf("/textures/", 0, Qt::CaseInsensitive); + if (texIdx > 0) { + const QString modRoot = virtPath.left(texIdx); + const QString rel = virtPath.mid(texIdx + 1); + const QString fixed = resolveCaseInsensitive(modRoot, rel); + if (!fixed.isEmpty()) return fixed; + } + } + + auto dataDir = game->dataDirectory(); + auto dataPath = dataDir.absoluteFilePath(QDir::cleanPath(normalized)); + if (QFileInfo::exists(dataPath)) { + return dataPath; + } + + // Final fallback: case-insensitive walk under the game data directory. + return resolveCaseInsensitive(dataDir.absolutePath(), normalized); +} diff --git a/libs/preview_nif/src/TextureManager.h b/libs/preview_nif/src/TextureManager.h new file mode 100644 index 0000000..7ba1c9a --- /dev/null +++ b/libs/preview_nif/src/TextureManager.h @@ -0,0 +1,53 @@ +#pragma once + +#include <imoinfo.h> +#include <gli/gli.hpp> +#include <QOpenGLTexture> +#include <QSet> +#include <QStringList> +#include <map> + +class TextureManager +{ +public: + TextureManager(MOBase::IOrganizer* organizer); + ~TextureManager() = default; + TextureManager(const TextureManager&) = delete; + TextureManager(TextureManager&&) = delete; + TextureManager& operator=(const TextureManager&) = delete; + TextureManager& operator=(TextureManager&&) = delete; + + void cleanup(); + + QOpenGLTexture* getTexture(const std::string& texturePath); + QOpenGLTexture* getTexture(QString texturePath); + + QOpenGLTexture* getErrorTexture(); + QOpenGLTexture* getBlackTexture(); + QOpenGLTexture* getWhiteTexture(); + QOpenGLTexture* getFlatNormalTexture(); + +private: + QOpenGLTexture* loadTexture(QString texturePath); + QOpenGLTexture* makeTexture(const gli::texture& texture); + QOpenGLTexture* makeSolidColor(QVector4D color); + + QString resolvePath(const MOBase::IPluginGame* game, QString path); + + // Build priority-sorted BSA candidate list. Shared process-wide, keyed by + // the current instance's profile path so switching instances rebuilds. + // Conflict semantics: only active mods contribute, highest profile + // priority first, then vanilla archives. No plugin-attachment filter — + // matches BodySlide's "load all BSAs" approach which is what MO2's + // virtual data tree effectively does. + const QStringList& bsaCandidates(); + void rebuildBsaCandidates(); + + MOBase::IOrganizer* m_MOInfo; + QOpenGLTexture* m_ErrorTexture = nullptr; + QOpenGLTexture* m_BlackTexture = nullptr; + QOpenGLTexture* m_WhiteTexture = nullptr; + QOpenGLTexture* m_FlatNormalTexture = nullptr; + + std::map<std::wstring, QOpenGLTexture*> m_Textures; +}; diff --git a/libs/preview_nif/src/preview_nif_en.ts b/libs/preview_nif/src/preview_nif_en.ts new file mode 100644 index 0000000..10b8b07 --- /dev/null +++ b/libs/preview_nif/src/preview_nif_en.ts @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE TS> +<TS version="2.1" language="en_US"> +<context> + <name>NifWidget</name> + <message> + <location filename="NifWidget.cpp" line="92"/> + <source>OpenGL debug message: %1</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>PreviewNif</name> + <message> + <location filename="PreviewNif.cpp" line="57"/> + <source>Failed to load file: %1</source> + <translation type="unfinished"></translation> + </message> + <message> + <location filename="PreviewNif.cpp" line="87"/> + <source>Verts: %1 | Faces: %2 | Shapes: %3</source> + <translation type="unfinished"></translation> + </message> +</context> +<context> + <name>QObject</name> + <message> + <location filename="TextureManager.cpp" line="118"/> + <source>Failed to interface with managed game plugin</source> + <translation type="unfinished"></translation> + </message> +</context> +</TS> diff --git a/libs/preview_nif/src/previewnif.json b/libs/preview_nif/src/previewnif.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/libs/preview_nif/src/previewnif.json @@ -0,0 +1 @@ +{} |
