diff --git a/.gitignore b/.gitignore index e94b5b5f6..a001e38de 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ /Release /wadsrc_wad *.user +/build /debug /release */debug @@ -41,7 +42,11 @@ /jpeg-6b/x64/ /lzma/x64/ /zlib/x64/ +/build_vc2013_64bit /build_vc2015 /build_vc2015-32 /build_vc2015-64 /build +/llvm +/src/r_drawersasm.obj +/src/r_drawersasm.o diff --git a/CMakeLists.txt b/CMakeLists.txt index 607eb0054..b52e680dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required( VERSION 2.8.7 ) -project(ZDoom) +project(QZDoom) if( COMMAND cmake_policy ) if( POLICY CMP0011 ) @@ -122,7 +122,7 @@ IF( NOT CMAKE_BUILD_TYPE ) ENDIF() set( ZDOOM_OUTPUT_DIR ${CMAKE_BINARY_DIR} CACHE PATH "Directory where zdoom.pk3 and the executable will be created." ) -set( ZDOOM_EXE_NAME "zdoom" CACHE FILEPATH "Name of the executable to create." ) +set( ZDOOM_EXE_NAME "qzdoom" CACHE FILEPATH "Name of the executable to create" ) if( MSVC ) # Allow the user to use ZDOOM_OUTPUT_DIR as a single release point. # Use zdoom, zdoomd, zdoom64, and zdoomd64 for the binary names @@ -320,6 +320,8 @@ add_subdirectory( tools ) add_subdirectory( dumb ) add_subdirectory( gdtoa ) add_subdirectory( wadsrc ) +add_subdirectory( wadsrc_bm ) +add_subdirectory( wadsrc_lights ) add_subdirectory( src ) if( NOT WIN32 AND NOT APPLE ) diff --git a/docs/licenses/fxaa.txt b/docs/licenses/fxaa.txt new file mode 100644 index 000000000..fbd143c1d --- /dev/null +++ b/docs/licenses/fxaa.txt @@ -0,0 +1,33 @@ +//---------------------------------------------------------------------------------- +// File: es3-kepler\FXAA/FXAA3_11.h +// SDK Version: v3.00 +// Email: gameworks@nvidia.com +// Site: http://developer.nvidia.com/ +// +// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 COPYRIGHT OWNER OR +// CONTRIBUTORS 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/docs/licenses/lgpl.txt b/docs/licenses/lgpl.txt index 5ab7695ab..be2c3ea8e 100644 --- a/docs/licenses/lgpl.txt +++ b/docs/licenses/lgpl.txt @@ -1,504 +1,841 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - Preamble + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. + 0. Additional Definitions. - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. + 1. Exception to Section 3 of the GNU GPL. - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. + 2. Conveying Modified Versions. - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + 3. Object Code Incorporating Material from Library Header Files. - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) + b) Accompany the object code with a copy of the GNU GPL and this license + document. - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. + 4. Combined Works. - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the Library. - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - a) The modified work must itself be a software library. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. + Preamble - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. + The GNU General Public License is a free, copyleft license for +software and other kinds of works. - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) + 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. -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. + 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. -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. + 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. -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. + 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. - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. + 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. - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. + 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. - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. + 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. - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. + 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. - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. + The precise terms and conditions for copying, distribution and +modification follow. - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. + TERMS AND CONDITIONS - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. + 0. Definitions. - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) + "This License" refers to version 3 of the GNU General Public License. - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: + "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. - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) + 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. - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. + A "covered work" means either the unmodified Program or a work based +on the Program. - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. + 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. - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. + 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. - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. + 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. - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. + 1. Source Code. - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: + 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) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. + 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. - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. + 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. - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. + 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. - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with + 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. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + + 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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. +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. -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. + 13. Use with the GNU Affero General Public License. -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. + 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. -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. + 14. Revised Versions of this License. - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. + 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. - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. + Each version is given a distinguishing version number. If the +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. -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. + 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. - NO WARRANTY + 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. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + 15. Disclaimer of Warranty. - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. + 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. - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries + 16. Limitation of Liability. - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). + 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. - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. + 17. Interpretation of Sections 15 and 16. - + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Copyright (C) - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + 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 library is distributed in the hope that it will be useful, + 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 - Lesser General Public License for more details. + 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 Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/licenses/xBRZ.jpg b/docs/licenses/xBRZ.jpg new file mode 100644 index 000000000..ab8335391 Binary files /dev/null and b/docs/licenses/xBRZ.jpg differ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index aca24181f..2fb046924 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -13,6 +13,7 @@ include( CheckIncludeFile ) include( CheckIncludeFiles ) include( CheckLibraryExists ) include( FindPkgConfig ) +include( FindOpenGL ) if( ZD_CMAKE_COMPILER_IS_GNUCXX_COMPATIBLE ) option( NO_STRIP "Do not strip Release or MinSizeRel builds" ) @@ -254,6 +255,14 @@ else() endif() endif() +# Check if we have OpenGL + +if( NOT OPENGL_FOUND ) + message( FATAL_ERROR "OpenGL is required for building." ) +endif( NOT OPENGL_FOUND ) + +set( ZDOOM_LIBS ${ZDOOM_LIBS} ${OPENGL_LIBRARIES} ) +include_directories( ${OPENGL_INCLUDE_DIR} ) if( NOT NO_OPENAL ) find_package( OpenAL ) @@ -408,6 +417,22 @@ else() set( BACKPATCH 0 ) endif() +if( X64 ) + set( HAVE_MMX 1 ) +else( X64 ) + set( SAFE_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} ) + + if( ZD_CMAKE_COMPILER_IS_GNUCXX_COMPATIBLE ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmmx") + endif( ZD_CMAKE_COMPILER_IS_GNUCXX_COMPATIBLE ) + + CHECK_CXX_SOURCE_COMPILES("#include + int main(void) { __m64 v = _m_from_int(0); }" + HAVE_MMX) + + set( CMAKE_CXX_FLAGS ${SAFE_CMAKE_CXX_FLAGS} ) +endif( X64 ) + # Set up flags for GCC if( ZD_CMAKE_COMPILER_IS_GNUCXX_COMPATIBLE ) @@ -540,6 +565,20 @@ add_custom_target( revision_check ALL WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} DEPENDS updaterevision ) +# Run drawer codegen tool + +if ( WIN32 ) + add_custom_target( drawergen_target ALL + COMMAND drawergen src/r_drawersasm.obj + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS drawergen ) +else() + add_custom_target( drawergen_target ALL + COMMAND drawergen src/r_drawersasm.o + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + DEPENDS drawergen ) +endif() + # Libraries ZDoom needs message( STATUS "Fluid synth libs: ${FLUIDSYNTH_LIBRARIES}" ) @@ -584,6 +623,7 @@ set( PLAT_WIN32_SOURCES win32/i_system.cpp win32/i_specialpaths.cpp win32/st_start.cpp + win32/win32gliface.cpp win32/win32video.cpp ) set( PLAT_POSIX_SOURCES posix/i_cd.cpp @@ -599,6 +639,7 @@ set( PLAT_SDL_SOURCES posix/sdl/i_system.cpp posix/sdl/i_timer.cpp posix/sdl/sdlvideo.cpp + posix/sdl/sdlglvideo.cpp posix/sdl/st_start.cpp ) set( PLAT_UNIX_SOURCES posix/unix/i_specialpaths.cpp @@ -724,6 +765,21 @@ file( GLOB HEADER_FILES scripting/zscript/*.h scripting/vm/*.h xlat/*.h + gl/*.h + gl/api/*.h + gl/data/*.h + gl/dynlights/*.h + gl/hqnx/*.h + gl/hqnx_asm/*.h + gl/xbr/*.h + gl/models/*.h + gl/renderer/*.h + gl/scene/*.h + gl/stereo3d/*.h + gl/shaders/*.h + gl/system/*.h + gl/textures/*.h + gl/utility/*.h *.h ) @@ -744,17 +800,33 @@ set( NOT_COMPILED_SOURCE_FILES set( FASTMATH_PCH_SOURCES r_swrenderer.cpp + r_poly.cpp + r_poly_scene.cpp + r_poly_portal.cpp + r_poly_cull.cpp + r_poly_decal.cpp + r_poly_particle.cpp + r_poly_plane.cpp + r_poly_playersprite.cpp + r_poly_wall.cpp + r_poly_wallsprite.cpp + r_poly_sprite.cpp + r_poly_sky.cpp + r_poly_triangle.cpp + r_poly_intersection.cpp r_3dfloors.cpp r_bsp.cpp r_draw.cpp r_draw_pal.cpp - r_drawt_pal.cpp + r_draw_rgba.cpp + r_drawers.cpp r_thread.cpp r_main.cpp r_plane.cpp r_segs.cpp r_sky.cpp r_things.cpp + r_voxel.cpp r_walldraw.cpp s_advsound.cpp s_environment.cpp @@ -835,6 +907,92 @@ set( FASTMATH_SOURCES sound/sndfile_decoder.cpp sound/music_pseudo_mididevice.cpp wildmidi/wildmidi_lib.cpp + gl/compatibility/gl_20.cpp + gl/data/gl_data.cpp + gl/data/gl_portaldata.cpp + gl/data/gl_setup.cpp + gl/data/gl_matrix.cpp + gl/data/gl_vertexbuffer.cpp + gl/dynlights/a_dynlight.cpp + gl/utility/gl_clock.cpp + gl/utility/gl_cycler.cpp + gl/utility/gl_geometric.cpp + gl/renderer/gl_2ddrawer.cpp + gl/renderer/gl_quaddrawer.cpp + gl/renderer/gl_renderer.cpp + gl/renderer/gl_renderstate.cpp + gl/renderer/gl_renderbuffers.cpp + gl/renderer/gl_lightdata.cpp + gl/renderer/gl_postprocess.cpp + gl/renderer/gl_postprocessstate.cpp + gl/hqnx/init.cpp + gl/hqnx/hq2x.cpp + gl/hqnx/hq3x.cpp + gl/hqnx/hq4x.cpp + gl/xbr/xbrz.cpp + gl/xbr/xbrz_old.cpp + gl/textures/gl_hwtexture.cpp + gl/textures/gl_texture.cpp + gl/textures/gl_material.cpp + gl/textures/gl_hirestex.cpp + gl/textures/gl_bitmap.cpp + gl/textures/gl_samplers.cpp + gl/textures/gl_translate.cpp + gl/textures/gl_hqresize.cpp + gl/textures/gl_skyboxtexture.cpp + gl/scene/gl_bsp.cpp + gl/scene/gl_fakeflat.cpp + gl/scene/gl_clipper.cpp + gl/scene/gl_decal.cpp + gl/scene/gl_drawinfo.cpp + gl/scene/gl_flats.cpp + gl/scene/gl_walls.cpp + gl/scene/gl_sprite.cpp + gl/scene/gl_skydome.cpp + gl/scene/gl_renderhacks.cpp + gl/scene/gl_weapon.cpp + gl/scene/gl_scene.cpp + gl/scene/gl_sky.cpp + gl/scene/gl_portal.cpp + gl/scene/gl_walls_draw.cpp + gl/scene/gl_vertex.cpp + gl/scene/gl_spritelight.cpp + gl/stereo3d/gl_stereo3d.cpp + gl/stereo3d/gl_stereo_cvars.cpp + gl/stereo3d/gl_stereo_leftright.cpp + gl/stereo3d/scoped_view_shifter.cpp + gl/stereo3d/gl_anaglyph.cpp + gl/stereo3d/gl_quadstereo.cpp + gl/stereo3d/gl_sidebyside3d.cpp + gl/stereo3d/gl_interleaved3d.cpp + gl/dynlights/gl_dynlight.cpp + gl/dynlights/gl_glow.cpp + gl/dynlights/gl_dynlight1.cpp + gl/dynlights/gl_lightbuffer.cpp + gl/shaders/gl_shader.cpp + gl/shaders/gl_texshader.cpp + gl/shaders/gl_shaderprogram.cpp + gl/shaders/gl_presentshader.cpp + gl/shaders/gl_present3dRowshader.cpp + gl/shaders/gl_bloomshader.cpp + gl/shaders/gl_ambientshader.cpp + gl/shaders/gl_blurshader.cpp + gl/shaders/gl_colormapshader.cpp + gl/shaders/gl_tonemapshader.cpp + gl/shaders/gl_lensshader.cpp + gl/shaders/gl_fxaashader.cpp + gl/system/gl_interface.cpp + gl/system/gl_framebuffer.cpp + gl/system/gl_swframebuffer.cpp + gl/system/gl_swwipe.cpp + gl/system/gl_debug.cpp + gl/system/gl_menu.cpp + gl/system/gl_wipe.cpp + gl/system/gl_load.c + gl/models/gl_models_md3.cpp + gl/models/gl_models_md2.cpp + gl/models/gl_models.cpp + gl/models/gl_voxels.cpp ) set (PCH_SOURCES @@ -929,6 +1087,7 @@ set (PCH_SOURCES p_mobj.cpp p_pillar.cpp p_plats.cpp + p_portals.cpp p_pspr.cpp p_pusher.cpp p_saveg.cpp @@ -1069,6 +1228,16 @@ set (PCH_SOURCES ) enable_precompiled_headers( g_pch.h PCH_SOURCES ) +if ( WIN32 ) + set (CODEGENOBJ_SOURCES + r_drawersasm.obj + ) +else() + set (CODEGENOBJ_SOURCES + r_drawersasm.o + ) +endif() + add_executable( zdoom WIN32 MACOSX_BUNDLE ${HEADER_FILES} ${NOT_COMPILED_SOURCE_FILES} @@ -1099,14 +1268,21 @@ add_executable( zdoom WIN32 MACOSX_BUNDLE math/tanh.c math/fastsin.cpp zzautozend.cpp + ${CMAKE_BINARY_DIR}/src/${CODEGENOBJ_SOURCES} ) +set_source_files_properties( ${CODEGENOBJ_SOURCES} PROPERTIES EXTERNAL_OBJECT true GENERATED true) + set_source_files_properties( ${FASTMATH_SOURCES} PROPERTIES COMPILE_FLAGS ${ZD_FASTMATH_FLAG} ) set_source_files_properties( xlat/parse_xlat.cpp PROPERTIES OBJECT_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/xlat_parser.c" ) set_source_files_properties( sc_man.cpp PROPERTIES OBJECT_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/sc_man_scanner.h" ) set_source_files_properties( ${NOT_COMPILED_SOURCE_FILES} PROPERTIES HEADER_FILE_ONLY TRUE ) if ( WIN32 ) set_source_files_properties( win32/fb_d3d9.cpp win32/fb_d3d9_wipe.cpp PROPERTIES COMPILE_FLAGS ${ZD_FASTMATH_FLAG} ) + + # Supress C4244: 'initializing': conversion from '__int64' to 'unsigned int', possible loss of data + # For some reason using #pragma warning(disable: 4244) is not working.. + set_source_files_properties( ${PCH_SOURCES} PROPERTIES COMPILE_FLAGS /wd4244 ) endif() @@ -1116,6 +1292,7 @@ if(${CMAKE_SYSTEM_NAME} STREQUAL "SunOS") endif() target_link_libraries( zdoom ${ZDOOM_LIBS} gdtoa dumb lzma ) + include_directories( . g_strife g_shared @@ -1133,7 +1310,7 @@ include_directories( . ${CMAKE_BINARY_DIR}/gdtoa ${SYSTEM_SOURCES_DIR} ) -add_dependencies( zdoom revision_check ) +add_dependencies( zdoom revision_check drawergen_target ) # Due to some quirks, we need to do this in this order if( NOT ZDOOM_OUTPUT_OLDSTYLE ) @@ -1250,6 +1427,20 @@ source_group("Games\\Strife Game" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DI source_group("Intermission" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/intermission/.+") source_group("Inventory" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/g_inventory/.+") source_group("Menu" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/menu/.+") +source_group("OpenGL Renderer" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/.+") +source_group("OpenGL Renderer\\Data" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/data/.+") +source_group("OpenGL Renderer\\Dynamic Lights" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/dynlights/.+") +source_group("OpenGL Renderer\\HQ Resize" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/hqnx/.+") +source_group("OpenGL Renderer\\HQ Resize MMX version" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/hqnx_asm/.+") +source_group("OpenGL Renderer\\XBRZ" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/hqnx_asm/.+") +source_group("OpenGL Renderer\\Models" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/models/.+") +source_group("OpenGL Renderer\\Renderer" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/renderer/.+") +source_group("OpenGL Renderer\\Scene" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/scene/.+") +source_group("OpenGL Renderer\\Stereo3D" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/stereo3d/.+") +source_group("OpenGL Renderer\\Shaders" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/shaders/.+") +source_group("OpenGL Renderer\\System" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/system/.+") +source_group("OpenGL Renderer\\Textures" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/textures/.+") +source_group("OpenGL Renderer\\Utilities" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/gl/utility/.+") source_group("Render Core\\Render Headers" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_.+\\.h$") source_group("Render Core\\Render Sources" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_.+\\.cpp$") source_group("Render Data\\Resource Headers" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_data/.+\\.h$") diff --git a/src/actor.h b/src/actor.h index 364bb7098..5445c92be 100644 --- a/src/actor.h +++ b/src/actor.h @@ -1439,6 +1439,14 @@ public: int ApplyDamageFactor(FName damagetype, int damage) const; int GetModifiedDamage(FName damagetype, int damage, bool passive); + + // begin of GZDoom specific additions + TArray > dynamiclights; + void * lightassociations; + bool hasmodel; + // end of GZDoom specific additions + + size_t PropagateMark(); }; class FActorIterator diff --git a/src/c_console.cpp b/src/c_console.cpp index faeec0a68..0e9b94996 100644 --- a/src/c_console.cpp +++ b/src/c_console.cpp @@ -159,10 +159,14 @@ int active_con_scale() int scale = con_scale; if (scale <= 0) { - scale = CleanXfac - 1; - if (scale <= 0) + scale = uiscale; + if (scale == 0) { - scale = 1; + scale = CleanXfac - 1; + if (scale <= 0) + { + scale = 1; + } } } return scale; diff --git a/src/d_main.cpp b/src/d_main.cpp index 04ba34cbb..1ea2d2707 100644 --- a/src/d_main.cpp +++ b/src/d_main.cpp @@ -205,6 +205,11 @@ CUSTOM_CVAR (String, vid_cursor, "None", CVAR_ARCHIVE | CVAR_NOINITCALL) } } +// Controlled by startup dialog +CVAR (Bool, disableautoload, false, CVAR_ARCHIVE | CVAR_NOINITCALL | CVAR_GLOBALCONFIG) +CVAR (Bool, autoloadbrightmaps, false, CVAR_ARCHIVE | CVAR_NOINITCALL | CVAR_GLOBALCONFIG) +CVAR (Bool, autoloadlights, false, CVAR_ARCHIVE | CVAR_NOINITCALL | CVAR_GLOBALCONFIG) + bool wantToRestart; bool DrawFSHUD; // [RH] Draw fullscreen HUD? TArray allwads; @@ -2038,7 +2043,24 @@ static void AddAutoloadFiles(const char *autoname) { LumpFilterIWAD.Format("%s.", autoname); // The '.' is appened to simplify parsing the string - if (!(gameinfo.flags & GI_SHAREWARE) && !Args->CheckParm("-noautoload")) + // [SP] Dialog reaction - load lights.pk3 and brightmaps.pk3 based on user choices + if (!(gameinfo.flags & GI_SHAREWARE)) + { + if (autoloadlights) + { + const char *lightswad = BaseFileSearch ("lights.pk3", NULL); + if (lightswad) + D_AddFile (allwads, lightswad); + } + if (autoloadbrightmaps) + { + const char *bmwad = BaseFileSearch ("brightmaps.pk3", NULL); + if (bmwad) + D_AddFile (allwads, bmwad); + } + } + + if (!(gameinfo.flags & GI_SHAREWARE) && !Args->CheckParm("-noautoload") && !disableautoload) { FString file; diff --git a/src/f_wipe.cpp b/src/f_wipe.cpp index a3ceb8d50..1fb7c982b 100644 --- a/src/f_wipe.cpp +++ b/src/f_wipe.cpp @@ -28,6 +28,9 @@ #include "f_wipe.h" #include "c_cvars.h" #include "templates.h" +#include "v_palette.h" + +EXTERN_CVAR(Bool, r_blendmethod) // // SCREEN WIPE PACKAGE @@ -280,39 +283,80 @@ bool wipe_doBurn (int ticks) fromold = (BYTE *)wipe_scr_start; fromnew = (BYTE *)wipe_scr_end; - for (y = 0, firey = 0; y < SCREENHEIGHT; y++, firey += ystep) + if (!r_blendmethod) { - for (x = 0, firex = 0; x < SCREENWIDTH; x++, firex += xstep) + for (y = 0, firey = 0; y < SCREENHEIGHT; y++, firey += ystep) { - int fglevel; + for (x = 0, firex = 0; x < SCREENWIDTH; x++, firex += xstep) + { + int fglevel; - fglevel = burnarray[(firex>>SHIFT)+(firey>>SHIFT)*FIREWIDTH] / 2; - if (fglevel >= 63) - { - to[x] = fromnew[x]; - } - else if (fglevel == 0) - { - to[x] = fromold[x]; - done = false; - } - else - { - int bglevel = 64-fglevel; - DWORD *fg2rgb = Col2RGB8[fglevel]; - DWORD *bg2rgb = Col2RGB8[bglevel]; - DWORD fg = fg2rgb[fromnew[x]]; - DWORD bg = bg2rgb[fromold[x]]; - fg = (fg+bg) | 0x1f07c1f; - to[x] = RGB32k.All[fg & (fg>>15)]; - done = false; + fglevel = burnarray[(firex>>SHIFT)+(firey>>SHIFT)*FIREWIDTH] / 2; + if (fglevel >= 63) + { + to[x] = fromnew[x]; + } + else if (fglevel == 0) + { + to[x] = fromold[x]; + done = false; + } + else + { + int bglevel = 64-fglevel; + DWORD *fg2rgb = Col2RGB8[fglevel]; + DWORD *bg2rgb = Col2RGB8[bglevel]; + DWORD fg = fg2rgb[fromnew[x]]; + DWORD bg = bg2rgb[fromold[x]]; + fg = (fg+bg) | 0x1f07c1f; + to[x] = RGB32k.All[fg & (fg>>15)]; + done = false; + } } + fromold += SCREENWIDTH; + fromnew += SCREENWIDTH; + to += SCREENPITCH; } - fromold += SCREENWIDTH; - fromnew += SCREENWIDTH; - to += SCREENPITCH; - } + } + else + { + for (y = 0, firey = 0; y < SCREENHEIGHT; y++, firey += ystep) + { + for (x = 0, firex = 0; x < SCREENWIDTH; x++, firex += xstep) + { + int fglevel; + + fglevel = burnarray[(firex>>SHIFT)+(firey>>SHIFT)*FIREWIDTH] / 2; + if (fglevel >= 63) + { + to[x] = fromnew[x]; + } + else if (fglevel == 0) + { + to[x] = fromold[x]; + done = false; + } + else + { + int bglevel = 64-fglevel; + + const PalEntry* pal = GPalette.BaseColors; + + DWORD fg = fromnew[x]; + DWORD bg = fromold[x]; + int r = MIN((pal[fg].r * fglevel + pal[bg].r * bglevel) >> 8, 63); + int g = MIN((pal[fg].g * fglevel + pal[bg].g * bglevel) >> 8, 63); + int b = MIN((pal[fg].b * fglevel + pal[bg].b * bglevel) >> 8, 63); + to[x] = RGB256k.RGB[r][g][b]; + done = false; + } + } + fromold += SCREENWIDTH; + fromnew += SCREENWIDTH; + to += SCREENPITCH; + } + } return done || (burntime > 40); } @@ -347,19 +391,41 @@ bool wipe_doFade (int ticks) BYTE *fromnew = (BYTE *)wipe_scr_end; BYTE *fromold = (BYTE *)wipe_scr_start; BYTE *to = screen->GetBuffer(); + const PalEntry *pal = GPalette.BaseColors; - for (y = 0; y < SCREENHEIGHT; y++) + if (!r_blendmethod) { - for (x = 0; x < SCREENWIDTH; x++) + for (y = 0; y < SCREENHEIGHT; y++) { - DWORD fg = fg2rgb[fromnew[x]]; - DWORD bg = bg2rgb[fromold[x]]; - fg = (fg+bg) | 0x1f07c1f; - to[x] = RGB32k.All[fg & (fg>>15)]; + for (x = 0; x < SCREENWIDTH; x++) + { + DWORD fg = fg2rgb[fromnew[x]]; + DWORD bg = bg2rgb[fromold[x]]; + fg = (fg+bg) | 0x1f07c1f; + to[x] = RGB32k.All[fg & (fg>>15)]; + } + fromnew += SCREENWIDTH; + fromold += SCREENWIDTH; + to += SCREENPITCH; + } + } + else + { + for (y = 0; y < SCREENHEIGHT; y++) + { + for (x = 0; x < SCREENWIDTH; x++) + { + DWORD fg = fromnew[x]; + DWORD bg = fromold[x]; + int r = MIN((pal[fg].r * (64-bglevel) + pal[bg].r * bglevel) >> 8, 63); + int g = MIN((pal[fg].g * (64-bglevel) + pal[bg].g * bglevel) >> 8, 63); + int b = MIN((pal[fg].b * (64-bglevel) + pal[bg].b * bglevel) >> 8, 63); + to[x] = RGB256k.RGB[r][g][b]; + } + fromnew += SCREENWIDTH; + fromold += SCREENWIDTH; + to += SCREENPITCH; } - fromnew += SCREENWIDTH; - fromold += SCREENWIDTH; - to += SCREENPITCH; } } return false; @@ -382,6 +448,9 @@ static bool (*wipes[])(int) = // Returns true if the wipe should be performed. bool wipe_StartScreen (int type) { + if (screen->IsBgra()) + return false; + CurrentWipeType = clamp(type, 0, wipe_NUMWIPES - 1); if (CurrentWipeType) @@ -395,11 +464,15 @@ bool wipe_StartScreen (int type) void wipe_EndScreen (void) { + if (screen->IsBgra()) + return; + if (CurrentWipeType) { wipe_scr_end = new short[SCREENWIDTH * SCREENHEIGHT / 2]; screen->GetBlock (0, 0, SCREENWIDTH, SCREENHEIGHT, (BYTE *)wipe_scr_end); screen->DrawBlock (0, 0, SCREENWIDTH, SCREENHEIGHT, (BYTE *)wipe_scr_start); // restore start scr. + // Initialize the wipe (*wipes[(CurrentWipeType-1)*3])(0); } @@ -410,6 +483,9 @@ bool wipe_ScreenWipe (int ticks) { bool rc; + if (screen->IsBgra()) + return true; + if (CurrentWipeType == wipe_None) return true; @@ -423,6 +499,9 @@ bool wipe_ScreenWipe (int ticks) // Final things for the wipe void wipe_Cleanup() { + if (screen->IsBgra()) + return; + if (wipe_scr_start != NULL) { delete[] wipe_scr_start; diff --git a/src/g_inventory/a_artifacts.cpp b/src/g_inventory/a_artifacts.cpp index 4afe74f1f..572022f66 100644 --- a/src/g_inventory/a_artifacts.cpp +++ b/src/g_inventory/a_artifacts.cpp @@ -735,7 +735,8 @@ int APowerInvisibility::AlterWeaponSprite (visstyle_t *vis) if ((vis->Alpha < 0.25f && special1 > 0) || (vis->Alpha == 0)) { vis->Alpha = clamp((1.f - float(Strength/100)), 0.f, 1.f); - vis->colormap = SpecialColormaps[INVERSECOLORMAP].Colormap; + vis->BaseColormap = &SpecialColormaps[INVERSECOLORMAP]; + vis->ColormapNum = 0; } return -1; // This item is valid so another one shouldn't reset the translucency } diff --git a/src/g_level.cpp b/src/g_level.cpp index 321810589..f8ccd13be 100644 --- a/src/g_level.cpp +++ b/src/g_level.cpp @@ -1345,7 +1345,7 @@ void G_InitLevelLocals () level_info_t *info; BaseBlendA = 0.0f; // Remove underwater blend effect, if any - NormalLight.Maps = realcolormaps; + NormalLight.Maps = realcolormaps.Maps; // [BB] Instead of just setting the color, we also have to reset Desaturate and build the lights. NormalLight.ChangeColor (PalEntry (255, 255, 255), 0); @@ -1373,6 +1373,7 @@ void G_InitLevelLocals () R_SetDefaultColormap (info->FadeTable); if (strnicmp (info->FadeTable, "COLORMAP", 8) != 0) { + level.fadeto = 0xff939393; //[SP] Hexen True-color compatibility, just use gray. level.flags |= LEVEL_HASFADETABLE; } /* diff --git a/src/g_strife/strife_sbar.cpp b/src/g_strife/strife_sbar.cpp index 46dd63ff7..ccf17f8f1 100644 --- a/src/g_strife/strife_sbar.cpp +++ b/src/g_strife/strife_sbar.cpp @@ -37,7 +37,6 @@ public: const BYTE *GetColumn (unsigned int column, const Span **spans_out); const BYTE *GetPixels (); bool CheckModified (); - void Unload (); void SetVial (int level); @@ -92,10 +91,6 @@ bool FHealthBar::CheckModified () return NeedRefresh; } -void FHealthBar::Unload () -{ -} - const BYTE *FHealthBar::GetColumn (unsigned int column, const Span **spans_out) { if (NeedRefresh) diff --git a/src/gl/compatibility/gl_20.cpp b/src/gl/compatibility/gl_20.cpp new file mode 100644 index 000000000..348663929 --- /dev/null +++ b/src/gl/compatibility/gl_20.cpp @@ -0,0 +1,844 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_20.cpp +** +** Fallback code for ancient hardware +** This file collects everything larger that is only needed for +** OpenGL 2.0/no shader compatibility. +** +*/ + +#include "gl/system/gl_system.h" +#include "menu/menu.h" +#include "tarray.h" +#include "doomtype.h" +#include "m_argv.h" +#include "zstring.h" +#include "version.h" +#include "i_system.h" +#include "v_text.h" +#include "r_utility.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/utility/gl_geometric.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/data/gl_vertexbuffer.h" + + +CVAR(Bool, gl_lights_additive, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + +//========================================================================== +// +// Do some tinkering with the menus so that certain options only appear +// when they are actually valid. +// +//========================================================================== + +void gl_PatchMenu() +{ + // Radial fog and Doom lighting are not available without full shader support. + + FOptionValues **opt = OptionValues.CheckKey("LightingModes"); + if (opt != NULL) + { + for(int i = (*opt)->mValues.Size()-1; i>=0; i--) + { + // Delete 'Doom' lighting mode + if ((*opt)->mValues[i].Value == 2.0 || (*opt)->mValues[i].Value == 8.0) + { + (*opt)->mValues.Delete(i); + } + } + } + + opt = OptionValues.CheckKey("FogMode"); + if (opt != NULL) + { + for(int i = (*opt)->mValues.Size()-1; i>=0; i--) + { + // Delete 'Radial' fog mode + if ((*opt)->mValues[i].Value == 2.0) + { + (*opt)->mValues.Delete(i); + } + } + } + + // disable features that don't work without shaders. + if (gl_lightmode == 2 || gl_lightmode == 8) gl_lightmode = 3; + if (gl_fogmode == 2) gl_fogmode = 1; + + // todo: remove more unsupported stuff like postprocessing options. +} + + +//========================================================================== +// +// +// +//========================================================================== + +void gl_SetTextureMode(int type) +{ + static float white[] = {1.f,1.f,1.f,1.f}; + + if (type == TM_MASK) + { + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA); + } + else if (type == TM_OPAQUE) + { + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + } + else if (type == TM_INVERSE) + { + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_ONE_MINUS_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA); + } + else if (type == TM_INVERTOPAQUE) + { + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_ONE_MINUS_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); + } + else // if (type == TM_MODULATE) + { + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +static int ffTextureMode; +static bool ffTextureEnabled; +static bool ffFogEnabled; +static PalEntry ffFogColor; +static int ffSpecialEffect; +static float ffFogDensity; +static bool currentTextureMatrixState; +static bool currentModelMatrixState; + +void FRenderState::ApplyFixedFunction() +{ + if (mTextureMode != ffTextureMode) + { + ffTextureMode = mTextureMode; + if (ffTextureMode == TM_CLAMPY) ffTextureMode = TM_MODULATE; // this cannot be replicated. Too bad if it creates visual artifacts + gl_SetTextureMode(ffTextureMode); + } + if (mTextureEnabled != ffTextureEnabled) + { + if ((ffTextureEnabled = mTextureEnabled)) glEnable(GL_TEXTURE_2D); + else glDisable(GL_TEXTURE_2D); + } + if (mFogEnabled != ffFogEnabled) + { + if ((ffFogEnabled = mFogEnabled)) + { + glEnable(GL_FOG); + } + else glDisable(GL_FOG); + } + if (mFogEnabled) + { + if (ffFogColor != mFogColor) + { + ffFogColor = mFogColor; + GLfloat FogColor[4] = { mFogColor.r / 255.0f,mFogColor.g / 255.0f,mFogColor.b / 255.0f,0.0f }; + glFogfv(GL_FOG_COLOR, FogColor); + } + if (ffFogDensity != mLightParms[2]) + { + glFogf(GL_FOG_DENSITY, mLightParms[2] * -0.6931471f); // = 1/log(2) + ffFogDensity = mLightParms[2]; + } + } + if (mSpecialEffect != ffSpecialEffect) + { + switch (ffSpecialEffect) + { + case EFF_SPHEREMAP: + glDisable(GL_TEXTURE_GEN_T); + glDisable(GL_TEXTURE_GEN_S); + + default: + break; + } + switch (mSpecialEffect) + { + case EFF_SPHEREMAP: + // Use sphere mapping for this + glEnable(GL_TEXTURE_GEN_T); + glEnable(GL_TEXTURE_GEN_S); + glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); + glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); + break; + + default: + break; + } + ffSpecialEffect = mSpecialEffect; + } + + FStateVec4 col = mColor; + + col.vec[0] += mDynColor.vec[0]; + col.vec[1] += mDynColor.vec[1]; + col.vec[2] += mDynColor.vec[2]; + col.vec[0] = clamp(col.vec[0], 0.f, 1.f); + + col.vec[0] = clamp(col.vec[0], 0.f, 1.f); + col.vec[1] = clamp(col.vec[1], 0.f, 1.f); + col.vec[2] = clamp(col.vec[2], 0.f, 1.f); + col.vec[3] = clamp(col.vec[3], 0.f, 1.f); + + col.vec[0] *= (mObjectColor.r / 255.f); + col.vec[1] *= (mObjectColor.g / 255.f); + col.vec[2] *= (mObjectColor.b / 255.f); + col.vec[3] *= (mObjectColor.a / 255.f); + glColor4fv(col.vec); + + glEnable(GL_BLEND); + if (mAlphaThreshold > 0) + { + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, mAlphaThreshold * col.vec[3]); + } + else + { + glDisable(GL_ALPHA_TEST); + } + + if (mTextureMatrixEnabled) + { + glMatrixMode(GL_TEXTURE); + glLoadMatrixf(mTextureMatrix.get()); + currentTextureMatrixState = true; + } + else if (currentTextureMatrixState) + { + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + currentTextureMatrixState = false; + } + + if (mModelMatrixEnabled) + { + VSMatrix mult = mViewMatrix; + mult.multMatrix(mModelMatrix); + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(mult.get()); + currentModelMatrixState = true; + } + else if (currentModelMatrixState) + { + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(mViewMatrix.get()); + currentModelMatrixState = false; + } + + +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_FillScreen(); + +void FRenderState::DrawColormapOverlay() +{ + float r, g, b; + if (mColormapState > CM_DEFAULT && mColormapState < CM_MAXCOLORMAP) + { + FSpecialColormap *scm = &SpecialColormaps[gl_fixedcolormap - CM_FIRSTSPECIALCOLORMAP]; + float m[] = { scm->ColorizeEnd[0] - scm->ColorizeStart[0], + scm->ColorizeEnd[1] - scm->ColorizeStart[1], scm->ColorizeEnd[2] - scm->ColorizeStart[2], 0.f }; + + if (m[0] < 0 && m[1] < 0 && m[2] < 0) + { + gl_RenderState.SetColor(1, 1, 1, 1); + gl_RenderState.BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); + gl_FillScreen(); + + r = scm->ColorizeStart[0]; + g = scm->ColorizeStart[1]; + b = scm->ColorizeStart[2]; + } + else + { + r = scm->ColorizeEnd[0]; + g = scm->ColorizeEnd[1]; + b = scm->ColorizeEnd[2]; + } + } + else if (mColormapState == CM_LITE) + { + if (gl_enhanced_nightvision) + { + r = 0.375f, g = 1.0f, b = 0.375f; + } + else + { + return; + } + } + else if (mColormapState >= CM_TORCH) + { + int flicker = mColormapState - CM_TORCH; + r = (0.8f + (7 - flicker) / 70.0f); + if (r > 1.0f) r = 1.0f; + b = g = r; + if (gl_enhanced_nightvision) b = g * 0.75f; + } + else return; + + gl_RenderState.SetColor(r, g, b, 1.f); + gl_RenderState.BlendFunc(GL_DST_COLOR, GL_ZERO); + gl_FillScreen(); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +} + +//========================================================================== +// +// Sets up the parameters to render one dynamic light onto one plane +// +//========================================================================== + +bool gl_SetupLight(int group, Plane & p, ADynamicLight * light, Vector & nearPt, Vector & up, Vector & right, + float & scale, bool checkside, bool additive) +{ + Vector fn, pos; + + DVector3 lpos = light->PosRelative(group); + + float dist = fabsf(p.DistToPoint(lpos.X, lpos.Z, lpos.Y)); + float radius = light->GetRadius(); + + if (radius <= 0.f) return false; + if (dist > radius) return false; + if (checkside && gl_lights_checkside && p.PointOnSide(lpos.X, lpos.Z, lpos.Y)) + { + return false; + } + if (!light->visibletoplayer) + { + return false; + } + + scale = 1.0f / ((2.f * radius) - dist); + + // project light position onto plane (find closest point on plane) + + + pos.Set(lpos.X, lpos.Z, lpos.Y); + fn = p.Normal(); + fn.GetRightUp(right, up); + +#ifdef _MSC_VER + nearPt = pos + fn * dist; +#else + Vector tmpVec = fn * dist; + nearPt = pos + tmpVec; +#endif + + float cs = 1.0f - (dist / radius); + if (additive) cs *= 0.2f; // otherwise the light gets too strong. + float r = light->GetRed() / 255.0f * cs; + float g = light->GetGreen() / 255.0f * cs; + float b = light->GetBlue() / 255.0f * cs; + + if (light->IsSubtractive()) + { + Vector v; + + gl_RenderState.BlendEquation(GL_FUNC_REVERSE_SUBTRACT); + v.Set(r, g, b); + r = v.Length() - r; + g = v.Length() - g; + b = v.Length() - b; + } + else + { + gl_RenderState.BlendEquation(GL_FUNC_ADD); + } + gl_RenderState.SetColor(r, g, b); + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool gl_SetupLightTexture() +{ + if (GLRenderer->gllight == nullptr) return false; + FMaterial * pat = FMaterial::ValidateTexture(GLRenderer->gllight, false); + gl_RenderState.SetMaterial(pat, CLAMP_XY_NOMIP, 0, -1, false); + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool GLWall::PutWallCompat(int passflag) +{ + static int list_indices[2][2] = + { { GLLDL_WALLS_PLAIN, GLLDL_WALLS_FOG },{ GLLDL_WALLS_MASKED, GLLDL_WALLS_FOGMASKED } }; + + // are lights possible? + if (gl_fixedcolormap != CM_DEFAULT || !gl_lights || seg->sidedef == nullptr || type == RENDERWALL_M2SNF || !gltexture) return false; + + // multipassing these is problematic. + if ((flags&GLWF_SKYHACK && type == RENDERWALL_M2S)) return false; + + // Any lights affecting this wall? + if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + if (seg->sidedef->lighthead == nullptr) return false; + } + else if (sub) + { + if (sub->lighthead == nullptr) return false; + } + + bool foggy = gl_CheckFog(&Colormap, lightlevel) || (level.flags&LEVEL_HASFADETABLE) || gl_lights_additive; + bool masked = passflag == 2 && gltexture->isMasked(); + + int list = list_indices[masked][foggy]; + gl_drawinfo->dldrawlists[list].AddWall(this); + return true; + +} + +//========================================================================== +// +// +// +//========================================================================== + +bool GLFlat::PutFlatCompat(bool fog) +{ + // are lights possible? + if (gl_fixedcolormap != CM_DEFAULT || !gl_lights || !gltexture || renderstyle != STYLE_Translucent || alpha < 1.f - FLT_EPSILON || sector->lighthead == NULL) return false; + + static int list_indices[2][2] = + { { GLLDL_FLATS_PLAIN, GLLDL_FLATS_FOG },{ GLLDL_FLATS_MASKED, GLLDL_FLATS_FOGMASKED } }; + + bool masked = gltexture->isMasked() && ((renderflags&SSRF_RENDER3DPLANES) || stack); + bool foggy = gl_CheckFog(&Colormap, lightlevel) || (level.flags&LEVEL_HASFADETABLE) || gl_lights_additive; + + + int list = list_indices[masked][foggy]; + gl_drawinfo->dldrawlists[list].AddFlat(this); + return true; +} + + +//========================================================================== +// +// Fog boundary without any shader support +// +//========================================================================== + +void GLWall::RenderFogBoundaryCompat() +{ + // without shaders some approximation is needed. This won't look as good + // as the shader version but it's an acceptable compromise. + float fogdensity = gl_GetFogDensity(lightlevel, Colormap.FadeColor); + + float dist1 = Dist2(ViewPos.X, ViewPos.Y, glseg.x1, glseg.y1); + float dist2 = Dist2(ViewPos.X, ViewPos.Y, glseg.x2, glseg.y2); + + // these values were determined by trial and error and are scale dependent! + float fogd1 = (0.95f - exp(-fogdensity*dist1 / 62500.f)) * 1.05f; + float fogd2 = (0.95f - exp(-fogdensity*dist2 / 62500.f)) * 1.05f; + + float fc[4] = { Colormap.FadeColor.r / 255.0f,Colormap.FadeColor.g / 255.0f,Colormap.FadeColor.b / 255.0f,fogd2 }; + + gl_RenderState.EnableTexture(false); + gl_RenderState.EnableFog(false); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0); + gl_RenderState.Apply(); + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + glDepthFunc(GL_LEQUAL); + glColor4f(fc[0], fc[1], fc[2], fogd1); + glBegin(GL_TRIANGLE_FAN); + glTexCoord2f(tcs[LOLFT].u, tcs[LOLFT].v); + glVertex3f(glseg.x1, zbottom[0], glseg.y1); + glTexCoord2f(tcs[UPLFT].u, tcs[UPLFT].v); + glVertex3f(glseg.x1, ztop[0], glseg.y1); + glColor4f(fc[0], fc[1], fc[2], fogd2); + glTexCoord2f(tcs[UPRGT].u, tcs[UPRGT].v); + glVertex3f(glseg.x2, ztop[1], glseg.y2); + glTexCoord2f(tcs[LORGT].u, tcs[LORGT].v); + glVertex3f(glseg.x2, zbottom[1], glseg.y2); + glEnd(); + glDepthFunc(GL_LESS); + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + gl_RenderState.EnableFog(true); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.5f); + gl_RenderState.EnableTexture(true); +} + +//========================================================================== +// +// Flats +// +//========================================================================== + +void GLFlat::DrawSubsectorLights(subsector_t * sub, int pass) +{ + Plane p; + Vector nearPt, up, right, t1; + float scale; + + FLightNode * node = sub->lighthead; + while (node) + { + ADynamicLight * light = node->lightsource; + + if (light->flags2&MF2_DORMANT || + (pass == GLPASS_LIGHTTEX && light->IsAdditive()) || + (pass == GLPASS_LIGHTTEX_ADDITIVE && !light->IsAdditive())) + { + node = node->nextLight; + continue; + } + + // we must do the side check here because gl_SetupLight needs the correct plane orientation + // which we don't have for Legacy-style 3D-floors + double planeh = plane.plane.ZatPoint(light); + if (gl_lights_checkside && ((planehZ() && ceiling) || (planeh>light->Z() && !ceiling))) + { + node = node->nextLight; + continue; + } + + p.Set(plane.plane); + if (!gl_SetupLight(sub->sector->PortalGroup, p, light, nearPt, up, right, scale, false, pass != GLPASS_LIGHTTEX)) + { + node = node->nextLight; + continue; + } + gl_RenderState.Apply(); + + FFlatVertex *ptr = GLRenderer->mVBO->GetBuffer(); + for (unsigned int k = 0; k < sub->numlines; k++) + { + vertex_t *vt = sub->firstline[k].v1; + ptr->x = vt->fX(); + ptr->z = plane.plane.ZatPoint(vt) + dz; + ptr->y = vt->fY(); + t1.Set(ptr->x, ptr->z, ptr->y); + Vector nearToVert = t1 - nearPt; + + ptr->u = (nearToVert.Dot(right) * scale) + 0.5f; + ptr->v = (nearToVert.Dot(up) * scale) + 0.5f; + ptr++; + } + GLRenderer->mVBO->RenderCurrent(ptr, GL_TRIANGLE_FAN); + node = node->nextLight; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLFlat::DrawLightsCompat(int pass) +{ + gl_RenderState.Apply(); + // Draw the subsectors belonging to this sector + for (int i = 0; isubsectorcount; i++) + { + subsector_t * sub = sector->subsectors[i]; + if (gl_drawinfo->ss_renderflags[sub - subsectors] & renderflags) + { + DrawSubsectorLights(sub, pass); + } + } + + // Draw the subsectors assigned to it due to missing textures + if (!(renderflags&SSRF_RENDER3DPLANES)) + { + gl_subsectorrendernode * node = (renderflags&SSRF_RENDERFLOOR) ? + gl_drawinfo->GetOtherFloorPlanes(sector->sectornum) : + gl_drawinfo->GetOtherCeilingPlanes(sector->sectornum); + + while (node) + { + DrawSubsectorLights(node->sub, pass); + node = node->next; + } + } +} + + +//========================================================================== +// +// Sets up the texture coordinates for one light to be rendered +// +//========================================================================== +bool GLWall::PrepareLight(ADynamicLight * light, int pass) +{ + float vtx[] = { glseg.x1,zbottom[0],glseg.y1, glseg.x1,ztop[0],glseg.y1, glseg.x2,ztop[1],glseg.y2, glseg.x2,zbottom[1],glseg.y2 }; + Plane p; + Vector nearPt, up, right; + float scale; + + p.Init(vtx, 4); + + if (!p.ValidNormal()) + { + return false; + } + + if (!gl_SetupLight(seg->frontsector->PortalGroup, p, light, nearPt, up, right, scale, true, pass != GLPASS_LIGHTTEX)) + { + return false; + } + + Vector t1; + int outcnt[4] = { 0,0,0,0 }; + + for (int i = 0; i<4; i++) + { + t1.Set(&vtx[i * 3]); + Vector nearToVert = t1 - nearPt; + tcs[i].u = (nearToVert.Dot(right) * scale) + 0.5f; + tcs[i].v = (nearToVert.Dot(up) * scale) + 0.5f; + + // quick check whether the light touches this polygon + if (tcs[i].u<0) outcnt[0]++; + if (tcs[i].u>1) outcnt[1]++; + if (tcs[i].v<0) outcnt[2]++; + if (tcs[i].v>1) outcnt[3]++; + + } + // The light doesn't touch this polygon + if (outcnt[0] == 4 || outcnt[1] == 4 || outcnt[2] == 4 || outcnt[3] == 4) return false; + + draw_dlight++; + return true; +} + + +void GLWall::RenderLightsCompat(int pass) +{ + FLightNode * node; + + // black fog is diminishing light and should affect lights less than the rest! + if (pass == GLPASS_LIGHTTEX) gl_SetFog((255 + lightlevel) >> 1, 0, NULL, false); + else gl_SetFog(lightlevel, 0, &Colormap, true); + + if (seg->sidedef == NULL) + { + return; + } + else if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + // Iterate through all dynamic lights which touch this wall and render them + node = seg->sidedef->lighthead; + } + else if (sub) + { + // To avoid constant rechecking for polyobjects use the subsector's lightlist instead + node = sub->lighthead; + } + else + { + return; + } + + texcoord save[4]; + memcpy(save, tcs, sizeof(tcs)); + while (node) + { + ADynamicLight * light = node->lightsource; + + if (light->flags2&MF2_DORMANT || + (pass == GLPASS_LIGHTTEX && light->IsAdditive()) || + (pass == GLPASS_LIGHTTEX_ADDITIVE && !light->IsAdditive())) + { + node = node->nextLight; + continue; + } + if (PrepareLight(light, pass)) + { + vertcount = 0; + RenderWall(RWF_TEXTURED); + } + node = node->nextLight; + } + memcpy(tcs, save, sizeof(tcs)); + vertcount = 0; +} + +//========================================================================== +// +// +// +//========================================================================== + +void FGLRenderer::RenderMultipassStuff() +{ + // First pass: empty background with sector light only + + // Part 1: solid geometry. This is set up so that there are no transparent parts + + // remove any remaining texture bindings and shaders whick may get in the way. + gl_RenderState.EnableTexture(false); + gl_RenderState.EnableBrightmap(false); + gl_RenderState.Apply(); + gl_drawinfo->dldrawlists[GLLDL_WALLS_PLAIN].DrawWalls(GLPASS_PLAIN); + gl_drawinfo->dldrawlists[GLLDL_FLATS_PLAIN].DrawFlats(GLPASS_PLAIN); + + // Part 2: masked geometry. This is set up so that only pixels with alpha>0.5 will show + // This creates a blank surface that only fills the nontransparent parts of the texture + gl_RenderState.EnableTexture(true); + gl_RenderState.SetTextureMode(TM_MASK); + gl_RenderState.EnableBrightmap(true); + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_threshold); + gl_drawinfo->dldrawlists[GLLDL_WALLS_MASKED].DrawWalls(GLPASS_PLAIN); + gl_drawinfo->dldrawlists[GLLDL_FLATS_MASKED].DrawFlats(GLPASS_PLAIN); + + // Part 3: The base of fogged surfaces, including the texture + gl_RenderState.EnableBrightmap(false); + gl_RenderState.SetTextureMode(TM_MODULATE); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0); + gl_drawinfo->dldrawlists[GLLDL_WALLS_FOG].DrawWalls(GLPASS_PLAIN); + gl_drawinfo->dldrawlists[GLLDL_FLATS_FOG].DrawFlats(GLPASS_PLAIN); + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_threshold); + gl_drawinfo->dldrawlists[GLLDL_WALLS_FOGMASKED].DrawWalls(GLPASS_PLAIN); + gl_drawinfo->dldrawlists[GLLDL_FLATS_FOGMASKED].DrawFlats(GLPASS_PLAIN); + + // second pass: draw lights + glDepthMask(false); + if (mLightCount && !gl_fixedcolormap) + { + if (gl_SetupLightTexture()) + { + gl_RenderState.BlendFunc(GL_ONE, GL_ONE); + glDepthFunc(GL_EQUAL); + if (glset.lightmode == 8) gl_RenderState.SetSoftLightLevel(255); + gl_drawinfo->dldrawlists[GLLDL_WALLS_PLAIN].DrawWalls(GLPASS_LIGHTTEX); + gl_drawinfo->dldrawlists[GLLDL_WALLS_MASKED].DrawWalls(GLPASS_LIGHTTEX); + gl_drawinfo->dldrawlists[GLLDL_FLATS_PLAIN].DrawFlats(GLPASS_LIGHTTEX); + gl_drawinfo->dldrawlists[GLLDL_FLATS_MASKED].DrawFlats(GLPASS_LIGHTTEX); + gl_RenderState.BlendEquation(GL_FUNC_ADD); + } + else gl_lights = false; + } + + // third pass: modulated texture + gl_RenderState.SetColor(0xffffffff); + gl_RenderState.BlendFunc(GL_DST_COLOR, GL_ZERO); + gl_RenderState.EnableFog(false); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0); + glDepthFunc(GL_LEQUAL); + gl_drawinfo->dldrawlists[GLLDL_WALLS_PLAIN].DrawWalls(GLPASS_TEXONLY); + gl_drawinfo->dldrawlists[GLLDL_FLATS_PLAIN].DrawFlats(GLPASS_TEXONLY); + gl_RenderState.AlphaFunc(GL_GREATER, gl_mask_threshold); + gl_drawinfo->dldrawlists[GLLDL_WALLS_MASKED].DrawWalls(GLPASS_TEXONLY); + gl_drawinfo->dldrawlists[GLLDL_FLATS_MASKED].DrawFlats(GLPASS_TEXONLY); + + // fourth pass: additive lights + gl_RenderState.EnableFog(true); + gl_RenderState.BlendFunc(GL_ONE, GL_ONE); + glDepthFunc(GL_EQUAL); + if (gl_SetupLightTexture()) + { + gl_drawinfo->dldrawlists[GLLDL_WALLS_PLAIN].DrawWalls(GLPASS_LIGHTTEX_ADDITIVE); + gl_drawinfo->dldrawlists[GLLDL_WALLS_MASKED].DrawWalls(GLPASS_LIGHTTEX_ADDITIVE); + gl_drawinfo->dldrawlists[GLLDL_FLATS_PLAIN].DrawFlats(GLPASS_LIGHTTEX_ADDITIVE); + gl_drawinfo->dldrawlists[GLLDL_FLATS_MASKED].DrawFlats(GLPASS_LIGHTTEX_ADDITIVE); + gl_drawinfo->dldrawlists[GLLDL_WALLS_FOG].DrawWalls(GLPASS_LIGHTTEX_FOGGY); + gl_drawinfo->dldrawlists[GLLDL_WALLS_FOGMASKED].DrawWalls(GLPASS_LIGHTTEX_FOGGY); + gl_drawinfo->dldrawlists[GLLDL_FLATS_FOG].DrawFlats(GLPASS_LIGHTTEX_FOGGY); + gl_drawinfo->dldrawlists[GLLDL_FLATS_FOGMASKED].DrawFlats(GLPASS_LIGHTTEX_FOGGY); + } + else gl_lights = false; + + glDepthFunc(GL_LESS); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.EnableFog(true); + gl_RenderState.BlendFunc(GL_ONE, GL_ZERO); + glDepthMask(true); + +} + diff --git a/src/gl/data/gl_data.cpp b/src/gl/data/gl_data.cpp new file mode 100644 index 000000000..eb676de75 --- /dev/null +++ b/src/gl/data/gl_data.cpp @@ -0,0 +1,574 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_data.cpp +** Maintenance data for GL renderer (mostly to handle rendering hacks) +** +**/ + +#include "gl/system/gl_system.h" + +#include "doomtype.h" +#include "colormatcher.h" +#include "i_system.h" +#include "p_local.h" +#include "p_tags.h" +#include "p_lnspec.h" +#include "c_dispatch.h" +#include "r_sky.h" +#include "sc_man.h" +#include "w_wad.h" +#include "gi.h" +#include "g_level.h" +#include "doomstat.h" +#include "d_player.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/models/gl_models.h" +#include "gl/utility/gl_clock.h" +#include "gl/shaders/gl_shader.h" +#include "gl/gl_functions.h" + +GLRenderSettings glset; +long gl_frameMS; +long gl_frameCount; + +EXTERN_CVAR(Int, gl_lightmode) +EXTERN_CVAR(Bool, gl_brightfog) +EXTERN_CVAR(Bool, gl_lightadditivesurfaces) +EXTERN_CVAR(Bool, gl_attenuate) + + +CUSTOM_CVAR(Float, maxviewpitch, 90.f, CVAR_ARCHIVE|CVAR_SERVERINFO) +{ + if (self>90.f) self=90.f; + else if (self<-90.f) self=-90.f; + if (usergame) + { + // [SP] Update pitch limits to the netgame/gamesim. + players[consoleplayer].SendPitchLimits(); + } +} + +CUSTOM_CVAR(Bool, gl_notexturefill, false, 0) +{ + glset.notexturefill = self; +} + + +CUSTOM_CVAR(Bool, gl_nocoloredspritelighting, false, 0) +{ + glset.nocoloredspritelighting = self; +} + +void gl_CreateSections(); + +//----------------------------------------------------------------------------- +// +// Adjust sprite offsets for GL rendering (IWAD resources only) +// +//----------------------------------------------------------------------------- + +void AdjustSpriteOffsets() +{ + int lump, lastlump = 0; + while ((lump = Wads.FindLump("SPROFS", &lastlump, false)) != -1) + { + FScanner sc; + sc.OpenLumpNum(lump); + sc.SetCMode(true); + GLRenderer->FlushTextures(); + int ofslumpno = Wads.GetLumpFile(lump); + while (sc.GetString()) + { + int x,y; + bool iwadonly = false; + FTextureID texno = TexMan.CheckForTexture(sc.String, FTexture::TEX_Sprite); + sc.MustGetStringName(","); + sc.MustGetNumber(); + x=sc.Number; + sc.MustGetStringName(","); + sc.MustGetNumber(); + y=sc.Number; + if (sc.CheckString(",")) + { + sc.MustGetString(); + if (sc.Compare("iwad")) iwadonly = true; + } + if (texno.isValid()) + { + FTexture * tex = TexMan[texno]; + + int lumpnum = tex->GetSourceLump(); + // We only want to change texture offsets for sprites in the IWAD or the file this lump originated from. + if (lumpnum >= 0 && lumpnum < Wads.GetNumLumps()) + { + int wadno = Wads.GetLumpFile(lumpnum); + if ((iwadonly && wadno==FWadCollection::IWAD_FILENUM) || (!iwadonly && wadno == ofslumpno)) + { + tex->LeftOffset=x; + tex->TopOffset=y; + tex->KillNative(); + } + } + } + } + } +} + + + +// Normally this would be better placed in p_lnspec.cpp. +// But I have accidentally overwritten that file several times +// so I'd rather place it here. +int LS_Sector_SetPlaneReflection (line_t *ln, AActor *it, bool backSide, + int arg0, int arg1, int arg2, int arg3, int arg4) +{ +// Sector_SetPlaneReflection (tag, floor, ceiling) + int secnum; + FSectorTagIterator itr(arg0); + + while ((secnum = itr.Next()) >= 0) + { + sector_t * s = §ors[secnum]; + if (!s->floorplane.isSlope()) s->reflect[sector_t::floor] = arg1/255.f; + if (!s->ceilingplane.isSlope()) sectors[secnum].reflect[sector_t::ceiling] = arg2/255.f; + } + + return true; +} + +int LS_SetGlobalFogParameter (line_t *ln, AActor *it, bool backSide, + int arg0, int arg1, int arg2, int arg3, int arg4) +{ +// SetGlobalFogParameter (type, value) + switch(arg0) + { + case 0: + fogdensity = arg1>>1; + return true; + + case 1: + outsidefogdensity = arg1>>1; + return true; + + case 2: + skyfog = arg1; + return true; + + default: + return false; + } +} + + +//========================================================================== +// +// Portal identifier lists +// +//========================================================================== + + +//========================================================================== +// +// MAPINFO stuff +// +//========================================================================== + +struct FGLROptions : public FOptionalMapinfoData +{ + FGLROptions() + { + identifier = "gl_renderer"; + fogdensity = 0; + outsidefogdensity = 0; + skyfog = 0; + brightfog = false; + lightmode = -1; + attenuate = -1; + nocoloredspritelighting = -1; + notexturefill = -1; + skyrotatevector = FVector3(0,0,1); + skyrotatevector2 = FVector3(0,0,1); + pixelstretch = 1.2f; + lightadditivesurfaces = false; + } + virtual FOptionalMapinfoData *Clone() const + { + FGLROptions *newopt = new FGLROptions; + newopt->identifier = identifier; + newopt->fogdensity = fogdensity; + newopt->outsidefogdensity = outsidefogdensity; + newopt->skyfog = skyfog; + newopt->lightmode = lightmode; + newopt->attenuate = attenuate; + newopt->nocoloredspritelighting = nocoloredspritelighting; + newopt->notexturefill = notexturefill; + newopt->skyrotatevector = skyrotatevector; + newopt->skyrotatevector2 = skyrotatevector2; + newopt->pixelstretch = pixelstretch; + newopt->lightadditivesurfaces = lightadditivesurfaces; + return newopt; + } + int fogdensity; + int outsidefogdensity; + int skyfog; + int lightmode; + int brightfog; + int8_t attenuate; + int8_t lightadditivesurfaces; + int8_t nocoloredspritelighting; + int8_t notexturefill; + FVector3 skyrotatevector; + FVector3 skyrotatevector2; + float pixelstretch; +}; + +DEFINE_MAP_OPTION(fogdensity, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + parse.ParseAssign(); + parse.sc.MustGetNumber(); + opt->fogdensity = parse.sc.Number; +} + +DEFINE_MAP_OPTION(brightfog, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + parse.ParseAssign(); + parse.sc.MustGetNumber(); + opt->brightfog = parse.sc.Number; +} + +DEFINE_MAP_OPTION(outsidefogdensity, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + parse.ParseAssign(); + parse.sc.MustGetNumber(); + opt->outsidefogdensity = parse.sc.Number; +} + +DEFINE_MAP_OPTION(skyfog, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + parse.ParseAssign(); + parse.sc.MustGetNumber(); + opt->skyfog = parse.sc.Number; +} + +DEFINE_MAP_OPTION(lightmode, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + parse.ParseAssign(); + parse.sc.MustGetNumber(); + opt->lightmode = BYTE(parse.sc.Number); +} + +DEFINE_MAP_OPTION(nocoloredspritelighting, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + if (parse.CheckAssign()) + { + parse.sc.MustGetNumber(); + opt->nocoloredspritelighting = !!parse.sc.Number; + } + else + { + opt->nocoloredspritelighting = true; + } +} + +DEFINE_MAP_OPTION(notexturefill, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + if (parse.CheckAssign()) + { + parse.sc.MustGetNumber(); + opt->notexturefill = !!parse.sc.Number; + } + else + { + opt->notexturefill = true; + } +} + +DEFINE_MAP_OPTION(lightadditivesurfaces, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + if (parse.CheckAssign()) + { + parse.sc.MustGetNumber(); + opt->lightadditivesurfaces = !!parse.sc.Number; + } + else + { + opt->lightadditivesurfaces = true; + } +} + +DEFINE_MAP_OPTION(attenuate, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + if (parse.CheckAssign()) + { + parse.sc.MustGetNumber(); + opt->attenuate = !!parse.sc.Number; + } + else + { + opt->attenuate = true; + } +} + +DEFINE_MAP_OPTION(skyrotate, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + + parse.ParseAssign(); + parse.sc.MustGetFloat(); + opt->skyrotatevector.X = (float)parse.sc.Float; + if (parse.format_type == FMapInfoParser::FMT_New) parse.sc.MustGetStringName(","); + parse.sc.MustGetFloat(); + opt->skyrotatevector.Y = (float)parse.sc.Float; + if (parse.format_type == FMapInfoParser::FMT_New) parse.sc.MustGetStringName(","); + parse.sc.MustGetFloat(); + opt->skyrotatevector.Z = (float)parse.sc.Float; + opt->skyrotatevector.MakeUnit(); +} + +DEFINE_MAP_OPTION(skyrotate2, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + + parse.ParseAssign(); + parse.sc.MustGetFloat(); + opt->skyrotatevector2.X = (float)parse.sc.Float; + if (parse.format_type == FMapInfoParser::FMT_New) parse.sc.MustGetStringName(","); + parse.sc.MustGetFloat(); + opt->skyrotatevector2.Y = (float)parse.sc.Float; + if (parse.format_type == FMapInfoParser::FMT_New) parse.sc.MustGetStringName(","); + parse.sc.MustGetFloat(); + opt->skyrotatevector2.Z = (float)parse.sc.Float; + opt->skyrotatevector2.MakeUnit(); +} + +DEFINE_MAP_OPTION(pixelratio, false) +{ + FGLROptions *opt = info->GetOptData("gl_renderer"); + + parse.ParseAssign(); + parse.sc.MustGetFloat(); + opt->pixelstretch = (float)parse.sc.Float; +} + +bool IsLightmodeValid() +{ + return (glset.map_lightmode >= 0 && glset.map_lightmode <= 4) || glset.map_lightmode == 8; +} + +static void ResetOpts() +{ + if (!IsLightmodeValid()) glset.lightmode = gl_lightmode; + else glset.lightmode = glset.map_lightmode; + if (glset.map_nocoloredspritelighting == -1) glset.nocoloredspritelighting = gl_nocoloredspritelighting; + else glset.nocoloredspritelighting = !!glset.map_nocoloredspritelighting; + if (glset.map_notexturefill == -1) glset.notexturefill = gl_notexturefill; + else glset.notexturefill = !!glset.map_notexturefill; + if (glset.map_brightfog == -1) glset.brightfog = gl_brightfog; + else glset.brightfog = !!glset.map_brightfog; + if (glset.map_lightadditivesurfaces == -1) glset.lightadditivesurfaces = gl_lightadditivesurfaces; + else glset.lightadditivesurfaces = !!glset.map_lightadditivesurfaces; + if (glset.map_attenuate == -1) glset.attenuate = gl_attenuate; + else glset.attenuate = !!glset.map_attenuate; +} + +void InitGLRMapinfoData() +{ + FGLROptions *opt = level.info->GetOptData("gl_renderer", false); + + if (opt != NULL) + { + gl_SetFogParams(opt->fogdensity, level.info->outsidefog, opt->outsidefogdensity, opt->skyfog); + glset.map_lightmode = opt->lightmode; + glset.map_lightadditivesurfaces = opt->lightadditivesurfaces; + glset.map_attenuate = opt->attenuate; + glset.map_brightfog = opt->brightfog; + glset.map_nocoloredspritelighting = opt->nocoloredspritelighting; + glset.map_notexturefill = opt->notexturefill; + glset.skyrotatevector = opt->skyrotatevector; + glset.skyrotatevector2 = opt->skyrotatevector2; + glset.pixelstretch = opt->pixelstretch; + } + else + { + gl_SetFogParams(0, level.info->outsidefog, 0, 0); + glset.map_lightmode = -1; + glset.map_lightadditivesurfaces = -1; + glset.map_brightfog = -1; + glset.map_attenuate = -1; + glset.map_nocoloredspritelighting = -1; + glset.map_notexturefill = -1; + glset.skyrotatevector = FVector3(0, 0, 1); + glset.skyrotatevector2 = FVector3(0, 0, 1); + glset.pixelstretch = 1.2f; + } + ResetOpts(); +} +CCMD(gl_resetmap) +{ + ResetOpts(); +} + + +//=========================================================================== +// +// Gets the texture index for a sprite frame +// +//=========================================================================== + +FTextureID gl_GetSpriteFrame(unsigned sprite, int frame, int rot, angle_t ang, bool *mirror) +{ + spritedef_t *sprdef = &sprites[sprite]; + if (frame >= sprdef->numframes) + { + // If there are no frames at all for this sprite, don't draw it. + return FNullTextureID(); + } + else + { + //picnum = SpriteFrames[sprdef->spriteframes + thing->frame].Texture[0]; + // choose a different rotation based on player view + spriteframe_t *sprframe = &SpriteFrames[sprdef->spriteframes + frame]; + if (rot==-1) + { + if (sprframe->Texture[0] == sprframe->Texture[1]) + { + rot = (ang + (angle_t)(ANGLE_90/4)*9) >> 28; + } + else + { + rot = (ang + (angle_t)(ANGLE_90/4)*9-(angle_t)(ANGLE_180/16)) >> 28; + } + } + if (mirror) *mirror = !!(sprframe->Flip&(1<Texture[rot]; + } +} + + +//========================================================================== +// +// Recalculate all heights affectting this vertex. +// +//========================================================================== +void gl_RecalcVertexHeights(vertex_t * v) +{ + int i,j,k; + float height; + + v->numheights=0; + for(i=0;inumsectors;i++) + { + for(j=0;j<2;j++) + { + if (j==0) height=v->sectors[i]->ceilingplane.ZatPoint(v); + else height=v->sectors[i]->floorplane.ZatPoint(v); + + for(k=0;knumheights;k++) + { + if (height == v->heightlist[k]) break; + if (height < v->heightlist[k]) + { + memmove(&v->heightlist[k+1], &v->heightlist[k], sizeof(float) * (v->numheights-k)); + v->heightlist[k]=height; + v->numheights++; + break; + } + } + if (k==v->numheights) v->heightlist[v->numheights++]=height; + } + } + if (v->numheights<=2) v->numheights=0; // is not in need of any special attention + v->dirty = false; +} + + + + +void gl_InitData() +{ + AdjustSpriteOffsets(); +} + +//========================================================================== +// +// dumpgeometry +// +//========================================================================== + +CCMD(dumpgeometry) +{ + for(int i=0;isubsectorcount;j++) + { + subsector_t * sub = sector->subsectors[j]; + + Printf(PRINT_LOG, " Subsector %d - real sector = %d - %s\n", int(sub-subsectors), sub->sector->sectornum, sub->hacked&1? "hacked":""); + for(DWORD k=0;knumlines;k++) + { + seg_t * seg = sub->firstline + k; + if (seg->linedef) + { + Printf(PRINT_LOG, " (%4.4f, %4.4f), (%4.4f, %4.4f) - seg %d, linedef %d, side %d", + seg->v1->fX(), seg->v1->fY(), seg->v2->fX(), seg->v2->fY(), + int(seg-segs), int(seg->linedef-lines), seg->sidedef != seg->linedef->sidedef[0]); + } + else + { + Printf(PRINT_LOG, " (%4.4f, %4.4f), (%4.4f, %4.4f) - seg %d, miniseg", + seg->v1->fX(), seg->v1->fY(), seg->v2->fX(), seg->v2->fY(), + int(seg-segs)); + } + if (seg->PartnerSeg) + { + subsector_t * sub2 = seg->PartnerSeg->Subsector; + Printf(PRINT_LOG, ", back sector = %d, real back sector = %d", sub2->render_sector->sectornum, seg->PartnerSeg->frontsector->sectornum); + } + else if (seg->backsector) + { + Printf(PRINT_LOG, ", back sector = %d (no partnerseg)", seg->backsector->sectornum); + } + + Printf(PRINT_LOG, "\n"); + } + } + } +} diff --git a/src/gl/data/gl_data.h b/src/gl/data/gl_data.h new file mode 100644 index 000000000..bb57c9139 --- /dev/null +++ b/src/gl/data/gl_data.h @@ -0,0 +1,80 @@ + +#ifndef __GLC_DATA_H +#define __GLC_DATA_H + +#include "doomtype.h" +#include "vectors.h" + +struct GLRenderSettings +{ + + SBYTE lightmode; + bool nocoloredspritelighting; + bool notexturefill; + bool brightfog; + bool lightadditivesurfaces; + bool attenuate; + + int8_t map_lightmode; + int8_t map_nocoloredspritelighting; + int8_t map_notexturefill; + int8_t map_brightfog; + int8_t map_lightadditivesurfaces; + int8_t map_attenuate; + + FVector3 skyrotatevector; + FVector3 skyrotatevector2; + + float pixelstretch; + +}; + +extern GLRenderSettings glset; + +#include "r_defs.h" +#include "a_sharedglobal.h" +#include "c_cvars.h" + +extern int extralight; +EXTERN_CVAR(Int, gl_weaponlight); + +inline int getExtraLight() +{ + return extralight * gl_weaponlight; +} + +void gl_RecalcVertexHeights(vertex_t * v); +FTextureID gl_GetSpriteFrame(unsigned sprite, int frame, int rot, angle_t ang, bool *mirror); + +class AStackPoint; +struct GLSectorStackPortal; + +struct FPortal +{ + DVector2 mDisplacement; + int plane; + GLSectorStackPortal *glportal; // for quick access to the render data. This is only valid during BSP traversal! + + GLSectorStackPortal *GetRenderState(); +}; + +struct FGLLinePortal +{ + // defines the complete span of this portal, if this is of type PORTT_LINKED. + vertex_t *v1 = nullptr, *v2 = nullptr; // vertices, from v1 to v2 + TArray lines; + int validcount = 0; +}; + +extern TArray portals; +extern TArray linePortalToGL; + +extern TArray currentmapsection; + +void gl_InitPortals(); +void gl_BuildPortalCoverage(FPortalCoverage *coverage, subsector_t *subsector, const DVector2 &displacement); +void gl_InitData(); + +extern long gl_frameMS; + +#endif diff --git a/src/gl/data/gl_matrix.cpp b/src/gl/data/gl_matrix.cpp new file mode 100644 index 000000000..115882857 --- /dev/null +++ b/src/gl/data/gl_matrix.cpp @@ -0,0 +1,486 @@ +/* -------------------------------------------------- + +Lighthouse3D + +VSMatrix - Very Simple Matrix Library + +http://www.lighthouse3d.com/very-simple-libs + +This is a simplified version of VSMatrix that has been adjusted for GZDoom's needs. + +----------------------------------------------------*/ + +#include +#include "gl/system/gl_system.h" +#include +#include +#include +#include +#include "doomtype.h" +#include "gl/data/gl_matrix.h" + +static inline FLOATTYPE +DegToRad(FLOATTYPE degrees) +{ + return (FLOATTYPE)(degrees * (M_PI / 180.0f)); +}; + +// sets the square matrix mat to the identity matrix, +// size refers to the number of rows (or columns) +void +VSMatrix::setIdentityMatrix( FLOATTYPE *mat, int size) { + + // fill matrix with 0s + for (int i = 0; i < size * size; ++i) + mat[i] = 0.0f; + + // fill diagonal with 1s + for (int i = 0; i < size; ++i) + mat[i + i * size] = 1.0f; +} + + + +// gl LoadIdentity implementation +void +VSMatrix::loadIdentity() +{ + // fill matrix with 0s + for (int i = 0; i < 16; ++i) + mMatrix[i] = 0.0f; + + // fill diagonal with 1s + for (int i = 0; i < 4; ++i) + mMatrix[i + i * 4] = 1.0f; +} + + +// gl MultMatrix implementation +void +VSMatrix::multMatrix(const FLOATTYPE *aMatrix) +{ + + FLOATTYPE res[16]; + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + res[j*4 + i] = 0.0f; + for (int k = 0; k < 4; ++k) + { + res[j*4 + i] += mMatrix[k*4 + i] * aMatrix[j*4 + k]; + } + } + } + memcpy(mMatrix, res, 16 * sizeof(FLOATTYPE)); +} + +#ifdef USE_DOUBLE +// gl MultMatrix implementation +void +VSMatrix::multMatrix(const float *aMatrix) +{ + + FLOATTYPE res[16]; + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + res[j * 4 + i] = 0.0f; + for (int k = 0; k < 4; ++k) + { + res[j*4 + i] += mMatrix[k*4 + i] * aMatrix[j*4 + k]; + } + } + } + memcpy(mMatrix, res, 16 * sizeof(FLOATTYPE)); +} +#endif + + + +// gl LoadMatrix implementation +void +VSMatrix::loadMatrix(const FLOATTYPE *aMatrix) +{ + memcpy(mMatrix, aMatrix, 16 * sizeof(FLOATTYPE)); +} + +#ifdef USE_DOUBLE +// gl LoadMatrix implementation +void +VSMatrix::loadMatrix(const float *aMatrix) +{ + for (int i = 0; i < 16; ++i) + { + mMatrix[i] = aMatrix[i]; + } +} +#endif + + +// gl Translate implementation +void +VSMatrix::translate(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z) +{ + mMatrix[12] = mMatrix[0] * x + mMatrix[4] * y + mMatrix[8] * z + mMatrix[12]; + mMatrix[13] = mMatrix[1] * x + mMatrix[5] * y + mMatrix[9] * z + mMatrix[13]; + mMatrix[14] = mMatrix[2] * x + mMatrix[6] * y + mMatrix[10] * z + mMatrix[14]; +} + + +// gl Scale implementation +void +VSMatrix::scale(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z) +{ + mMatrix[0] *= x; mMatrix[1] *= x; mMatrix[2] *= x; mMatrix[3] *= x; + mMatrix[4] *= y; mMatrix[5] *= y; mMatrix[6] *= y; mMatrix[7] *= y; + mMatrix[8] *= z; mMatrix[9] *= z; mMatrix[10] *= z; mMatrix[11] *= z; +} + + +// gl Rotate implementation +void +VSMatrix::rotate(FLOATTYPE angle, FLOATTYPE x, FLOATTYPE y, FLOATTYPE z) +{ + FLOATTYPE mat[16]; + FLOATTYPE v[3]; + + v[0] = x; + v[1] = y; + v[2] = z; + + FLOATTYPE radAngle = DegToRad(angle); + FLOATTYPE co = cos(radAngle); + FLOATTYPE si = sin(radAngle); + normalize(v); + FLOATTYPE x2 = v[0]*v[0]; + FLOATTYPE y2 = v[1]*v[1]; + FLOATTYPE z2 = v[2]*v[2]; + +// mat[0] = x2 + (y2 + z2) * co; + mat[0] = co + x2 * (1 - co);// + (y2 + z2) * co; + mat[4] = v[0] * v[1] * (1 - co) - v[2] * si; + mat[8] = v[0] * v[2] * (1 - co) + v[1] * si; + mat[12]= 0.0f; + + mat[1] = v[0] * v[1] * (1 - co) + v[2] * si; +// mat[5] = y2 + (x2 + z2) * co; + mat[5] = co + y2 * (1 - co); + mat[9] = v[1] * v[2] * (1 - co) - v[0] * si; + mat[13]= 0.0f; + + mat[2] = v[0] * v[2] * (1 - co) - v[1] * si; + mat[6] = v[1] * v[2] * (1 - co) + v[0] * si; +// mat[10]= z2 + (x2 + y2) * co; + mat[10]= co + z2 * (1 - co); + mat[14]= 0.0f; + + mat[3] = 0.0f; + mat[7] = 0.0f; + mat[11]= 0.0f; + mat[15]= 1.0f; + + multMatrix(mat); +} + + +// gluLookAt implementation +void +VSMatrix::lookAt(FLOATTYPE xPos, FLOATTYPE yPos, FLOATTYPE zPos, + FLOATTYPE xLook, FLOATTYPE yLook, FLOATTYPE zLook, + FLOATTYPE xUp, FLOATTYPE yUp, FLOATTYPE zUp) +{ + FLOATTYPE dir[3], right[3], up[3]; + + up[0] = xUp; up[1] = yUp; up[2] = zUp; + + dir[0] = (xLook - xPos); + dir[1] = (yLook - yPos); + dir[2] = (zLook - zPos); + normalize(dir); + + crossProduct(dir,up,right); + normalize(right); + + crossProduct(right,dir,up); + normalize(up); + + FLOATTYPE m1[16],m2[16]; + + m1[0] = right[0]; + m1[4] = right[1]; + m1[8] = right[2]; + m1[12] = 0.0f; + + m1[1] = up[0]; + m1[5] = up[1]; + m1[9] = up[2]; + m1[13] = 0.0f; + + m1[2] = -dir[0]; + m1[6] = -dir[1]; + m1[10] = -dir[2]; + m1[14] = 0.0f; + + m1[3] = 0.0f; + m1[7] = 0.0f; + m1[11] = 0.0f; + m1[15] = 1.0f; + + setIdentityMatrix(m2,4); + m2[12] = -xPos; + m2[13] = -yPos; + m2[14] = -zPos; + + multMatrix(m1); + multMatrix(m2); +} + + +// gluPerspective implementation +void +VSMatrix::perspective(FLOATTYPE fov, FLOATTYPE ratio, FLOATTYPE nearp, FLOATTYPE farp) +{ + FLOATTYPE f = 1.0f / tan (fov * (M_PI / 360.0f)); + + loadIdentity(); + mMatrix[0] = f / ratio; + mMatrix[1 * 4 + 1] = f; + mMatrix[2 * 4 + 2] = (farp + nearp) / (nearp - farp); + mMatrix[3 * 4 + 2] = (2.0f * farp * nearp) / (nearp - farp); + mMatrix[2 * 4 + 3] = -1.0f; + mMatrix[3 * 4 + 3] = 0.0f; +} + + +// gl Ortho implementation +void +VSMatrix::ortho(FLOATTYPE left, FLOATTYPE right, + FLOATTYPE bottom, FLOATTYPE top, + FLOATTYPE nearp, FLOATTYPE farp) +{ + loadIdentity(); + + mMatrix[0 * 4 + 0] = 2 / (right - left); + mMatrix[1 * 4 + 1] = 2 / (top - bottom); + mMatrix[2 * 4 + 2] = -2 / (farp - nearp); + mMatrix[3 * 4 + 0] = -(right + left) / (right - left); + mMatrix[3 * 4 + 1] = -(top + bottom) / (top - bottom); + mMatrix[3 * 4 + 2] = -(farp + nearp) / (farp - nearp); +} + + +// gl Frustum implementation +void +VSMatrix::frustum(FLOATTYPE left, FLOATTYPE right, + FLOATTYPE bottom, FLOATTYPE top, + FLOATTYPE nearp, FLOATTYPE farp) +{ + FLOATTYPE m[16]; + + setIdentityMatrix(m,4); + + m[0 * 4 + 0] = 2 * nearp / (right-left); + m[1 * 4 + 1] = 2 * nearp / (top - bottom); + m[2 * 4 + 0] = (right + left) / (right - left); + m[2 * 4 + 1] = (top + bottom) / (top - bottom); + m[2 * 4 + 2] = - (farp + nearp) / (farp - nearp); + m[2 * 4 + 3] = -1.0f; + m[3 * 4 + 2] = - 2 * farp * nearp / (farp-nearp); + m[3 * 4 + 3] = 0.0f; + + multMatrix(m); +} + + +/* +// returns a pointer to the requested matrix +FLOATTYPE * +VSMatrix::get(MatrixTypes aType) +{ + return mMatrix[aType]; +} +*/ + + +/* ----------------------------------------------------- + SEND MATRICES TO OPENGL +------------------------------------------------------*/ + + + + +// universal +void +VSMatrix::matrixToGL(int loc) +{ +#ifdef USE_DOUBLE + float copyto[16]; + copy(copyto); + glUniformMatrix4fv(loc, 1, false, copyto); +#else + glUniformMatrix4fv(loc, 1, false, mMatrix); +#endif +} + +// ----------------------------------------------------- +// AUX functions +// ----------------------------------------------------- + + +// Compute res = M * point +void +VSMatrix::multMatrixPoint(const FLOATTYPE *point, FLOATTYPE *res) +{ + + for (int i = 0; i < 4; ++i) + { + + res[i] = 0.0f; + + for (int j = 0; j < 4; j++) { + + res[i] += point[j] * mMatrix[j*4 + i]; + } + } +} + +// res = a cross b; +void +VSMatrix::crossProduct(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res) { + + res[0] = a[1] * b[2] - b[1] * a[2]; + res[1] = a[2] * b[0] - b[2] * a[0]; + res[2] = a[0] * b[1] - b[0] * a[1]; +} + + +// returns a . b +FLOATTYPE +VSMatrix::dotProduct(const FLOATTYPE *a, const FLOATTYPE *b) { + + FLOATTYPE res = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + + return res; +} + + +// Normalize a vec3 +void +VSMatrix::normalize(FLOATTYPE *a) { + + FLOATTYPE mag = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + + a[0] /= mag; + a[1] /= mag; + a[2] /= mag; +} + + +// res = b - a +void +VSMatrix::subtract(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res) { + + res[0] = b[0] - a[0]; + res[1] = b[1] - a[1]; + res[2] = b[2] - a[2]; +} + + +// res = a + b +void +VSMatrix::add(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res) { + + res[0] = b[0] + a[0]; + res[1] = b[1] + a[1]; + res[2] = b[2] + a[2]; +} + + +// returns |a| +FLOATTYPE +VSMatrix::length(const FLOATTYPE *a) { + + return(sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])); + +} + + +static inline int +M3(int i, int j) +{ + return (i*3+j); +}; + + + +// computes the derived normal matrix for the view matrix +void +VSMatrix::computeNormalMatrix(const FLOATTYPE *aMatrix) +{ + + double mMat3x3[9]; + + mMat3x3[0] = aMatrix[0]; + mMat3x3[1] = aMatrix[1]; + mMat3x3[2] = aMatrix[2]; + + mMat3x3[3] = aMatrix[4]; + mMat3x3[4] = aMatrix[5]; + mMat3x3[5] = aMatrix[6]; + + mMat3x3[6] = aMatrix[8]; + mMat3x3[7] = aMatrix[9]; + mMat3x3[8] = aMatrix[10]; + + double det, invDet; + + det = mMat3x3[0] * (mMat3x3[4] * mMat3x3[8] - mMat3x3[5] * mMat3x3[7]) + + mMat3x3[1] * (mMat3x3[5] * mMat3x3[6] - mMat3x3[8] * mMat3x3[3]) + + mMat3x3[2] * (mMat3x3[3] * mMat3x3[7] - mMat3x3[4] * mMat3x3[6]); + + invDet = 1.0/det; + + mMatrix[0] = (mMat3x3[4] * mMat3x3[8] - mMat3x3[5] * mMat3x3[7]) * invDet; + mMatrix[1] = (mMat3x3[5] * mMat3x3[6] - mMat3x3[8] * mMat3x3[3]) * invDet; + mMatrix[2] = (mMat3x3[3] * mMat3x3[7] - mMat3x3[4] * mMat3x3[6]) * invDet; + mMatrix[3] = 0.0f; + mMatrix[4] = (mMat3x3[2] * mMat3x3[7] - mMat3x3[1] * mMat3x3[8]) * invDet; + mMatrix[5] = (mMat3x3[0] * mMat3x3[8] - mMat3x3[2] * mMat3x3[6]) * invDet; + mMatrix[6] = (mMat3x3[1] * mMat3x3[6] - mMat3x3[7] * mMat3x3[0]) * invDet; + mMatrix[7] = 0.0f; + mMatrix[8] = (mMat3x3[1] * mMat3x3[5] - mMat3x3[4] * mMat3x3[2]) * invDet; + mMatrix[9] = (mMat3x3[2] * mMat3x3[3] - mMat3x3[0] * mMat3x3[5]) * invDet; + mMatrix[10] =(mMat3x3[0] * mMat3x3[4] - mMat3x3[3] * mMat3x3[1]) * invDet; + mMatrix[11] = 0.0; + mMatrix[12] = 0.0; + mMatrix[13] = 0.0; + mMatrix[14] = 0.0; + mMatrix[15] = 1.0; + +} + + +// aux function resMat = resMat * aMatrix +void +VSMatrix::multMatrix(FLOATTYPE *resMat, const FLOATTYPE *aMatrix) +{ + + FLOATTYPE res[16]; + + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + res[j*4 + i] = 0.0f; + for (int k = 0; k < 4; ++k) + { + res[j*4 + i] += resMat[k*4 + i] * aMatrix[j*4 + k]; + } + } + } + memcpy(resMat, res, 16 * sizeof(FLOATTYPE)); +} diff --git a/src/gl/data/gl_matrix.h b/src/gl/data/gl_matrix.h new file mode 100644 index 000000000..3ec1f5ff4 --- /dev/null +++ b/src/gl/data/gl_matrix.h @@ -0,0 +1,115 @@ + +// Matrix class based on code from VSML: + +/** ---------------------------------------------------------- + * \class VSMathLib + * + * Lighthouse3D + * + * VSMathLib - Very Simple Matrix Library + * + * Full documentation at + * http://www.lighthouse3d.com/very-simple-libs + * + * This class aims at easing geometric transforms, camera + * placement and projection definition for programmers + * working with OpenGL core versions. + * + * + ---------------------------------------------------------------*/ +#ifndef __VSMatrix__ +#define __VSMatrix__ + +#include + +#ifdef USE_DOUBLE +typedef double FLOATTYPE; +#else +typedef float FLOATTYPE; +#endif + +class VSMatrix { + + public: + + VSMatrix() + { + } + + VSMatrix(int) + { + loadIdentity(); + } + + void translate(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); + void scale(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); + void rotate(FLOATTYPE angle, FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); + void loadIdentity(); +#ifdef USE_DOUBLE + void multMatrix(const float *aMatrix); +#endif + void multVector(FLOATTYPE *aVector); + void multMatrix(const FLOATTYPE *aMatrix); + void multMatrix(const VSMatrix &aMatrix) + { + multMatrix(aMatrix.mMatrix); + } + void loadMatrix(const FLOATTYPE *aMatrix); +#ifdef USE_DOUBLE + void loadMatrix(const float *aMatrix); +#endif + void lookAt(FLOATTYPE xPos, FLOATTYPE yPos, FLOATTYPE zPos, FLOATTYPE xLook, FLOATTYPE yLook, FLOATTYPE zLook, FLOATTYPE xUp, FLOATTYPE yUp, FLOATTYPE zUp); + void perspective(FLOATTYPE fov, FLOATTYPE ratio, FLOATTYPE nearp, FLOATTYPE farp); + void ortho(FLOATTYPE left, FLOATTYPE right, FLOATTYPE bottom, FLOATTYPE top, FLOATTYPE nearp=-1.0f, FLOATTYPE farp=1.0f); + void frustum(FLOATTYPE left, FLOATTYPE right, FLOATTYPE bottom, FLOATTYPE top, FLOATTYPE nearp, FLOATTYPE farp); + void copy(FLOATTYPE * pDest) + { + memcpy(pDest, mMatrix, 16 * sizeof(FLOATTYPE)); + } + +#ifdef USE_DOUBLE + void copy(float * pDest) + { + for (int i = 0; i < 16; i++) + { + pDest[i] = (float)mMatrix[i]; + } + } +#endif + + const FLOATTYPE *get() const + { + return mMatrix; + } + + void matrixToGL(int location); + void multMatrixPoint(const FLOATTYPE *point, FLOATTYPE *res); + +#ifdef USE_DOUBLE + void computeNormalMatrix(const float *aMatrix); +#endif + void computeNormalMatrix(const FLOATTYPE *aMatrix); + void computeNormalMatrix(const VSMatrix &aMatrix) + { + computeNormalMatrix(aMatrix.mMatrix); + } + bool inverseMatrix(VSMatrix &result); + void transpose(); + + protected: + static void crossProduct(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res); + static FLOATTYPE dotProduct(const FLOATTYPE *a, const FLOATTYPE * b); + static void normalize(FLOATTYPE *a); + static void subtract(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res); + static void add(const FLOATTYPE *a, const FLOATTYPE *b, FLOATTYPE *res); + static FLOATTYPE length(const FLOATTYPE *a); + static void multMatrix(FLOATTYPE *resMatrix, const FLOATTYPE *aMatrix); + + static void setIdentityMatrix(FLOATTYPE *mat, int size = 4); + + /// The storage for matrices + FLOATTYPE mMatrix[16]; + +}; + +#endif \ No newline at end of file diff --git a/src/gl/data/gl_portaldata.cpp b/src/gl/data/gl_portaldata.cpp new file mode 100644 index 000000000..a7e140449 --- /dev/null +++ b/src/gl/data/gl_portaldata.cpp @@ -0,0 +1,522 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_setup.cpp +** Initializes the data structures required by the GL renderer to handle +** a level +** +**/ + +#include "doomtype.h" +#include "colormatcher.h" +#include "i_system.h" +#include "p_local.h" +#include "p_lnspec.h" +#include "c_dispatch.h" +#include "r_sky.h" +#include "sc_man.h" +#include "w_wad.h" +#include "gi.h" +#include "g_level.h" +#include "a_sharedglobal.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_clipper.h" +#include "gl/scene/gl_portal.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/utility/gl_clock.h" +#include "gl/gl_functions.h" + +struct FPortalID +{ + DVector2 mDisplacement; + + // for the hash code + operator intptr_t() const { return (FLOAT2FIXED(mDisplacement.X) >> 8) + (FLOAT2FIXED(mDisplacement.Y) << 8); } + bool operator != (const FPortalID &other) const + { + return mDisplacement != other.mDisplacement; + } +}; + +struct FPortalSector +{ + sector_t *mSub; + int mPlane; +}; + +typedef TArray FPortalSectors; + +typedef TMap FPortalMap; + +TArray portals; +TArray linePortalToGL; +TArray glLinePortals; + +//========================================================================== +// +// +// +//========================================================================== + +GLSectorStackPortal *FPortal::GetRenderState() +{ + if (glportal == NULL) glportal = new GLSectorStackPortal(this); + return glportal; +} + +//========================================================================== +// +// this is left as fixed_t because the nodes also are, it makes no sense +// to convert this without converting the nodes as well. +// +//========================================================================== + +struct FCoverageVertex +{ + fixed_t x, y; + + bool operator !=(FCoverageVertex &other) + { + return x != other.x || y != other.y; + } +}; + +struct FCoverageLine +{ + FCoverageVertex v[2]; +}; + +struct FCoverageBuilder +{ + subsector_t *target; + TArray collect; + FCoverageVertex center; + + //========================================================================== + // + // + // + //========================================================================== + + FCoverageBuilder(subsector_t *sub) + { + target = sub; + } + + //========================================================================== + // + // GetIntersection + // + // adapted from P_InterceptVector + // + //========================================================================== + + bool GetIntersection(FCoverageVertex *v1, FCoverageVertex *v2, node_t *bsp, FCoverageVertex *v) + { + double frac; + double num; + double den; + + double v2x = (double)v1->x; + double v2y = (double)v1->y; + double v2dx = (double)(v2->x - v1->x); + double v2dy = (double)(v2->y - v1->y); + double v1x = (double)bsp->x; + double v1y = (double)bsp->y; + double v1dx = (double)bsp->dx; + double v1dy = (double)bsp->dy; + + den = v1dy*v2dx - v1dx*v2dy; + + if (den == 0) + return false; // parallel + + num = (v1x - v2x)*v1dy + (v2y - v1y)*v1dx; + frac = num / den; + + if (frac < 0. || frac > 1.) return false; + + v->x = xs_RoundToInt(v2x + frac * v2dx); + v->y = xs_RoundToInt(v2y + frac * v2dy); + return true; + } + + //========================================================================== + // + // + // + //========================================================================== + + double PartitionDistance(FCoverageVertex *vt, node_t *node) + { + return fabs(double(-node->dy) * (vt->x - node->x) + double(node->dx) * (vt->y - node->y)) / (node->len * 65536.); + } + + //========================================================================== + // + // + // + //========================================================================== + + int PointOnSide(FCoverageVertex *vt, node_t *node) + { + return R_PointOnSide(vt->x, vt->y, node); + } + + //========================================================================== + // + // adapted from polyobject splitter + // + //========================================================================== + + void CollectNode(void *node, TArray &shape) + { + static TArray lists[2]; + const double COVERAGE_EPSILON = 6.; // same epsilon as the node builder + + if (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + + int centerside = R_PointOnSide(center.x, center.y, bsp); + + lists[0].Clear(); + lists[1].Clear(); + for(unsigned i=0;ichildren[0], shape); + } + else if (lists[0].Size() == 0) + { + CollectNode(bsp->children[1], shape); + } + else + { + // copy the static arrays into local ones + TArray locallists[2]; + + for(int l=0;l<2;l++) + { + for (unsigned i=0;ichildren[0], locallists[0]); + CollectNode(bsp->children[1], locallists[1]); + } + } + else + { + // we reached a subsector so we can link the node with this subsector + subsector_t *sub = (subsector_t *)((BYTE *)node - 1); + collect.Push(int(sub-subsectors)); + } + } +}; + +//========================================================================== +// +// Calculate portal coverage for a single subsector +// +//========================================================================== + +void gl_BuildPortalCoverage(FPortalCoverage *coverage, subsector_t *subsector, const DVector2 &displacement) +{ + TArray shape; + double centerx=0, centery=0; + + shape.Resize(subsector->numlines); + for(unsigned i=0; inumlines; i++) + { + centerx += (shape[i].x = FLOAT2FIXED(subsector->firstline[i].v1->fX() + displacement.X)); + centery += (shape[i].y = FLOAT2FIXED(subsector->firstline[i].v1->fY() + displacement.Y)); + } + + FCoverageBuilder build(subsector); + build.center.x = xs_CRoundToInt(centerx / subsector->numlines); + build.center.y = xs_CRoundToInt(centery / subsector->numlines); + + build.CollectNode(nodes + numnodes - 1, shape); + coverage->subsectors = new DWORD[build.collect.Size()]; + coverage->sscount = build.collect.Size(); + memcpy(coverage->subsectors, &build.collect[0], build.collect.Size() * sizeof(DWORD)); +} + +//========================================================================== +// +// portal initialization +// +//========================================================================== + +static void CollectPortalSectors(FPortalMap &collection) +{ + for (int i=0;iGetPortalType(j); + if (ptype== PORTS_STACKEDSECTORTHING || ptype == PORTS_PORTAL || ptype == PORTS_LINKEDPORTAL) // only offset-displacing portal types + { + FPortalID id = { sec->GetPortalDisplacement(j) }; + + FPortalSectors &sss = collection[id]; + FPortalSector ss = { sec, j }; + sss.Push(ss); + } + } + } +} + +void gl_InitPortals() +{ + FPortalMap collection; + + if (numnodes == 0) return; + + for(int i=0;idx); + double fdy = FIXED2DBL(no->dy); + no->len = (float)sqrt(fdx * fdx + fdy * fdy); + } + + CollectPortalSectors(collection); + portals.Clear(); + + FPortalMap::Iterator it(collection); + FPortalMap::Pair *pair; + int c = 0; + int planeflags = 0; + while (it.NextPair(pair)) + { + for(unsigned i=0;iValue.Size(); i++) + { + if (pair->Value[i].mPlane == sector_t::floor) planeflags |= 1; + else if (pair->Value[i].mPlane == sector_t::ceiling) planeflags |= 2; + } + for (int i=1;i<=2;i<<=1) + { + // add separate portals for floor and ceiling. + if (planeflags & i) + { + FPortal *portal = new FPortal; + portal->mDisplacement = pair->Key.mDisplacement; + portal->plane = (i==1? sector_t::floor : sector_t::ceiling); /**/ + portal->glportal = NULL; + portals.Push(portal); + for(unsigned j=0;jValue.Size(); j++) + { + sector_t *sec = pair->Value[j].mSub; + int plane = pair->Value[j].mPlane; + if (portal->plane == plane) + { + for(int k=0;ksubsectorcount; k++) + { + subsector_t *sub = sec->subsectors[k]; + gl_BuildPortalCoverage(&sub->portalcoverage[plane], sub, pair->Key.mDisplacement); + } + sec->portals[plane] = portal; + } + } + } + } + } + + // Now group the line portals (each group must be a continuous set of colinear linedefs with no gaps) + glLinePortals.Clear(); + linePortalToGL.Clear(); + TArray tempindex; + + tempindex.Reserve(linePortals.Size()); + memset(&tempindex[0], -1, linePortals.Size() * sizeof(int)); + + for (unsigned i = 0; i < linePortals.Size(); i++) + { + auto port = linePortals[i]; + bool gotsome; + + if (tempindex[i] == -1) + { + tempindex[i] = glLinePortals.Size(); + line_t *pSrcLine = linePortals[i].mOrigin; + line_t *pLine = linePortals[i].mDestination; + FGLLinePortal &glport = glLinePortals[glLinePortals.Reserve(1)]; + glport.lines.Push(&linePortals[i]); + + // We cannot do this grouping for non-linked portals because they can be changed at run time. + if (linePortals[i].mType == PORTT_LINKED && pLine != nullptr) + { + glport.v1 = pLine->v1; + glport.v2 = pLine->v2; + do + { + // now collect all other colinear lines connected to this one. We run this loop as long as it still finds a match + gotsome = false; + for (unsigned j = 0; j < linePortals.Size(); j++) + { + if (tempindex[j] == -1) + { + line_t *pSrcLine2 = linePortals[j].mOrigin; + line_t *pLine2 = linePortals[j].mDestination; + // angular precision is intentionally reduced to 32 bit BAM to account for precision problems (otherwise many not perfectly horizontal or vertical portals aren't found here.) + unsigned srcang = pSrcLine->Delta().Angle().BAMs(); + unsigned dstang = pLine->Delta().Angle().BAMs(); + if ((pSrcLine->v2 == pSrcLine2->v1 && pLine->v1 == pLine2->v2) || + (pSrcLine->v1 == pSrcLine2->v2 && pLine->v2 == pLine2->v1)) + { + // The line connects, now check the translation + unsigned srcang2 = pSrcLine2->Delta().Angle().BAMs(); + unsigned dstang2 = pLine2->Delta().Angle().BAMs(); + if (srcang == srcang2 && dstang == dstang2) + { + // The lines connect and both source and destination are colinear, so this is a match + gotsome = true; + tempindex[j] = tempindex[i]; + if (pLine->v1 == pLine2->v2) glport.v1 = pLine2->v1; + else glport.v2 = pLine2->v2; + glport.lines.Push(&linePortals[j]); + } + } + } + } + } while (gotsome); + } + } + } + linePortalToGL.Resize(linePortals.Size()); + for (unsigned i = 0; i < linePortals.Size(); i++) + { + linePortalToGL[i] = &glLinePortals[tempindex[i]]; + /* + Printf("portal at line %d translates to GL portal %d, range = %f,%f to %f,%f\n", + int(linePortals[i].mOrigin - lines), tempindex[i], linePortalToGL[i]->v1->fixX() / 65536., linePortalToGL[i]->v1->fixY() / 65536., linePortalToGL[i]->v2->fixX() / 65536., linePortalToGL[i]->v2->fixY() / 65536.); + */ + } +} + +CCMD(dumpportals) +{ + for(unsigned i=0;imDisplacement.X; + double ydisp = portals[i]->mDisplacement.Y; + Printf(PRINT_LOG, "Portal #%d, %s, displacement = (%f,%f)\n", i, portals[i]->plane==0? "floor":"ceiling", + xdisp, ydisp); + Printf(PRINT_LOG, "Coverage:\n"); + for(int j=0;jrender_sector->GetGLPortal(portals[i]->plane); + if (port == portals[i]) + { + Printf(PRINT_LOG, "\tSubsector %d (%d):\n\t\t", j, sub->render_sector->sectornum); + for(unsigned k = 0;k< sub->numlines; k++) + { + Printf(PRINT_LOG, "(%.3f,%.3f), ", sub->firstline[k].v1->fX() + xdisp, sub->firstline[k].v1->fY() + ydisp); + } + Printf(PRINT_LOG, "\n\t\tCovered by subsectors:\n"); + FPortalCoverage *cov = &sub->portalcoverage[portals[i]->plane]; + for(int l = 0;l< cov->sscount; l++) + { + subsector_t *csub = &subsectors[cov->subsectors[l]]; + Printf(PRINT_LOG, "\t\t\t%5d (%4d): ", cov->subsectors[l], csub->render_sector->sectornum); + for(unsigned m = 0;m< csub->numlines; m++) + { + Printf(PRINT_LOG, "(%.3f,%.3f), ", csub->firstline[m].v1->fX(), csub->firstline[m].v1->fY()); + } + Printf(PRINT_LOG, "\n"); + } + } + } + } +} diff --git a/src/gl/data/gl_setup.cpp b/src/gl/data/gl_setup.cpp new file mode 100644 index 000000000..37f5c370e --- /dev/null +++ b/src/gl/data/gl_setup.cpp @@ -0,0 +1,731 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_setup.cpp +** Initializes the data structures required by the GL renderer to handle +** a level +** +**/ + +#include "gl/system/gl_system.h" +#include "doomtype.h" +#include "colormatcher.h" +#include "i_system.h" +#include "p_local.h" +#include "p_spec.h" +#include "p_lnspec.h" +#include "c_dispatch.h" +#include "r_sky.h" +#include "sc_man.h" +#include "w_wad.h" +#include "gi.h" +#include "p_setup.h" +#include "g_level.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/utility/gl_clock.h" +#include "gl/gl_functions.h" + +void InitGLRMapinfoData(); + +//========================================================================== +// +// +// +//========================================================================== +static TArray MapSectionCollector; + +static void DoSetMapSection(subsector_t *sub, int num) +{ + MapSectionCollector.Resize(1); + MapSectionCollector[0] = sub; + sub->mapsection = num; + for (unsigned a = 0; a < MapSectionCollector.Size(); a++) + { + sub = MapSectionCollector[a]; + for (DWORD i = 0; i < sub->numlines; i++) + { + seg_t * seg = sub->firstline + i; + + if (seg->PartnerSeg) + { + subsector_t * sub2 = seg->PartnerSeg->Subsector; + + if (sub2->mapsection != num) + { + assert(sub2->mapsection == 0); + sub2->mapsection = num; + MapSectionCollector.Push(sub2); + } + } + } + } + MapSectionCollector.Clear(); +} + +//========================================================================== +// +// Merge sections. This is needed in case the map contains errors +// like overlapping lines resulting in abnormal subsectors. +// +// This function ensures that any vertex position can only be in one section. +// +//========================================================================== + +struct cvertex_t +{ + double X, Y; + + operator int() const { return xs_FloorToInt(X) + 65536 * xs_FloorToInt(Y); } + bool operator!= (const cvertex_t &other) const { return fabs(X - other.X) >= EQUAL_EPSILON || fabs(Y - other.Y) >= EQUAL_EPSILON; } + cvertex_t& operator =(const vertex_t *v) { X = v->fX(); Y = v->fY(); return *this; } +}; + +typedef TMap FSectionVertexMap; + +static int MergeMapSections(int num) +{ + FSectionVertexMap vmap; + FSectionVertexMap::Pair *pair; + TArray sectmap; + TArray sectvalid; + sectmap.Resize(num); + sectvalid.Resize(num); + for(int i=0;iSubsector->mapsection; + for(int j=0;j<2;j++) + { + vt = j==0? seg->v1:seg->v2; + vmap[vt] = section; + } + } + + // second step: Check if any seg references more than one mapsection, either by subsector or by vertex + for(DWORD i=0;i<(DWORD)numsegs;i++) + { + seg_t * seg = &segs[i]; + int section = seg->Subsector->mapsection; + for(int j=0;j<2;j++) + { + vt = j==0? seg->v1:seg->v2; + int vsection = vmap[vt]; + + if (vsection != section) + { + // These 2 sections should be merged + for(int k=0;kValue == vsection) pair->Value = section; + } + sectvalid[vsection-1] = false; + } + } + } + for(int i=0;inumlines;i++) + { + seg_t * seg = sub->firstline + i; + + if (seg->PartnerSeg) + { + subsector_t * sub2 = seg->PartnerSeg->Subsector; + + if (!(sub2->hacked&1) && sub2->render_sector == sub->render_sector) + { + sub2->hacked|=1; + sub->hacked &= ~4; + SpreadHackedFlag (sub2); + } + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +static void PrepareSectorData() +{ + int i; + TArray undetermined; + subsector_t * ss; + + // now group the subsectors by sector + subsector_t ** subsectorbuffer = new subsector_t * [numsubsectors]; + + for(i=0, ss=subsectors; irender_sector->subsectorcount++; + } + + for (i=0; irender_sector->subsectors[ss->render_sector->subsectorcount++]=ss; + } + + // marks all malformed subsectors so rendering tricks using them can be handled more easily + for (i = 0; i < numsubsectors; i++) + { + if (subsectors[i].sector == subsectors[i].render_sector) + { + seg_t * seg = subsectors[i].firstline; + for(DWORD j=0;jSubsector->render_sector) + { + DPrintf(DMSG_NOTIFY, "Found hack: (%f,%f) (%f,%f)\n", seg[j].v1->fX(), seg[j].v1->fY(), seg[j].v2->fX(), seg[j].v2->fY()); + subsectors[i].hacked|=5; + SpreadHackedFlag(&subsectors[i]); + } + if (seg[j].PartnerSeg==NULL) subsectors[i].hacked|=2; // used for quick termination checks + } + } + } + SetMapSections(); +} + +//========================================================================== +// +// Some processing for transparent door hacks using a floor raised by 1 map unit +// - This will be used to lower the floor of such sectors by one map unit +// +//========================================================================== + +static void PrepareTransparentDoors(sector_t * sector) +{ + bool solidwall=false; + int notextures=0; + int nobtextures=0; + int selfref=0; + int i; + sector_t * nextsec=NULL; + +#ifdef _DEBUG + if (sector-sectors==34) + { + int a = 0; + } +#endif + + P_Recalculate3DFloors(sector); + if (sector->subsectorcount==0) return; + + sector->transdoorheight=sector->GetPlaneTexZ(sector_t::floor); + sector->transdoor= !(sector->e->XFloor.ffloors.Size() || sector->heightsec || sector->floorplane.isSlope()); + + if (sector->transdoor) + { + for (i=0; ilinecount; i++) + { + if (sector->lines[i]->frontsector==sector->lines[i]->backsector) + { + selfref++; + continue; + } + + sector_t * sec=getNextSector(sector->lines[i], sector); + if (sec==NULL) + { + solidwall=true; + continue; + } + else + { + nextsec=sec; + + int side = sector->lines[i]->sidedef[0]->sector == sec; + + if (sector->GetPlaneTexZ(sector_t::floor)!=sec->GetPlaneTexZ(sector_t::floor)+1. || sec->floorplane.isSlope()) + { + sector->transdoor=false; + return; + } + if (!sector->lines[i]->sidedef[1-side]->GetTexture(side_t::top).isValid()) notextures++; + if (!sector->lines[i]->sidedef[1-side]->GetTexture(side_t::bottom).isValid()) nobtextures++; + } + } + if (sector->GetTexture(sector_t::ceiling)==skyflatnum) + { + sector->transdoor=false; + return; + } + + if (selfref+nobtextures!=sector->linecount) + { + sector->transdoor=false; + } + + if (selfref+notextures!=sector->linecount) + { + // This is a crude attempt to fix an incorrect transparent door effect I found in some + // WolfenDoom maps but considering the amount of code required to handle it I left it in. + // Do this only if the sector only contains one-sided walls or ones with no lower texture. + if (solidwall) + { + if (solidwall+nobtextures+selfref==sector->linecount && nextsec) + { + sector->heightsec=nextsec; + sector->heightsec->MoreFlags=0; + } + sector->transdoor=false; + } + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +static void AddToVertex(const sector_t * sec, TArray & list) +{ + int secno = int(sec-sectors); + + for(unsigned i=0;i * vt_sectorlists; + + int i,j,k; + + vt_sectorlists = new TArray[numvertexes]; + + + for(i=0;iv1 : line->v2; + + for(k=0;k<2;k++) + { + sector_t * sec = k==0? line->frontsector : line->backsector; + + if (sec) + { + extsector_t::xfloor &x = sec->e->XFloor; + + AddToVertex(sec, vt_sectorlists[v-vertexes]); + if (sec->heightsec) AddToVertex(sec->heightsec, vt_sectorlists[v-vertexes]); + } + } + } + } + + for(i=0;i1) + { + vertexes[i].numsectors= cnt; + vertexes[i].sectors=new sector_t*[cnt]; + vertexes[i].heightlist = new float[cnt*2]; + for(int j=0;jsidedef[0] == &sides[sdnum]) + { + *v1 = ln->v1->fPos(); + *v2 = ln->v2->fPos(); + } + else + { + *v2 = ln->v1->fPos(); + *v1 = ln->v2->fPos(); + } +} + +static int segcmp(const void *a, const void *b) +{ + seg_t *A = *(seg_t**)a; + seg_t *B = *(seg_t**)b; + return xs_RoundToInt(FRACUNIT*(A->sidefrac - B->sidefrac)); +} + +//========================================================================== +// +// Group segs to sidedefs +// +//========================================================================== + +static void PrepareSegs() +{ + int *segcount = new int[numsides]; + int realsegs = 0; + + // Get floatng point coordinates of vertices + for(int i = 0; i < numvertexes; i++) + { + vertexes[i].dirty = true; + } + + // count the segs + memset(segcount, 0, numsides * sizeof(int)); + + // set up the extra data in case the map was loaded with regular nodes that might pass as GL nodes. + if (glsegextras == NULL) + { + for(int i=0;iPartnerSeg = &segs[partner]; + else seg->PartnerSeg = NULL; + seg->Subsector = glsegextras[i].Subsector; + } + } + + for(int i=0;isidedef == NULL) continue; // miniseg + int sidenum = int(seg->sidedef - sides); + + realsegs++; + segcount[sidenum]++; + DVector2 sidestart, sideend, segend = seg->v2->fPos(); + GetSideVertices(sidenum, &sidestart, &sideend); + + sideend -=sidestart; + segend -= sidestart; + + seg->sidefrac = float(segend.Length() / sideend.Length()); + } + + // allocate memory + sides[0].segs = new seg_t*[realsegs]; + sides[0].numsegs = 0; + + for(int i = 1; i < numsides; i++) + { + sides[i].segs = sides[i-1].segs + segcount[i-1]; + sides[i].numsegs = 0; + } + delete [] segcount; + + // assign the segs + for(int i=0;isidedef != NULL) seg->sidedef->segs[seg->sidedef->numsegs++] = seg; + } + + // sort the segs + for(int i = 0; i < numsides; i++) + { + if (sides[i].numsegs > 1) qsort(sides[i].segs, sides[i].numsegs, sizeof(seg_t*), segcmp); + } +} + +//========================================================================== +// +// Initialize the level data for the GL renderer +// +//========================================================================== +extern int restart; + +void gl_PreprocessLevel() +{ + int i; + + PrepareSegs(); + PrepareSectorData(); + InitVertexData(); + int *checkmap = new int[numvertexes]; + memset(checkmap, -1, sizeof(int)*numvertexes); + for(i=0;isidedef[0]->Flags & WALLF_POLYOBJ) continue; // don't bother with polyobjects + + int vtnum1 = int(l->v1 - vertexes); + int vtnum2 = int(l->v2 - vertexes); + + if (checkmap[vtnum1] < i) + { + checkmap[vtnum1] = i; + sectors[i].e->vertices.Push(&vertexes[vtnum1]); + vertexes[vtnum1].dirty = true; + } + + if (checkmap[vtnum2] < i) + { + checkmap[vtnum2] = i; + sectors[i].e->vertices.Push(&vertexes[vtnum2]); + vertexes[vtnum2].dirty = true; + } + } + } + delete[] checkmap; + + gl_InitPortals(); + + if (GLRenderer != NULL) + { + GLRenderer->SetupLevel(); + } + +#if 0 + gl_CreateSections(); +#endif + + InitGLRMapinfoData(); +} + + + +//========================================================================== +// +// Cleans up all the GL data for the last level +// +//========================================================================== + +void gl_CleanLevelData() +{ + // Dynamic lights must be destroyed before the sector information here is deleted. + TThinkerIterator it(STAT_DLIGHT); + AActor * mo=it.Next(); + while (mo) + { + AActor * next = it.Next(); + mo->Destroy(); + mo=next; + } + + if (vertexes != NULL) + { + for(int i = 0; i < numvertexes; i++) if (vertexes[i].numsectors > 0) + { + if (vertexes[i].sectors != NULL) + { + delete [] vertexes[i].sectors; + vertexes[i].sectors = NULL; + } + if (vertexes[i].heightlist != NULL) + { + delete [] vertexes[i].heightlist; + vertexes[i].heightlist = NULL; + } + } + } + + if (sides && sides[0].segs) + { + delete [] sides[0].segs; + sides[0].segs = NULL; + } + if (sectors && sectors[0].subsectors) + { + delete [] sectors[0].subsectors; + sectors[0].subsectors = NULL; + } + for (int i=0;isectornum, int(subsectors[j].firstline->linedef-lines)); + break; + } + } + } +} diff --git a/src/gl/data/gl_vertexbuffer.cpp b/src/gl/data/gl_vertexbuffer.cpp new file mode 100644 index 000000000..d14599eb8 --- /dev/null +++ b/src/gl/data/gl_vertexbuffer.cpp @@ -0,0 +1,494 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_vertexbuffer.cpp +** Vertex buffer handling. +** +**/ + +#include "gl/system/gl_system.h" +#include "doomtype.h" +#include "p_local.h" +#include "r_state.h" +#include "m_argv.h" +#include "c_cvars.h" +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/shaders/gl_shader.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" + + +//========================================================================== +// +// Create / destroy the VBO +// +//========================================================================== + +FVertexBuffer::FVertexBuffer(bool wantbuffer) +{ + vbo_id = 0; + if (wantbuffer) glGenBuffers(1, &vbo_id); +} + +FVertexBuffer::~FVertexBuffer() +{ + if (vbo_id != 0) + { + glDeleteBuffers(1, &vbo_id); + } +} + + +void FSimpleVertexBuffer::BindVBO() +{ + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + if (!gl.legacyMode) + { + glVertexAttribPointer(VATTR_VERTEX, 3, GL_FLOAT, false, sizeof(FSimpleVertex), &VSiO->x); + glVertexAttribPointer(VATTR_TEXCOORD, 2, GL_FLOAT, false, sizeof(FSimpleVertex), &VSiO->u); + glVertexAttribPointer(VATTR_COLOR, 4, GL_UNSIGNED_BYTE, true, sizeof(FSimpleVertex), &VSiO->color); + glEnableVertexAttribArray(VATTR_VERTEX); + glEnableVertexAttribArray(VATTR_TEXCOORD); + glEnableVertexAttribArray(VATTR_COLOR); + glDisableVertexAttribArray(VATTR_VERTEX2); + glDisableVertexAttribArray(VATTR_NORMAL); + } + else + { + glVertexPointer(3, GL_FLOAT, sizeof(FSimpleVertex), &VSiO->x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FSimpleVertex), &VSiO->u); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(FSimpleVertex), &VSiO->color); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + } +} + +void FSimpleVertexBuffer::EnableColorArray(bool on) +{ + if (on) + { + if (!gl.legacyMode) + { + glEnableVertexAttribArray(VATTR_COLOR); + } + else + { + glEnableClientState(GL_COLOR_ARRAY); + } + } + else + { + if (!gl.legacyMode) + { + glDisableVertexAttribArray(VATTR_COLOR); + } + else + { + glDisableClientState(GL_COLOR_ARRAY); + } + } +} + + +void FSimpleVertexBuffer::set(FSimpleVertex *verts, int count) +{ + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + gl_RenderState.ResetVertexBuffer(); + gl_RenderState.SetVertexBuffer(this); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(*verts), verts, GL_STREAM_DRAW); +} + +//========================================================================== +// +// +// +//========================================================================== + +FFlatVertexBuffer::FFlatVertexBuffer(int width, int height) +: FVertexBuffer(!gl.legacyMode) +{ + switch (gl.buffermethod) + { + case BM_PERSISTENT: + { + unsigned int bytesize = BUFFER_SIZE * sizeof(FFlatVertex); + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glBufferStorage(GL_ARRAY_BUFFER, bytesize, NULL, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + map = (FFlatVertex*)glMapBufferRange(GL_ARRAY_BUFFER, 0, bytesize, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + DPrintf(DMSG_NOTIFY, "Using persistent buffer\n"); + break; + } + + case BM_DEFERRED: + { + unsigned int bytesize = BUFFER_SIZE * sizeof(FFlatVertex); + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glBufferData(GL_ARRAY_BUFFER, bytesize, NULL, GL_STREAM_DRAW); + map = nullptr; + DPrintf(DMSG_NOTIFY, "Using deferred buffer\n"); + break; + } + + default: + { + map = new FFlatVertex[BUFFER_SIZE]; + DPrintf(DMSG_NOTIFY, "Using client array buffer\n"); + break; + } + } + mIndex = mCurIndex = 0; + mNumReserved = NUM_RESERVED; + vbo_shadowdata.Resize(mNumReserved); + + // the first quad is reserved for handling coordinates through uniforms. + vbo_shadowdata[0].Set(0, 0, 0, 0, 0); + vbo_shadowdata[1].Set(1, 0, 0, 0, 0); + vbo_shadowdata[2].Set(2, 0, 0, 0, 0); + vbo_shadowdata[3].Set(3, 0, 0, 0, 0); + + // and the second one for the fullscreen quad used for blend overlays. + vbo_shadowdata[4].Set(0, 0, 0, 0, 0); + vbo_shadowdata[5].Set(0, (float)height, 0, 0, 0); + vbo_shadowdata[6].Set((float)width, 0, 0, 0, 0); + vbo_shadowdata[7].Set((float)width, (float)height, 0, 0, 0); + + // and this is for the postprocessing copy operation + vbo_shadowdata[8].Set(-1.0f, -1.0f, 0, 0.0f, 0.0f); + vbo_shadowdata[9].Set(-1.0f, 1.0f, 0, 0.0f, 1.f); + vbo_shadowdata[10].Set(1.0f, -1.0f, 0, 1.f, 0.0f); + vbo_shadowdata[11].Set(1.0f, 1.0f, 0, 1.f, 1.f); + + // The next two are the stencil caps. + vbo_shadowdata[12].Set(-32767.0f, 32767.0f, -32767.0f, 0, 0); + vbo_shadowdata[13].Set(-32767.0f, 32767.0f, 32767.0f, 0, 0); + vbo_shadowdata[14].Set(32767.0f, 32767.0f, 32767.0f, 0, 0); + vbo_shadowdata[15].Set(32767.0f, 32767.0f, -32767.0f, 0, 0); + + vbo_shadowdata[16].Set(-32767.0f, -32767.0f, -32767.0f, 0, 0); + vbo_shadowdata[17].Set(-32767.0f, -32767.0f, 32767.0f, 0, 0); + vbo_shadowdata[18].Set(32767.0f, -32767.0f, 32767.0f, 0, 0); + vbo_shadowdata[19].Set(32767.0f, -32767.0f, -32767.0f, 0, 0); + + if (gl.buffermethod == BM_DEFERRED) + { + Map(); + memcpy(map, &vbo_shadowdata[0], mNumReserved * sizeof(FFlatVertex)); + Unmap(); + } + +} + +FFlatVertexBuffer::~FFlatVertexBuffer() +{ + if (vbo_id != 0) + { + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glUnmapBuffer(GL_ARRAY_BUFFER); + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + if (gl.legacyMode) + { + delete[] map; + } + map = nullptr; +} + +void FFlatVertexBuffer::OutputResized(int width, int height) +{ + vbo_shadowdata[4].Set(0, 0, 0, 0, 0); + vbo_shadowdata[5].Set(0, (float)height, 0, 0, 0); + vbo_shadowdata[6].Set((float)width, 0, 0, 0, 0); + vbo_shadowdata[7].Set((float)width, (float)height, 0, 0, 0); + + Map(); + memcpy(&map[4], &vbo_shadowdata[4], 4 * sizeof(FFlatVertex)); + Unmap(); +} + +void FFlatVertexBuffer::BindVBO() +{ + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + if (!gl.legacyMode) + { + glVertexAttribPointer(VATTR_VERTEX, 3, GL_FLOAT, false, sizeof(FFlatVertex), &VTO->x); + glVertexAttribPointer(VATTR_TEXCOORD, 2, GL_FLOAT, false, sizeof(FFlatVertex), &VTO->u); + glEnableVertexAttribArray(VATTR_VERTEX); + glEnableVertexAttribArray(VATTR_TEXCOORD); + glDisableVertexAttribArray(VATTR_COLOR); + glDisableVertexAttribArray(VATTR_VERTEX2); + glDisableVertexAttribArray(VATTR_NORMAL); + } + else + { + glVertexPointer(3, GL_FLOAT, sizeof(FFlatVertex), &map->x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FFlatVertex), &map->u); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + } +} + +void FFlatVertexBuffer::Map() +{ + if (gl.buffermethod == BM_DEFERRED) + { + unsigned int bytesize = BUFFER_SIZE * sizeof(FFlatVertex); + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + gl_RenderState.ResetVertexBuffer(); + map = (FFlatVertex*)glMapBufferRange(GL_ARRAY_BUFFER, 0, bytesize, GL_MAP_WRITE_BIT|GL_MAP_UNSYNCHRONIZED_BIT); + } +} + +void FFlatVertexBuffer::Unmap() +{ + if (gl.buffermethod == BM_DEFERRED) + { + unsigned int bytesize = BUFFER_SIZE * sizeof(FFlatVertex); + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + gl_RenderState.ResetVertexBuffer(); + glUnmapBuffer(GL_ARRAY_BUFFER); + map = nullptr; + } +} + +//========================================================================== +// +// Initialize a single vertex +// +//========================================================================== + +void FFlatVertex::SetFlatVertex(vertex_t *vt, const secplane_t & plane) +{ + x = vt->fX(); + y = vt->fY(); + z = plane.ZatPoint(vt); + u = vt->fX()/64.f; + v = -vt->fY()/64.f; +} + +//========================================================================== +// +// Find a 3D floor +// +//========================================================================== + +static F3DFloor *Find3DFloor(sector_t *target, sector_t *model) +{ + for(unsigned i=0; ie->XFloor.ffloors.Size(); i++) + { + F3DFloor *ffloor = target->e->XFloor.ffloors[i]; + if (ffloor->model == model) return ffloor; + } + return NULL; +} + +//========================================================================== +// +// Creates the vertices for one plane in one subsector +// +//========================================================================== + +int FFlatVertexBuffer::CreateSubsectorVertices(subsector_t *sub, const secplane_t &plane, int floor) +{ + int idx = vbo_shadowdata.Reserve(sub->numlines); + for(unsigned int k=0; knumlines; k++, idx++) + { + vbo_shadowdata[idx].SetFlatVertex(sub->firstline[k].v1, plane); + if (sub->sector->transdoor && floor) vbo_shadowdata[idx].z -= 1.f; + } + return idx; +} + +//========================================================================== +// +// Creates the vertices for one plane in one subsector +// +//========================================================================== + +int FFlatVertexBuffer::CreateSectorVertices(sector_t *sec, const secplane_t &plane, int floor) +{ + int rt = vbo_shadowdata.Size(); + // First calculate the vertices for the sector itself + for(int j=0; jsubsectorcount; j++) + { + subsector_t *sub = sec->subsectors[j]; + CreateSubsectorVertices(sub, plane, floor); + } + return rt; +} + +//========================================================================== +// +// +// +//========================================================================== + +int FFlatVertexBuffer::CreateVertices(int h, sector_t *sec, const secplane_t &plane, int floor) +{ + // First calculate the vertices for the sector itself + sec->vboheight[h] = sec->GetPlaneTexZ(h); + sec->vboindex[h] = CreateSectorVertices(sec, plane, floor); + + // Next are all sectors using this one as heightsec + TArray &fakes = sec->e->FakeFloor.Sectors; + for (unsigned g=0; gvboindex[2+h] = CreateSectorVertices(fsec, plane, false); + } + + // and finally all attached 3D floors + TArray &xf = sec->e->XFloor.attached; + for (unsigned g=0; gflags & FF_RENDERPLANES) + { + bool dotop = (ffloor->top.model == sec) && (ffloor->top.isceiling == h); + bool dobottom = (ffloor->bottom.model == sec) && (ffloor->bottom.isceiling == h); + + if (dotop || dobottom) + { + if (dotop) ffloor->top.vindex = vbo_shadowdata.Size(); + if (dobottom) ffloor->bottom.vindex = vbo_shadowdata.Size(); + + CreateSectorVertices(fsec, plane, false); + } + } + } + sec->vbocount[h] = vbo_shadowdata.Size() - sec->vboindex[h]; + return sec->vboindex[h]; +} + + +//========================================================================== +// +// +// +//========================================================================== + +void FFlatVertexBuffer::CreateFlatVBO() +{ + for (int h = sector_t::floor; h <= sector_t::ceiling; h++) + { + for(int i=0; iXFloor.ffloors.Size(); j++) + { + F3DFloor *ff = sectors[i].e->XFloor.ffloors[j]; + + if (ff->top.model == §ors[i]) + { + ff->top.vindex = sectors[i].vboindex[ff->top.isceiling]; + } + if (ff->bottom.model == §ors[i]) + { + ff->bottom.vindex = sectors[i].vboindex[ff->top.isceiling]; + } + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FFlatVertexBuffer::UpdatePlaneVertices(sector_t *sec, int plane) +{ + int startvt = sec->vboindex[plane]; + int countvt = sec->vbocount[plane]; + secplane_t &splane = sec->GetSecPlane(plane); + FFlatVertex *vt = &vbo_shadowdata[startvt]; + FFlatVertex *mapvt = &map[startvt]; + for(int i=0; iz = splane.ZatPoint(vt->x, vt->y); + if (plane == sector_t::floor && sec->transdoor) vt->z -= 1; + mapvt->z = vt->z; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FFlatVertexBuffer::CreateVBO() +{ + vbo_shadowdata.Resize(mNumReserved); + CreateFlatVBO(); + mCurIndex = mIndex = vbo_shadowdata.Size(); + Map(); + memcpy(map, &vbo_shadowdata[0], vbo_shadowdata.Size() * sizeof(FFlatVertex)); + Unmap(); +} + +//========================================================================== +// +// +// +//========================================================================== + +void FFlatVertexBuffer::CheckPlanes(sector_t *sector) +{ + if (sector->GetPlaneTexZ(sector_t::ceiling) != sector->vboheight[sector_t::ceiling]) + { + UpdatePlaneVertices(sector, sector_t::ceiling); + sector->vboheight[sector_t::ceiling] = sector->GetPlaneTexZ(sector_t::ceiling); + } + if (sector->GetPlaneTexZ(sector_t::floor) != sector->vboheight[sector_t::floor]) + { + UpdatePlaneVertices(sector, sector_t::floor); + sector->vboheight[sector_t::floor] = sector->GetPlaneTexZ(sector_t::floor); + } +} + +//========================================================================== +// +// checks the validity of all planes attached to this sector +// and updates them if possible. +// +//========================================================================== + +void FFlatVertexBuffer::CheckUpdate(sector_t *sector) +{ + CheckPlanes(sector); + sector_t *hs = sector->GetHeightSec(); + if (hs != NULL) CheckPlanes(hs); + for (unsigned i = 0; i < sector->e->XFloor.ffloors.Size(); i++) + CheckPlanes(sector->e->XFloor.ffloors[i]->model); +} \ No newline at end of file diff --git a/src/gl/data/gl_vertexbuffer.h b/src/gl/data/gl_vertexbuffer.h new file mode 100644 index 000000000..f777118fd --- /dev/null +++ b/src/gl/data/gl_vertexbuffer.h @@ -0,0 +1,322 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#ifndef __VERTEXBUFFER_H +#define __VERTEXBUFFER_H + +#include "tarray.h" +#include "gl/utility/gl_clock.h" +#include "gl/system/gl_interface.h" + +struct vertex_t; +struct secplane_t; +struct subsector_t; +struct sector_t; + +enum +{ + VATTR_VERTEX_BIT, + VATTR_TEXCOORD_BIT, + VATTR_COLOR_BIT, + VATTR_VERTEX2_BIT, + VATTR_NORMAL_BIT +}; + + +class FVertexBuffer +{ +protected: + unsigned int vbo_id; + +public: + FVertexBuffer(bool wantbuffer = true); + virtual ~FVertexBuffer(); + virtual void BindVBO() = 0; + void EnableBufferArrays(int enable, int disable); +}; + +struct FFlatVertex +{ + float x,z,y; // world position + float u,v; // texture coordinates + + void SetFlatVertex(vertex_t *vt, const secplane_t &plane); + void Set(float xx, float zz, float yy, float uu, float vv) + { + x = xx; + z = zz; + y = yy; + u = uu; + v = vv; + } +}; + +struct FSimpleVertex +{ + float x, z, y; // world position + float u, v; // texture coordinates + PalEntry color; + + void Set(float xx, float zz, float yy, float uu = 0, float vv = 0, PalEntry col = 0xffffffff) + { + x = xx; + z = zz; + y = yy; + u = uu; + v = vv; + color = col; + } +}; + +#define VTO ((FFlatVertex*)NULL) +#define VSiO ((FSimpleVertex*)NULL) + +class FSimpleVertexBuffer : public FVertexBuffer +{ + TArray mBuffer; +public: + FSimpleVertexBuffer() + { + } + void BindVBO(); + void set(FSimpleVertex *verts, int count); + void EnableColorArray(bool on); +}; + +class FFlatVertexBuffer : public FVertexBuffer +{ + FFlatVertex *map; + unsigned int mIndex; + unsigned int mCurIndex; + unsigned int mNumReserved; + + void CheckPlanes(sector_t *sector); + + static const unsigned int BUFFER_SIZE = 2000000; + static const unsigned int BUFFER_SIZE_TO_USE = 1999500; + +public: + enum + { + QUAD_INDEX = 0, + FULLSCREEN_INDEX = 4, + PRESENT_INDEX = 8, + STENCILTOP_INDEX = 12, + STENCILBOTTOM_INDEX = 16, + + NUM_RESERVED = 20 + }; + + TArray vbo_shadowdata; // this is kept around for updating the actual (non-readable) buffer and as stand-in for pre GL 4.x + + FFlatVertexBuffer(int width, int height); + ~FFlatVertexBuffer(); + + void OutputResized(int width, int height); + + void BindVBO(); + + void CreateVBO(); + void CheckUpdate(sector_t *sector); + + FFlatVertex *GetBuffer() + { + return &map[mCurIndex]; + } + FFlatVertex *Alloc(int num, int *poffset) + { + FFlatVertex *p = GetBuffer(); + *poffset = mCurIndex; + mCurIndex += num; + if (mCurIndex >= BUFFER_SIZE_TO_USE) mCurIndex = mIndex; + return p; + } + + unsigned int GetCount(FFlatVertex *newptr, unsigned int *poffset) + { + unsigned int newofs = (unsigned int)(newptr - map); + unsigned int diff = newofs - mCurIndex; + *poffset = mCurIndex; + mCurIndex = newofs; + if (mCurIndex >= BUFFER_SIZE_TO_USE) mCurIndex = mIndex; + return diff; + } +#ifdef __GL_PCH_H // we need the system includes for this but we cannot include them ourselves without creating #define clashes. The affected files wouldn't try to draw anyway. + void RenderArray(unsigned int primtype, unsigned int offset, unsigned int count) + { + drawcalls.Clock(); + glDrawArrays(primtype, offset, count); + drawcalls.Unclock(); + } + + void RenderCurrent(FFlatVertex *newptr, unsigned int primtype, unsigned int *poffset = NULL, unsigned int *pcount = NULL) + { + unsigned int offset; + unsigned int count = GetCount(newptr, &offset); + RenderArray(primtype, offset, count); + if (poffset) *poffset = offset; + if (pcount) *pcount = count; + } + +#endif + void Reset() + { + mCurIndex = mIndex; + } + + void Map(); + void Unmap(); + +private: + int CreateSubsectorVertices(subsector_t *sub, const secplane_t &plane, int floor); + int CreateSectorVertices(sector_t *sec, const secplane_t &plane, int floor); + int CreateVertices(int h, sector_t *sec, const secplane_t &plane, int floor); + void CreateFlatVBO(); + void UpdatePlaneVertices(sector_t *sec, int plane); + +}; + + +struct FSkyVertex +{ + float x, y, z, u, v; + PalEntry color; + + void Set(float xx, float zz, float yy, float uu=0, float vv=0, PalEntry col=0xffffffff) + { + x = xx; + z = zz; + y = yy; + u = uu; + v = vv; + color = col; + } + + void SetXYZ(float xx, float yy, float zz, float uu = 0, float vv = 0, PalEntry col = 0xffffffff) + { + x = xx; + y = yy; + z = zz; + u = uu; + v = vv; + color = col; + } + +}; + +class FSkyVertexBuffer : public FVertexBuffer +{ +public: + static const int SKYHEMI_UPPER = 1; + static const int SKYHEMI_LOWER = 2; + + enum + { + SKYMODE_MAINLAYER = 0, + SKYMODE_SECONDLAYER = 1, + SKYMODE_FOGLAYER = 2 + }; + +private: + TArray mVertices; + TArray mPrimStart; + + int mRows, mColumns; + + // indices for sky cubemap faces + int mFaceStart[7]; + int mSideStart; + + void SkyVertex(int r, int c, bool yflip); + void CreateSkyHemisphere(int hemi); + void CreateDome(); + void RenderRow(int prim, int row); + +public: + + FSkyVertexBuffer(); + virtual ~FSkyVertexBuffer(); + void RenderDome(FMaterial *tex, int mode); + void BindVBO(); + int FaceStart(int i) + { + if (i >= 0 && i < 7) return mFaceStart[i]; + else return mSideStart; + } + +}; + +#define VSO ((FSkyVertex*)NULL) + +struct FModelVertex +{ + float x, y, z; // world position + float u, v; // texture coordinates + unsigned packedNormal; // normal vector as GL_INT_2_10_10_10_REV. + + void Set(float xx, float yy, float zz, float uu, float vv) + { + x = xx; + y = yy; + z = zz; + u = uu; + v = vv; + } + + void SetNormal(float nx, float ny, float nz) + { + /* + int inx = int(nx * 512); + int iny = int(ny * 512); + int inz = int(nz * 512); + packedNormal = 0x40000000 | ((inx & 1023) << 20) | ((iny & 1023) << 10) | (inz & 1023); + */ + packedNormal = 0; // Per-pixel lighting for models isn't implemented yet so leave this at 0 for now. + } +}; + + +class FModelVertexBuffer : public FVertexBuffer +{ + int mIndexFrame[2]; + FModelVertex *vbo_ptr; + uint32_t ibo_id; + +public: + + FModelVertexBuffer(bool needindex, bool singleframe); + ~FModelVertexBuffer(); + + FModelVertex *LockVertexBuffer(unsigned int size); + void UnlockVertexBuffer(); + + unsigned int *LockIndexBuffer(unsigned int size); + void UnlockIndexBuffer(); + + unsigned int SetupFrame(unsigned int frame1, unsigned int frame2, unsigned int size); + void BindVBO(); +}; + +#define VMO ((FModelVertex*)NULL) + + +#endif \ No newline at end of file diff --git a/src/gl/dynlights/a_dynlight.cpp b/src/gl/dynlights/a_dynlight.cpp new file mode 100644 index 000000000..40420963c --- /dev/null +++ b/src/gl/dynlights/a_dynlight.cpp @@ -0,0 +1,888 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** a_dynlight.cpp +** Implements actors representing dynamic lights (hardware independent) +** +** +** all functions marked with [TS] are licensed under +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "gl/system/gl_system.h" + +#include "templates.h" +#include "m_random.h" +#include "p_local.h" +#include "c_dispatch.h" +#include "g_level.h" +#include "scripting/thingdef.h" +#include "i_system.h" +#include "templates.h" +#include "doomdata.h" +#include "r_utility.h" +#include "p_local.h" +#include "portal.h" +#include "doomstat.h" +#include "serializer.h" + + +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/utility/gl_convert.h" +#include "gl/utility/gl_templates.h" + + + +//========================================================================== +// +//========================================================================== +DEFINE_CLASS_PROPERTY(type, S, DynamicLight) +{ + PROP_STRING_PARM(str, 0); + static const char * ltype_names[]={ + "Point","Pulse","Flicker","Sector","RandomFlicker", "ColorPulse", "ColorFlicker", "RandomColorFlicker", NULL}; + + static const int ltype_values[]={ + PointLight, PulseLight, FlickerLight, SectorLight, RandomFlickerLight, ColorPulseLight, ColorFlickerLight, RandomColorFlickerLight }; + + int style = MatchString(str, ltype_names); + if (style < 0) I_Error("Unknown light type '%s'", str); + defaults->lighttype = ltype_values[style]; +} + +//========================================================================== +// +// Actor classes +// +// For flexibility all functionality has been packed into a single class +// which is controlled by flags +// +//========================================================================== +IMPLEMENT_CLASS (ADynamicLight, false, false) +IMPLEMENT_CLASS (AVavoomLight, false, false) +IMPLEMENT_CLASS (AVavoomLightWhite, false, false) +IMPLEMENT_CLASS (AVavoomLightColor, false, false) + +void AVavoomLight::BeginPlay () +{ + // This must not call Super::BeginPlay! + ChangeStatNum(STAT_DLIGHT); + if (Sector) AddZ(-Sector->floorplane.ZatPoint(this), false); + lighttype = PointLight; +} + +void AVavoomLightWhite::BeginPlay () +{ + m_Radius[0] = args[0] * 4; + args[LIGHT_RED] = 128; + args[LIGHT_GREEN] = 128; + args[LIGHT_BLUE] = 128; + + Super::BeginPlay(); +} + +void AVavoomLightColor::BeginPlay () +{ + int l_args[5]; + memcpy(l_args, args, sizeof(l_args)); + memset(args, 0, sizeof(args)); + m_Radius[0] = l_args[0] * 4; + args[LIGHT_RED] = l_args[1] >> 1; + args[LIGHT_GREEN] = l_args[2] >> 1; + args[LIGHT_BLUE] = l_args[3] >> 1; + + Super::BeginPlay(); +} + +static FRandom randLight; + +//========================================================================== +// +// Base class +// +//========================================================================== + +//========================================================================== +// +// +// +//========================================================================== +void ADynamicLight::Serialize(FSerializer &arc) +{ + Super::Serialize (arc); + auto def = static_cast(GetDefault()); + arc("lightflags", lightflags, def->lightflags) + ("lighttype", lighttype, def->lighttype) + ("tickcount", m_tickCount, def->m_tickCount) + ("currentradius", m_currentRadius, def->m_currentRadius) + .Array("lightradius", m_Radius, def->m_Radius, 2); + + if (lighttype == PulseLight) + arc("lastupdate", m_lastUpdate, def->m_lastUpdate) + ("cycler", m_cycler, def->m_cycler); +} + + +void ADynamicLight::PostSerialize() +{ + Super::PostSerialize(); + // The default constructor which is used for creating objects before deserialization will not set this variable. + // It needs to be true for all placed lights. + visibletoplayer = true; + LinkLight(); +} + +//========================================================================== +// +// [TS] +// +//========================================================================== +void ADynamicLight::BeginPlay() +{ + //Super::BeginPlay(); + ChangeStatNum(STAT_DLIGHT); + + m_Radius[0] = args[LIGHT_INTENSITY]; + m_Radius[1] = args[LIGHT_SECONDARY_INTENSITY]; + specialf1 = DAngle(double(SpawnAngle)).Normalized360().Degrees; + visibletoplayer = true; +} + +//========================================================================== +// +// [TS] +// +//========================================================================== +void ADynamicLight::PostBeginPlay() +{ + Super::PostBeginPlay(); + + if (!(SpawnFlags & MTF_DORMANT)) + { + Activate (NULL); + } + + subsector = R_PointInSubsector(Pos()); +} + + +//========================================================================== +// +// [TS] +// +//========================================================================== +void ADynamicLight::Activate(AActor *activator) +{ + //Super::Activate(activator); + flags2&=~MF2_DORMANT; + + m_currentRadius = float(m_Radius[0]); + m_tickCount = 0; + + if (lighttype == PulseLight) + { + float pulseTime = specialf1 / TICRATE; + + m_lastUpdate = level.maptime; + m_cycler.SetParams(float(m_Radius[1]), float(m_Radius[0]), pulseTime); + m_cycler.ShouldCycle(true); + m_cycler.SetCycleType(CYCLE_Sin); + m_currentRadius = m_cycler.GetVal(); + } +} + + +//========================================================================== +// +// [TS] +// +//========================================================================== +void ADynamicLight::Deactivate(AActor *activator) +{ + //Super::Deactivate(activator); + flags2|=MF2_DORMANT; +} + + +//========================================================================== +// +// [TS] +// +//========================================================================== +void ADynamicLight::Tick() +{ + if (IsOwned()) + { + if (!target || !target->state) + { + this->Destroy(); + return; + } + if (target->flags & MF_UNMORPHED) return; + visibletoplayer = target->IsVisibleToPlayer(); // cache this value for the renderer to speed up calculations. + } + + // Don't bother if the light won't be shown + if (!IsActive()) return; + + // I am doing this with a type field so that I can dynamically alter the type of light + // without having to create or maintain multiple objects. + switch(lighttype) + { + case PulseLight: + { + float diff = (level.maptime - m_lastUpdate) / (float)TICRATE; + + m_lastUpdate = level.maptime; + m_cycler.Update(diff); + m_currentRadius = m_cycler.GetVal(); + break; + } + + case FlickerLight: + { + BYTE rnd = randLight(); + float pct = specialf1 / 360.f; + + m_currentRadius = float(m_Radius[rnd >= pct * 255]); + break; + } + + case RandomFlickerLight: + { + int flickerRange = m_Radius[1] - m_Radius[0]; + float amt = randLight() / 255.f; + + if (m_tickCount > specialf1) + { + m_tickCount = 0; + } + if (m_tickCount++ == 0 || m_currentRadius > m_Radius[1]) + { + m_currentRadius = float(m_Radius[0] + (amt * flickerRange)); + } + break; + } + +#if 0 + // These need some more work elsewhere + case ColorFlickerLight: + { + BYTE rnd = randLight(); + float pct = specialf1/360.f; + + m_currentRadius = m_Radius[rnd >= pct * 255]; + break; + } + + case RandomColorFlickerLight: + { + int flickerRange = m_Radius[1] - m_Radius[0]; + float amt = randLight() / 255.f; + + m_tickCount++; + + if (m_tickCount > specialf1) + { + m_currentRadius = m_Radius[0] + (amt * flickerRange); + m_tickCount = 0; + } + break; + } +#endif + + case SectorLight: + { + float intensity; + float scale = args[LIGHT_SCALE] / 8.f; + + if (scale == 0.f) scale = 1.f; + + intensity = Sector->lightlevel * scale; + intensity = clamp(intensity, 0.f, 255.f); + + m_currentRadius = intensity; + break; + } + + case PointLight: + m_currentRadius = float(m_Radius[0]); + break; + } + UpdateLocation(); +} + + + + +//========================================================================== +// +// +// +//========================================================================== +void ADynamicLight::UpdateLocation() +{ + double oldx= X(); + double oldy= Y(); + double oldradius= radius; + float intensity; + + if (IsActive()) + { + if (target) + { + DAngle angle = target->Angles.Yaw; + double s = angle.Sin(); + double c = angle.Cos(); + + DVector3 pos = target->Vec3Offset(m_off.X * c + m_off.Y * s, m_off.X * s - m_off.Y * c, m_off.Z + target->GetBobOffset()); + SetXYZ(pos); // attached lights do not need to go into the regular blockmap + Prev = target->Pos(); + subsector = R_PointInSubsector(Prev); + Sector = subsector->sector; + + // Some z-coordinate fudging to prevent the light from getting too close to the floor or ceiling planes. With proper attenuation this would render them invisible. + // A distance of 5 is needed so that the light's effect doesn't become too small. + if (Z() < target->floorz + 5.) SetZ(target->floorz + 5.); + else if (Z() > target->ceilingz - 5.) SetZ(target->ceilingz - 5.); + } + else + { + if (Z() < floorz + 5.) SetZ(floorz + 5.); + else if (Z() > ceilingz - 5.) SetZ(ceilingz - 5.); + } + + + // The radius being used here is always the maximum possible with the + // current settings. This avoids constant relinking of flickering lights + + if (lighttype == FlickerLight || lighttype == RandomFlickerLight || lighttype == PulseLight) + { + intensity = float(MAX(m_Radius[0], m_Radius[1])); + } + else + { + intensity = m_currentRadius; + } + radius = intensity * 2.0f; + assert(radius >= m_currentRadius * 2); + + if (X() != oldx || Y() != oldy || radius != oldradius) + { + //Update the light lists + LinkLight(); + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +void ADynamicLight::SetOrigin(double x, double y, double z, bool moving) +{ + Super::SetOrigin(x, y, z, moving); + LinkLight(); +} + +//========================================================================== +// +// +// +//========================================================================== + +void ADynamicLight::SetOffset(const DVector3 &pos) +{ + m_off = pos; + UpdateLocation(); +} + + +//========================================================================== +// +// The target pointer in dynamic lights should never be substituted unless +// notOld is NULL (which indicates that the object was destroyed by force.) +// +//========================================================================== +size_t ADynamicLight::PointerSubstitution (DObject *old, DObject *notOld) +{ + AActor *saved_target = target; + size_t ret = Super::PointerSubstitution(old, notOld); + if (notOld != NULL) target = saved_target; + return ret; +} + +//============================================================================= +// +// These have been copied from the secnode code and modified for the light links +// +// P_AddSecnode() searches the current list to see if this sector is +// already there. If not, it adds a sector node at the head of the list of +// sectors this object appears in. This is called when creating a list of +// nodes that will get linked in later. Returns a pointer to the new node. +// +//============================================================================= + +FLightNode * AddLightNode(FLightNode ** thread, void * linkto, ADynamicLight * light, FLightNode *& nextnode) +{ + FLightNode * node; + + node = nextnode; + while (node) + { + if (node->targ==linkto) // Already have a node for this sector? + { + node->lightsource = light; // Yes. Setting m_thing says 'keep it'. + return(nextnode); + } + node = node->nextTarget; + } + + // Couldn't find an existing node for this sector. Add one at the head + // of the list. + + node = new FLightNode; + + node->targ = linkto; + node->lightsource = light; + + node->prevTarget = &nextnode; + node->nextTarget = nextnode; + + if (nextnode) nextnode->prevTarget = &node->nextTarget; + + // Add new node at head of sector thread starting at s->touching_thinglist + + node->prevLight = thread; + node->nextLight = *thread; + if (node->nextLight) node->nextLight->prevLight=&node->nextLight; + *thread = node; + return(node); +} + + +//============================================================================= +// +// P_DelSecnode() deletes a sector node from the list of +// sectors this object appears in. Returns a pointer to the next node +// on the linked list, or NULL. +// +//============================================================================= + +static FLightNode * DeleteLightNode(FLightNode * node) +{ + FLightNode * tn; // next node on thing thread + + if (node) + { + + *node->prevTarget = node->nextTarget; + if (node->nextTarget) node->nextTarget->prevTarget=node->prevTarget; + + *node->prevLight = node->nextLight; + if (node->nextLight) node->nextLight->prevLight=node->prevLight; + + // Return this node to the freelist + tn=node->nextTarget; + delete node; + return(tn); + } + return(NULL); +} // phares 3/13/98 + + + +//========================================================================== +// +// Gets the light's distance to a line +// +//========================================================================== + +double ADynamicLight::DistToSeg(const DVector3 &pos, seg_t *seg) +{ + double u, px, py; + + double seg_dx = seg->v2->fX() - seg->v1->fX(); + double seg_dy = seg->v2->fY() - seg->v1->fY(); + double seg_length_sq = seg_dx * seg_dx + seg_dy * seg_dy; + + u = (((pos.X - seg->v1->fX()) * seg_dx) + (pos.Y - seg->v1->fY()) * seg_dy) / seg_length_sq; + if (u < 0.) u = 0.; // clamp the test point to the line segment + else if (u > 1.) u = 1.; + + px = seg->v1->fX() + (u * seg_dx); + py = seg->v1->fY() + (u * seg_dy); + + px -= pos.X; + py -= pos.Y; + + return (px*px) + (py*py); +} + + +//========================================================================== +// +// Collect all touched sidedefs and subsectors +// to sidedefs and sector parts. +// +//========================================================================== +struct LightLinkEntry +{ + subsector_t *sub; + DVector3 pos; +}; +static TArray collected_ss; + +void ADynamicLight::CollectWithinRadius(const DVector3 &opos, subsector_t *subSec, float radius) +{ + if (!subSec) return; + collected_ss.Clear(); + collected_ss.Push({ subSec, opos }); + subSec->validcount = ::validcount; + + for (unsigned i = 0; i < collected_ss.Size(); i++) + { + subSec = collected_ss[i].sub; + + touching_subsectors = AddLightNode(&subSec->lighthead, subSec, this, touching_subsectors); + if (subSec->sector->validcount != ::validcount) + { + touching_sector = AddLightNode(&subSec->render_sector->lighthead, subSec->sector, this, touching_sector); + subSec->sector->validcount = ::validcount; + } + + for (unsigned int j = 0; j < subSec->numlines; ++j) + { + auto &pos = collected_ss[i].pos; + seg_t *seg = subSec->firstline + j; + + // check distance from x/y to seg and if within radius add this seg and, if present the opposing subsector (lather/rinse/repeat) + // If out of range we do not need to bother with this seg. + if (DistToSeg(pos, seg) <= radius) + { + if (seg->sidedef && seg->linedef && seg->linedef->validcount != ::validcount) + { + // light is in front of the seg + if ((pos.Y - seg->v1->fY()) * (seg->v2->fX() - seg->v1->fX()) + (seg->v1->fX() - pos.X) * (seg->v2->fY() - seg->v1->fY()) <= 0) + { + seg->linedef->validcount = validcount; + touching_sides = AddLightNode(&seg->sidedef->lighthead, seg->sidedef, this, touching_sides); + } + } + if (seg->linedef) + { + FLinePortal *port = seg->linedef->getPortal(); + if (port && port->mType == PORTT_LINKED) + { + line_t *other = port->mDestination; + if (other->validcount != ::validcount) + { + subsector_t *othersub = R_PointInSubsector(other->v1->fPos() + other->Delta() / 2); + if (othersub->validcount != ::validcount) + { + othersub->validcount = ::validcount; + collected_ss.Push({ othersub, PosRelative(other) }); + } + } + } + } + + seg_t *partner = seg->PartnerSeg; + if (partner) + { + subsector_t *sub = partner->Subsector; + if (sub != NULL && sub->validcount != ::validcount) + { + sub->validcount = ::validcount; + collected_ss.Push({ sub, pos }); + } + } + } + } + sector_t *sec = subSec->sector; + if (!sec->PortalBlocksSight(sector_t::ceiling)) + { + line_t *other = subSec->firstline->linedef; + if (sec->GetPortalPlaneZ(sector_t::ceiling) < Z() + radius) + { + DVector2 refpos = other->v1->fPos() + other->Delta() / 2 + sec->GetPortalDisplacement(sector_t::ceiling); + subsector_t *othersub = R_PointInSubsector(refpos); + if (othersub->validcount != ::validcount) + { + othersub->validcount = ::validcount; + collected_ss.Push({ othersub, PosRelative(othersub->sector) }); + } + } + } + if (!sec->PortalBlocksSight(sector_t::floor)) + { + line_t *other = subSec->firstline->linedef; + if (sec->GetPortalPlaneZ(sector_t::floor) > Z() - radius) + { + DVector2 refpos = other->v1->fPos() + other->Delta() / 2 + sec->GetPortalDisplacement(sector_t::floor); + subsector_t *othersub = R_PointInSubsector(refpos); + if (othersub->validcount != ::validcount) + { + othersub->validcount = ::validcount; + collected_ss.Push({ othersub, PosRelative(othersub->sector) }); + } + } + } + } +} + +//========================================================================== +// +// Link the light into the world +// +//========================================================================== + +void ADynamicLight::LinkLight() +{ + // mark the old light nodes + FLightNode * node; + + node = touching_sides; + while (node) + { + node->lightsource = NULL; + node = node->nextTarget; + } + node = touching_subsectors; + while (node) + { + node->lightsource = NULL; + node = node->nextTarget; + } + node = touching_sector; + while (node) + { + node->lightsource = NULL; + node = node->nextTarget; + } + + if (radius>0) + { + // passing in radius*radius allows us to do a distance check without any calls to sqrt + subsector_t * subSec = R_PointInSubsector(Pos()); + ::validcount++; + CollectWithinRadius(Pos(), subSec, radius*radius); + + } + + // Now delete any nodes that won't be used. These are the ones where + // m_thing is still NULL. + + node = touching_sides; + while (node) + { + if (node->lightsource == NULL) + { + node = DeleteLightNode(node); + } + else + node = node->nextTarget; + } + + node = touching_subsectors; + while (node) + { + if (node->lightsource == NULL) + { + node = DeleteLightNode(node); + } + else + node = node->nextTarget; + } + + node = touching_sector; + while (node) + { + if (node->lightsource == NULL) + { + node = DeleteLightNode(node); + } + else + node = node->nextTarget; + } +} + + +//========================================================================== +// +// Deletes the link lists +// +//========================================================================== +void ADynamicLight::UnlinkLight () +{ + if (owned && target != NULL) + { + // Delete reference in owning actor + for(int c=target->dynamiclights.Size()-1; c>=0; c--) + { + if (target->dynamiclights[c] == this) + { + target->dynamiclights.Delete(c); + break; + } + } + } + while (touching_sides) touching_sides = DeleteLightNode(touching_sides); + while (touching_subsectors) touching_subsectors = DeleteLightNode(touching_subsectors); + while (touching_sector) touching_sector = DeleteLightNode(touching_sector); +} + +void ADynamicLight::Destroy() +{ + UnlinkLight(); + Super::Destroy(); +} + + +//========================================================================== +// +// Needed for garbage collection +// +//========================================================================== + +size_t AActor::PropagateMark() +{ + for (unsigned i=0; i it; + + while ((dl=it.Next())) + { + walls=0; + sectors=0; + subsecs = 0; + Printf("%s at (%f, %f, %f), color = 0x%02x%02x%02x, radius = %f ", + dl->target? dl->target->GetClass()->TypeName.GetChars() : dl->GetClass()->TypeName.GetChars(), + dl->X(), dl->Y(), dl->Z(), dl->args[LIGHT_RED], + dl->args[LIGHT_GREEN], dl->args[LIGHT_BLUE], dl->radius); + i++; + + if (dl->target) + { + FTextureID spr = gl_GetSpriteFrame(dl->target->sprite, dl->target->frame, 0, 0, NULL); + Printf(", frame = %s ", TexMan[spr]->Name.GetChars()); + } + + + FLightNode * node; + + node=dl->touching_sides; + + while (node) + { + walls++; + allwalls++; + node = node->nextTarget; + } + + node=dl->touching_subsectors; + + while (node) + { + allsubsecs++; + subsecs++; + node = node->nextTarget; + } + + node = dl->touching_sector; + + while (node) + { + allsectors++; + sectors++; + node = node->nextTarget; + } + Printf("- %d walls, %d subsectors, %d sectors\n", walls, subsecs, sectors); + + } + Printf("%i dynamic lights, %d walls, %d subsectors, %d sectors\n\n\n", i, allwalls, allsubsecs, allsectors); +} + +CCMD(listsublights) +{ + for(int i=0;ilighthead; + while (node != NULL) + { + lights++; + node = node->nextLight; + } + + Printf(PRINT_LOG, "Subsector %d - %d lights\n", i, lights); + } +} + + diff --git a/src/gl/dynlights/gl_dynlight.cpp b/src/gl/dynlights/gl_dynlight.cpp new file mode 100644 index 000000000..de05bb19f --- /dev/null +++ b/src/gl/dynlights/gl_dynlight.cpp @@ -0,0 +1,1409 @@ +/* +** gl_dynlight.cpp +** Light definitions for actors. +** +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** Copyright 2005 Christoph Oelckers +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + + +#include +#include "i_system.h" +#include "doomtype.h" +#include "c_cvars.h" +#include "c_dispatch.h" +#include "m_random.h" +#include "sc_man.h" +#include "templates.h" +#include "w_wad.h" +#include "gi.h" +#include "r_state.h" +#include "stats.h" +#include "zstring.h" +#include "d_dehacked.h" + + +#include "gl/dynlights/gl_dynlight.h" +#include "gl/textures/gl_skyboxtexture.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_convert.h" +#include "gl/data/gl_data.h" + +int ScriptDepth; +void gl_InitGlow(FScanner &sc); +void gl_ParseBrightmap(FScanner &sc, int); +void gl_DestroyUserShaders(); +void gl_ParseHardwareShader(FScanner &sc, int deflump); +void gl_ParseSkybox(FScanner &sc); +void gl_ParseDetailTexture(FScanner &sc); +void gl_ParseVavoomSkybox(); + +//========================================================================== +// +// Dehacked aliasing +// +//========================================================================== + +inline PClassActor * GetRealType(PClassActor * ti) +{ + PClassActor *rep = ti->GetReplacement(false); + if (rep != ti && rep != NULL && rep->IsDescendantOf(RUNTIME_CLASS(ADehackedPickup))) + { + return rep; + } + return ti; +} + + + +//========================================================================== +// +// Light associations +// +//========================================================================== +class FLightAssociation +{ +public: + //FLightAssociation(); + FLightAssociation(FName actorName, const char *frameName, FName lightName) + : m_ActorName(actorName), m_AssocLight(lightName) + { + strncpy(m_FrameName, frameName, 8); + } + + FName ActorName() { return m_ActorName; } + const char *FrameName() { return m_FrameName; } + FName Light() { return m_AssocLight; } + void ReplaceLightName(FName newName) { m_AssocLight = newName; } +protected: + char m_FrameName[8]; + FName m_ActorName, m_AssocLight; +}; + +TArray LightAssociations; + + +//========================================================================== +// +// Light definitions +// +//========================================================================== +class FLightDefaults +{ +public: + FLightDefaults(FName name, ELightType type); + + void ApplyProperties(ADynamicLight * light) const; + FName GetName() const { return m_Name; } + void SetParameter(double p) { m_Param = p; } + void SetArg(int arg, BYTE val) { m_Args[arg] = val; } + BYTE GetArg(int arg) { return m_Args[arg]; } + void SetOffset(float* ft) { m_Pos.X = ft[0]; m_Pos.Z = ft[1]; m_Pos.Y = ft[2]; } + void SetSubtractive(bool subtract) { m_subtractive = subtract; } + void SetAdditive(bool add) { m_additive = add; } + void SetDontLightSelf(bool add) { m_dontlightself = add; } + void SetAttenuate(bool on) { m_attenuate = on; } + void SetHalo(bool halo) { m_halo = halo; } +protected: + FName m_Name; + unsigned char m_Args[5]; + double m_Param; + DVector3 m_Pos; + ELightType m_type; + int8_t m_attenuate; + bool m_subtractive, m_additive, m_halo, m_dontlightself; +}; + +TArray LightDefaults; + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +FLightDefaults::FLightDefaults(FName name, ELightType type) +{ + m_Name = name; + m_type = type; + + m_Pos.Zero(); + memset(m_Args, 0, 5); + m_Param = 0; + + m_subtractive = false; + m_additive = false; + m_halo = false; + m_dontlightself = false; + m_attenuate = -1; +} + +void FLightDefaults::ApplyProperties(ADynamicLight * light) const +{ + auto oldtype = light->lighttype; + + light->lighttype = m_type; + light->specialf1 = m_Param; + light->SetOffset(m_Pos); + light->halo = m_halo; + for (int a = 0; a < 3; a++) light->args[a] = clamp((int)(m_Args[a]), 0, 255); + light->m_Radius[0] = int(m_Args[LIGHT_INTENSITY]); + light->m_Radius[1] = int(m_Args[LIGHT_SECONDARY_INTENSITY]); + light->flags4 &= ~(MF4_ADDITIVE | MF4_SUBTRACTIVE | MF4_DONTLIGHTSELF); + if (m_subtractive) light->flags4 |= MF4_SUBTRACTIVE; + if (m_additive) light->flags4 |= MF4_ADDITIVE; + if (m_dontlightself) light->flags4 |= MF4_DONTLIGHTSELF; + light->m_tickCount = 0; + if (m_type == PulseLight) + { + float pulseTime = float(m_Param / TICRATE); + + light->m_lastUpdate = level.maptime; + light->m_cycler.SetParams(float(light->m_Radius[1]), float(light->m_Radius[0]), pulseTime, oldtype == PulseLight); + light->m_cycler.ShouldCycle(true); + light->m_cycler.SetCycleType(CYCLE_Sin); + light->m_currentRadius = light->m_cycler.GetVal(); + } + + switch (m_attenuate) + { + case 0: light->flags4 &= ~MF4_ATTENUATE; break; + case 1: light->flags4 |= MF4_ATTENUATE; break; + default: if (glset.attenuate) light->flags4 |= MF4_ATTENUATE; else light->flags4 &= ~MF4_ATTENUATE; break; + } + } + + +//========================================================================== +// +// light definition file parser +// +//========================================================================== + + +static const char *LightTags[]= +{ + "color", + "size", + "secondarySize", + "offset", + "chance", + "interval", + "scale", + "frame", + "light", + "{", + "}", + "subtractive", + "additive", + "halo", + "dontlightself", + "attenuate", + NULL +}; + + +enum { + LIGHTTAG_COLOR, + LIGHTTAG_SIZE, + LIGHTTAG_SECSIZE, + LIGHTTAG_OFFSET, + LIGHTTAG_CHANCE, + LIGHTTAG_INTERVAL, + LIGHTTAG_SCALE, + LIGHTTAG_FRAME, + LIGHTTAG_LIGHT, + LIGHTTAG_OPENBRACE, + LIGHTTAG_CLOSEBRACE, + LIGHTTAG_SUBTRACTIVE, + LIGHTTAG_ADDITIVE, + LIGHTTAG_HALO, + LIGHTTAG_DONTLIGHTSELF, + LIGHTTAG_ATTENUATE +}; + + +extern int ScriptDepth; + + +//========================================================================== +// +// +// +//========================================================================== + +inline float gl_ParseFloat(FScanner &sc) +{ + sc.GetFloat(); + + return float(sc.Float); +} + + +inline int gl_ParseInt(FScanner &sc) +{ + sc.GetNumber(); + + return sc.Number; +} + + +inline char *gl_ParseString(FScanner &sc) +{ + sc.GetString(); + + return sc.String; +} + + +void gl_ParseTriple(FScanner &sc, float floatVal[3]) +{ + for (int i = 0; i < 3; i++) + { + floatVal[i] = gl_ParseFloat(sc); + } +} + + +void gl_AddLightDefaults(FLightDefaults *defaults) +{ + FLightDefaults *temp; + unsigned int i; + + // remove duplicates + for (i = 0; i < LightDefaults.Size(); i++) + { + temp = LightDefaults[i]; + if (temp->GetName() == defaults->GetName()) + { + delete temp; + LightDefaults.Delete(i); + break; + } + } + + LightDefaults.Push(defaults); +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParsePointLight(FScanner &sc) +{ + int type; + float floatTriple[3]; + int intVal; + FLightDefaults *defaults; + + // get name + sc.GetString(); + FName name = sc.String; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + defaults = new FLightDefaults(name, PointLight); + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_COLOR: + gl_ParseTriple(sc, floatTriple); + defaults->SetArg(LIGHT_RED, clamp((int)(floatTriple[0] * 255), 0, 255)); + defaults->SetArg(LIGHT_GREEN, clamp((int)(floatTriple[1] * 255), 0, 255)); + defaults->SetArg(LIGHT_BLUE, clamp((int)(floatTriple[2] * 255), 0, 255)); + break; + case LIGHTTAG_OFFSET: + gl_ParseTriple(sc, floatTriple); + defaults->SetOffset(floatTriple); + break; + case LIGHTTAG_SIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_INTENSITY, intVal); + break; + case LIGHTTAG_SUBTRACTIVE: + defaults->SetSubtractive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ADDITIVE: + defaults->SetAdditive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_HALO: + defaults->SetHalo(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_DONTLIGHTSELF: + defaults->SetDontLightSelf(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ATTENUATE: + defaults->SetAttenuate(gl_ParseInt(sc) != 0); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + gl_AddLightDefaults(defaults); + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParsePulseLight(FScanner &sc) +{ + int type; + float floatVal, floatTriple[3]; + int intVal; + FLightDefaults *defaults; + + // get name + sc.GetString(); + FName name = sc.String; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + defaults = new FLightDefaults(name, PulseLight); + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_COLOR: + gl_ParseTriple(sc, floatTriple); + defaults->SetArg(LIGHT_RED, clamp((int)(floatTriple[0] * 255), 0, 255)); + defaults->SetArg(LIGHT_GREEN, clamp((int)(floatTriple[1] * 255), 0, 255)); + defaults->SetArg(LIGHT_BLUE, clamp((int)(floatTriple[2] * 255), 0, 255)); + break; + case LIGHTTAG_OFFSET: + gl_ParseTriple(sc, floatTriple); + defaults->SetOffset(floatTriple); + break; + case LIGHTTAG_SIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_INTENSITY, intVal); + break; + case LIGHTTAG_SECSIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_SECONDARY_INTENSITY, intVal); + break; + case LIGHTTAG_INTERVAL: + floatVal = gl_ParseFloat(sc); + defaults->SetParameter(floatVal * TICRATE); + break; + case LIGHTTAG_SUBTRACTIVE: + defaults->SetSubtractive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_HALO: + defaults->SetHalo(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_DONTLIGHTSELF: + defaults->SetDontLightSelf(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ATTENUATE: + defaults->SetAttenuate(gl_ParseInt(sc) != 0); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + if (defaults->GetArg(LIGHT_INTENSITY) > defaults->GetArg(LIGHT_SECONDARY_INTENSITY)) + { + auto i = defaults->GetArg(LIGHT_INTENSITY); + auto j = defaults->GetArg(LIGHT_SECONDARY_INTENSITY); + defaults->SetArg(LIGHT_INTENSITY, j); + defaults->SetArg(LIGHT_SECONDARY_INTENSITY, i); + } + + gl_AddLightDefaults(defaults); + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseFlickerLight(FScanner &sc) +{ + int type; + float floatVal, floatTriple[3]; + int intVal; + FLightDefaults *defaults; + + // get name + sc.GetString(); + FName name = sc.String; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + defaults = new FLightDefaults(name, FlickerLight); + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_COLOR: + gl_ParseTriple(sc, floatTriple); + defaults->SetArg(LIGHT_RED, clamp((int)(floatTriple[0] * 255), 0, 255)); + defaults->SetArg(LIGHT_GREEN, clamp((int)(floatTriple[1] * 255), 0, 255)); + defaults->SetArg(LIGHT_BLUE, clamp((int)(floatTriple[2] * 255), 0, 255)); + break; + case LIGHTTAG_OFFSET: + gl_ParseTriple(sc, floatTriple); + defaults->SetOffset(floatTriple); + break; + case LIGHTTAG_SIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_INTENSITY, intVal); + break; + case LIGHTTAG_SECSIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_SECONDARY_INTENSITY, intVal); + break; + case LIGHTTAG_CHANCE: + floatVal = gl_ParseFloat(sc); + defaults->SetParameter(floatVal*360.); + break; + case LIGHTTAG_SUBTRACTIVE: + defaults->SetSubtractive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_HALO: + defaults->SetHalo(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_DONTLIGHTSELF: + defaults->SetDontLightSelf(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ATTENUATE: + defaults->SetAttenuate(gl_ParseInt(sc) != 0); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + gl_AddLightDefaults(defaults); + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseFlickerLight2(FScanner &sc) +{ + int type; + float floatVal, floatTriple[3]; + int intVal; + FLightDefaults *defaults; + + // get name + sc.GetString(); + FName name = sc.String; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + defaults = new FLightDefaults(name, RandomFlickerLight); + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_COLOR: + gl_ParseTriple(sc, floatTriple); + defaults->SetArg(LIGHT_RED, clamp((int)(floatTriple[0] * 255), 0, 255)); + defaults->SetArg(LIGHT_GREEN, clamp((int)(floatTriple[1] * 255), 0, 255)); + defaults->SetArg(LIGHT_BLUE, clamp((int)(floatTriple[2] * 255), 0, 255)); + break; + case LIGHTTAG_OFFSET: + gl_ParseTriple(sc, floatTriple); + defaults->SetOffset(floatTriple); + break; + case LIGHTTAG_SIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_INTENSITY, intVal); + break; + case LIGHTTAG_SECSIZE: + intVal = clamp(gl_ParseInt(sc), 0, 255); + defaults->SetArg(LIGHT_SECONDARY_INTENSITY, intVal); + break; + case LIGHTTAG_INTERVAL: + floatVal = gl_ParseFloat(sc); + defaults->SetParameter(floatVal * 360.); + break; + case LIGHTTAG_SUBTRACTIVE: + defaults->SetSubtractive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_HALO: + defaults->SetHalo(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_DONTLIGHTSELF: + defaults->SetDontLightSelf(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ATTENUATE: + defaults->SetAttenuate(gl_ParseInt(sc) != 0); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + if (defaults->GetArg(LIGHT_SECONDARY_INTENSITY) < defaults->GetArg(LIGHT_INTENSITY)) + { + BYTE v = defaults->GetArg(LIGHT_SECONDARY_INTENSITY); + defaults->SetArg(LIGHT_SECONDARY_INTENSITY, defaults->GetArg(LIGHT_INTENSITY)); + defaults->SetArg(LIGHT_INTENSITY, v); + } + gl_AddLightDefaults(defaults); + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseSectorLight(FScanner &sc) +{ + int type; + float floatVal; + float floatTriple[3]; + FLightDefaults *defaults; + + // get name + sc.GetString(); + FName name = sc.String; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + defaults = new FLightDefaults(name, SectorLight); + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_COLOR: + gl_ParseTriple(sc, floatTriple); + defaults->SetArg(LIGHT_RED, clamp((int)(floatTriple[0] * 255), 0, 255)); + defaults->SetArg(LIGHT_GREEN, clamp((int)(floatTriple[1] * 255), 0, 255)); + defaults->SetArg(LIGHT_BLUE, clamp((int)(floatTriple[2] * 255), 0, 255)); + break; + case LIGHTTAG_OFFSET: + gl_ParseTriple(sc, floatTriple); + defaults->SetOffset(floatTriple); + break; + case LIGHTTAG_SCALE: + floatVal = gl_ParseFloat(sc); + defaults->SetArg(LIGHT_SCALE, (BYTE)(floatVal * 255)); + break; + case LIGHTTAG_SUBTRACTIVE: + defaults->SetSubtractive(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_HALO: + defaults->SetHalo(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_DONTLIGHTSELF: + defaults->SetDontLightSelf(gl_ParseInt(sc) != 0); + break; + case LIGHTTAG_ATTENUATE: + defaults->SetAttenuate(gl_ParseInt(sc) != 0); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + gl_AddLightDefaults(defaults); + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_AddLightAssociation(const char *actor, const char *frame, const char *light) +{ + FLightAssociation *temp; + unsigned int i; + FLightAssociation assoc(actor, frame, light); + + for (i = 0; i < LightAssociations.Size(); i++) + { + temp = &LightAssociations[i]; + if (temp->ActorName() == assoc.ActorName()) + { + if (strcmp(temp->FrameName(), assoc.FrameName()) == 0) + { + temp->ReplaceLightName(assoc.Light()); + return; + } + } + } + + LightAssociations.Push(assoc); +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseFrame(FScanner &sc, FString name) +{ + int type, startDepth; + FString frameName; + + // get name + sc.GetString(); + if (strlen(sc.String) > 8) + { + sc.ScriptError("Name longer than 8 characters: %s\n", sc.String); + } + frameName = sc.String; + + startDepth = ScriptDepth; + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + ScriptDepth++; + while (ScriptDepth > startDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_LIGHT: + gl_ParseString(sc); + gl_AddLightAssociation(name, frameName, sc.String); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseObject(FScanner &sc) +{ + int type; + FString name; + + // get name + sc.GetString(); + name = sc.String; + if (!PClass::FindClass(name)) + sc.ScriptMessage("Warning: dynamic lights attached to non-existent actor %s\n", name.GetChars()); + + // check for opening brace + sc.GetString(); + if (sc.Compare("{")) + { + ScriptDepth++; + while (ScriptDepth) + { + sc.GetString(); + type = sc.MatchString(LightTags); + switch (type) + { + case LIGHTTAG_OPENBRACE: + ScriptDepth++; + break; + case LIGHTTAG_CLOSEBRACE: + ScriptDepth--; + break; + case LIGHTTAG_FRAME: + gl_ParseFrame(sc, name); + break; + default: + sc.ScriptError("Unknown tag: %s\n", sc.String); + } + } + } + else + { + sc.ScriptError("Expected '{'.\n"); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ReleaseLights() +{ + unsigned int i; + + for (i = 0; i < LightDefaults.Size(); i++) + { + delete LightDefaults[i]; + } + + LightAssociations.Clear(); + LightDefaults.Clear(); +} + +//========================================================================== +// +// +// +//========================================================================== + +// these are the core types available in the *DEFS lump +static const char *CoreKeywords[]= +{ + "pointlight", + "pulselight", + "flickerlight", + "flickerlight2", + "sectorlight", + "object", + "clearlights", + "shader", + "clearshaders", + "skybox", + "glow", + "brightmap", + "disable_fullbright", + "hardwareshader", + "detail", + "#include", + NULL +}; + + +enum +{ + LIGHT_POINT, + LIGHT_PULSE, + LIGHT_FLICKER, + LIGHT_FLICKER2, + LIGHT_SECTOR, + LIGHT_OBJECT, + LIGHT_CLEAR, + TAG_SHADER, + TAG_CLEARSHADERS, + TAG_SKYBOX, + TAG_GLOW, + TAG_BRIGHTMAP, + TAG_DISABLE_FB, + TAG_HARDWARESHADER, + TAG_DETAIL, + TAG_INCLUDE, +}; + + +//========================================================================== +// +// This is only here so any shader definition for ZDoomGL can be skipped +// There is no functionality for this stuff! +// +//========================================================================== +bool gl_ParseShader(FScanner &sc) +{ + int ShaderDepth = 0; + + if (sc.GetString()) + { + char *tmp; + + tmp = strstr(sc.String, "{"); + while (tmp) + { + ShaderDepth++; + tmp++; + tmp = strstr(tmp, "{"); + } + + tmp = strstr(sc.String, "}"); + while (tmp) + { + ShaderDepth--; + tmp++; + tmp = strstr(tmp, "}"); + } + + if (ShaderDepth == 0) return true; + } + return false; +} + +//========================================================================== +// +// Light associations per actor class +// +// Turn this inefficient mess into something that can be used at run time. +// +//========================================================================== + +class FInternalLightAssociation +{ +public: + FInternalLightAssociation(FLightAssociation * asso); + int Sprite() const { return m_sprite; } + int Frame() const { return m_frame; } + const FLightDefaults *Light() const { return m_AssocLight; } +protected: + int m_sprite; + int m_frame; + FLightDefaults * m_AssocLight; +}; + +//========================================================================== +// +// +// +//========================================================================== + +FInternalLightAssociation::FInternalLightAssociation(FLightAssociation * asso) +{ + + m_AssocLight=NULL; + for(unsigned int i=0;iGetName() == asso->Light()) + { + m_AssocLight = LightDefaults[i]; + break; + } + } + + m_sprite=-1; + m_frame = -1; + for (unsigned i = 0; i < sprites.Size (); ++i) + { + if (strncmp (sprites[i].name, asso->FrameName(), 4) == 0) + { + m_sprite = (int)i; + break; + } + } + + // Only handle lights for full frames. + // I won't bother with special lights for single rotations + // because there is no decent use for them! + if (strlen(asso->FrameName())==5 || asso->FrameName()[5]=='0') + { + m_frame = toupper(asso->FrameName()[4])-'A'; + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +inline TDeletingArray * gl_GetActorLights(AActor * actor) +{ + return (TDeletingArray*)actor->lightassociations; +} + +TDeletingArray< TDeletingArray * > AssoDeleter; + +//========================================================================== +// +// State lights +// +//========================================================================== +TArray ParsedStateLights; +TArray StateLights; + + + +//========================================================================== +// +// +// +//========================================================================== + +void gl_InitializeActorLights() +{ + for(unsigned int i=0;ilightassociations) + { + TDeletingArray *p =new TDeletingArray; + defaults->lightassociations = p; + AssoDeleter.Push(p); + } + TDeletingArray * lights = gl_GetActorLights(defaults); + if (iasso->Light()==NULL) + { + // The definition was not valid. + delete iasso; + } + else + { + lights->Push(iasso); + } + } + } + } + // we don't need the parser data for the light associations anymore + LightAssociations.Clear(); + LightAssociations.ShrinkToFit(); + + StateLights.Resize(ParsedStateLights.Size()+1); + for(unsigned i=0; iGetName() == ParsedStateLights[i]) + { + StateLights[i] = LightDefaults[j]; + break; + } + } + } + else StateLights[i] = NULL; + } + StateLights[StateLights.Size()-1] = NULL; // terminator + ParsedStateLights.Clear(); + ParsedStateLights.ShrinkToFit(); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void gl_AttachLight(AActor *actor, unsigned int count, const FLightDefaults *lightdef) +{ + ADynamicLight *light; + + // I'm skipping the single rotations because that really doesn't make sense! + if (count < actor->dynamiclights.Size()) + { + light = barrier_cast(actor->dynamiclights[count]); + assert(light != NULL); + } + else + { + light = Spawn(actor->Pos(), NO_REPLACE); + light->target = actor; + light->owned = true; + light->ObjectFlags |= OF_Transient; + //light->flags4 |= MF4_ATTENUATE; + actor->dynamiclights.Push(light); + } + light->flags2&=~MF2_DORMANT; + lightdef->ApplyProperties(light); +} + +//========================================================================== +// +// per-state light adjustment +// +//========================================================================== + +void gl_SetActorLights(AActor *actor) +{ + TArray * l = gl_GetActorLights(actor); + unsigned int count = 0; + + All.Clock(); + if (actor->state == NULL) return; + if (l) + { + TArray & LightAssociations=*l; + ADynamicLight *lights, *tmpLight; + unsigned int i; + + int sprite = actor->sprite; + int frame = actor->frame; + + lights = tmpLight = NULL; + + + for (i = 0; i < LightAssociations.Size(); i++) + { + if (LightAssociations[i]->Sprite() == sprite && + (LightAssociations[i]->Frame()==frame || LightAssociations[i]->Frame()==-1)) + { + gl_AttachLight(actor, count++, LightAssociations[i]->Light()); + } + } + } + if (count == 0 && actor->state->Light > 0) + { + for(int i= actor->state->Light; StateLights[i] != NULL; i++) + { + if (StateLights[i] != (FLightDefaults*)-1) + { + gl_AttachLight(actor, count++, StateLights[i]); + } + } + } + + for(;countdynamiclights.Size();count++) + { + actor->dynamiclights[count]->flags2|=MF2_DORMANT; + memset(actor->dynamiclights[count]->args, 0, sizeof(actor->args)); + } + All.Unclock(); +} + +//========================================================================== +// +// This is called before saving the game +// +//========================================================================== + +void gl_DeleteAllAttachedLights() +{ + TThinkerIterator it; + AActor * a; + ADynamicLight * l; + + while ((a=it.Next())) + { + a->dynamiclights.Clear(); + } + + TThinkerIterator it2; + + l=it2.Next(); + while (l) + { + ADynamicLight * ll = it2.Next(); + if (l->owned) l->Destroy(); + l=ll; + } + + +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_RecreateAllAttachedLights() +{ + TThinkerIterator it; + AActor * a; + + while ((a=it.Next())) + { + gl_SetActorLights(a); + } +} + + +//========================================================================== +// The actual light def parsing code is there. +// DoParseDefs is no longer called directly by ParseDefs, now it's called +// by LoadDynLightDefs, which wasn't simply integrated into ParseDefs +// because of the way the code needs to load two out of five lumps. +//========================================================================== +void gl_DoParseDefs(FScanner &sc, int workingLump) +{ + int recursion=0; + int lump, type; + + // Get actor class name. + while (true) + { + sc.SavePos(); + if (!sc.GetToken ()) + { + return; + } + type = sc.MatchString(CoreKeywords); + switch (type) + { + case TAG_INCLUDE: + { + sc.MustGetString(); + // This is not using sc.Open because it can print a more useful error message when done here + lump = Wads.CheckNumForFullName(sc.String, true); + if (lump==-1) + sc.ScriptError("Lump '%s' not found", sc.String); + + FScanner newscanner(lump); + gl_DoParseDefs(newscanner, lump); + break; + } + case LIGHT_POINT: + gl_ParsePointLight(sc); + break; + case LIGHT_PULSE: + gl_ParsePulseLight(sc); + break; + case LIGHT_FLICKER: + gl_ParseFlickerLight(sc); + break; + case LIGHT_FLICKER2: + gl_ParseFlickerLight2(sc); + break; + case LIGHT_SECTOR: + gl_ParseSectorLight(sc); + break; + case LIGHT_OBJECT: + gl_ParseObject(sc); + break; + case LIGHT_CLEAR: + gl_ReleaseLights(); + break; + case TAG_SHADER: + gl_ParseShader(sc); + break; + case TAG_CLEARSHADERS: + break; + case TAG_SKYBOX: + gl_ParseSkybox(sc); + break; + case TAG_GLOW: + gl_InitGlow(sc); + break; + case TAG_BRIGHTMAP: + gl_ParseBrightmap(sc, workingLump); + break; + case TAG_HARDWARESHADER: + gl_ParseHardwareShader(sc, workingLump); + break; + case TAG_DETAIL: + gl_ParseDetailTexture(sc); + break; + case TAG_DISABLE_FB: + { + /* not implemented. + sc.MustGetString(); + const PClass *cls = PClass::FindClass(sc.String); + if (cls) GetDefaultByType(cls)->renderflags |= RF_NEVERFULLBRIGHT; + */ + } + break; + default: + sc.ScriptError("Error parsing defs. Unknown tag: %s.\n", sc.String); + break; + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_LoadGLDefs(const char * defsLump) +{ + int workingLump, lastLump; + + lastLump = 0; + while ((workingLump = Wads.FindLump(defsLump, &lastLump)) != -1) + { + FScanner sc(workingLump); + gl_DoParseDefs(sc, workingLump); + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +void gl_ParseDefs() +{ + const char *defsLump = NULL; + + atterm( gl_ReleaseLights ); + gl_ReleaseLights(); + gl_DestroyUserShaders(); + switch (gameinfo.gametype) + { + case GAME_Heretic: + defsLump = "HTICDEFS"; + break; + case GAME_Hexen: + defsLump = "HEXNDEFS"; + break; + case GAME_Strife: + defsLump = "STRFDEFS"; + break; + case GAME_Doom: + defsLump = "DOOMDEFS"; + break; + case GAME_Chex: + defsLump = "CHEXDEFS"; + break; + default: // silence GCC + break; + } + gl_ParseVavoomSkybox(); + if (defsLump != NULL) gl_LoadGLDefs(defsLump); + gl_LoadGLDefs("GLDEFS"); + gl_InitializeActorLights(); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void AddStateLight(FState *State, const char *lname) +{ + if (State->Light == 0) + { + ParsedStateLights.Push(NAME_None); + State->Light = ParsedStateLights.Push(FName(lname)); + } + else + { + ParsedStateLights.Push(FName(lname)); + } +} diff --git a/src/gl/dynlights/gl_dynlight.h b/src/gl/dynlights/gl_dynlight.h new file mode 100644 index 000000000..f71f0dfdf --- /dev/null +++ b/src/gl/dynlights/gl_dynlight.h @@ -0,0 +1,211 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#ifndef __GLC_DYNLIGHT_H +#define __GLC_DYNLIGHT_H + +#include "c_cvars.h" +#include "gl/utility/gl_geometric.h" +#include "gl/utility/gl_cycler.h" + + +EXTERN_CVAR(Bool, gl_lights) +EXTERN_CVAR(Bool, gl_attachedlights) + +class ADynamicLight; +class FSerializer; +class FLightDefaults; + + +enum +{ + LIGHT_RED = 0, + LIGHT_GREEN = 1, + LIGHT_BLUE = 2, + LIGHT_INTENSITY = 3, + LIGHT_SECONDARY_INTENSITY = 4, + LIGHT_SCALE = 3, +}; + +// This is as good as something new - and it can be set directly in the ActorInfo! +#define MF4_SUBTRACTIVE MF4_MISSILEEVENMORE +#define MF4_ADDITIVE MF4_MISSILEMORE +#define MF4_DONTLIGHTSELF MF4_SEESDAGGERS +#define MF4_ATTENUATE MF4_INCOMBAT + +enum ELightType +{ + PointLight, + PulseLight, + FlickerLight, + RandomFlickerLight, + SectorLight, + SpotLight, + ColorPulseLight, + ColorFlickerLight, + RandomColorFlickerLight +}; + + +struct FLightNode +{ + FLightNode ** prevTarget; + FLightNode * nextTarget; + FLightNode ** prevLight; + FLightNode * nextLight; + ADynamicLight * lightsource; + union + { + side_t * targLine; + subsector_t * targSubsector; + void * targ; + }; +}; + + +// +// Base class +// +// [CO] I merged everything together in this one class so that I don't have +// to create and re-create an excessive amount of objects +// + +class ADynamicLight : public AActor +{ + friend class FLightDefaults; + DECLARE_CLASS (ADynamicLight, AActor) +public: + virtual void Tick(); + void Serialize(FSerializer &arc); + void PostSerialize(); + BYTE GetRed() const { return args[LIGHT_RED]; } + BYTE GetGreen() const { return args[LIGHT_GREEN]; } + BYTE GetBlue() const { return args[LIGHT_BLUE]; } + float GetRadius() const { return (IsActive() ? m_currentRadius * 2.f : 0.f); } + void LinkLight(); + void UnlinkLight(); + size_t PointerSubstitution (DObject *old, DObject *notOld); + + void BeginPlay(); + void SetOrigin (double x, double y, double z, bool moving = false); + void PostBeginPlay(); + void Destroy(); + void Activate(AActor *activator); + void Deactivate(AActor *activator); + void SetOffset(const DVector3 &pos); + void UpdateLocation(); + bool IsOwned() const { return owned; } + bool IsActive() const { return !(flags2&MF2_DORMANT); } + bool IsSubtractive() { return !!(flags4&MF4_SUBTRACTIVE); } + bool IsAdditive() { return !!(flags4&MF4_ADDITIVE); } + FState *targetState; + FLightNode * touching_sides; + FLightNode * touching_subsectors; + FLightNode * touching_sector; + +private: + double DistToSeg(const DVector3 &pos, seg_t *seg); + void CollectWithinRadius(const DVector3 &pos, subsector_t *subSec, float radius); + +protected: + DVector3 m_off; + float m_currentRadius; + unsigned int m_lastUpdate; + FCycler m_cycler; + subsector_t * subsector; + +public: + int m_tickCount; + int m_Radius[2]; + BYTE lightflags; + BYTE lighttype; + bool owned; + bool halo; + BYTE color2[3]; + bool visibletoplayer; + int bufferindex; + + +}; + +class AVavoomLight : public ADynamicLight +{ + DECLARE_CLASS (AVavoomLight, ADynamicLight) +public: + virtual void BeginPlay(); +}; + +class AVavoomLightWhite : public AVavoomLight +{ + DECLARE_CLASS (AVavoomLightWhite, AVavoomLight) +public: + virtual void BeginPlay(); +}; + +class AVavoomLightColor : public AVavoomLight +{ + DECLARE_CLASS (AVavoomLightColor, AVavoomLight) +public: + void BeginPlay(); +}; + + +enum +{ + STAT_DLIGHT=64 +}; + +struct FDynLightData +{ + TArray arrays[3]; + + void Clear() + { + arrays[0].Clear(); + arrays[1].Clear(); + arrays[2].Clear(); + } + + void Combine(int *siz, int max) + { + siz[0] = arrays[0].Size(); + siz[1] = siz[0] + arrays[1].Size(); + siz[2] = siz[1] + arrays[2].Size(); + arrays[0].Resize(arrays[0].Size() + arrays[1].Size() + arrays[2].Size()); + memcpy(&arrays[0][siz[0]], &arrays[1][0], arrays[1].Size() * sizeof(float)); + memcpy(&arrays[0][siz[1]], &arrays[2][0], arrays[2].Size() * sizeof(float)); + siz[0]>>=2; + siz[1]>>=2; + siz[2]>>=2; + if (siz[0] > max) siz[0] = max; + if (siz[1] > max) siz[1] = max; + if (siz[2] > max) siz[2] = max; + } +}; + + + +bool gl_GetLight(int group, Plane & p, ADynamicLight * light, bool checkside, FDynLightData &data); +void gl_UploadLights(FDynLightData &data); + + +#endif diff --git a/src/gl/dynlights/gl_dynlight1.cpp b/src/gl/dynlights/gl_dynlight1.cpp new file mode 100644 index 000000000..2f8ef44ed --- /dev/null +++ b/src/gl/dynlights/gl_dynlight1.cpp @@ -0,0 +1,122 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_dynlight1.cpp +** dynamic light application +** +**/ + +#include "gl/system/gl_system.h" +#include "c_dispatch.h" +#include "p_local.h" +#include "vectors.h" +#include "gl/gl_functions.h" +#include "g_level.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" + + +//========================================================================== +// +// Light related CVARs +// +//========================================================================== + +CUSTOM_CVAR (Bool, gl_lights, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (self) gl_RecreateAllAttachedLights(); + else gl_DeleteAllAttachedLights(); +} + +CVAR (Bool, gl_attachedlights, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); +CVAR (Bool, gl_lights_checkside, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); +CVAR (Bool, gl_light_sprites, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); +CVAR (Bool, gl_light_particles, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +//========================================================================== +// +// Sets up the parameters to render one dynamic light onto one plane +// +//========================================================================== +bool gl_GetLight(int group, Plane & p, ADynamicLight * light, bool checkside, FDynLightData &ldata) +{ + int i = 0; + + DVector3 pos = light->PosRelative(group); + + float dist = fabsf(p.DistToPoint(pos.X, pos.Z, pos.Y)); + float radius = (light->GetRadius()); + + if (radius <= 0.f) return false; + if (dist > radius) return false; + if (checkside && gl_lights_checkside && p.PointOnSide(pos.X, pos.Z, pos.Y)) + { + return false; + } + + + float cs; + if (light->IsAdditive()) + { + cs = 0.2f; + i = 2; + } + else + { + cs = 1.0f; + } + + float r = light->GetRed() / 255.0f * cs; + float g = light->GetGreen() / 255.0f * cs; + float b = light->GetBlue() / 255.0f * cs; + + if (light->IsSubtractive()) + { + Vector v; + + v.Set(r, g, b); + r = v.Length() - r; + g = v.Length() - g; + b = v.Length() - b; + i = 1; + } + + float *data = &ldata.arrays[i][ldata.arrays[i].Reserve(8)]; + data[0] = pos.X; + data[1] = pos.Z; + data[2] = pos.Y; + data[3] = radius; + data[4] = r; + data[5] = g; + data[6] = b; + data[7] = !!(light->flags4 & MF4_ATTENUATE); + return true; +} + diff --git a/src/gl/dynlights/gl_glow.cpp b/src/gl/dynlights/gl_glow.cpp new file mode 100644 index 000000000..eacbfa953 --- /dev/null +++ b/src/gl/dynlights/gl_glow.cpp @@ -0,0 +1,126 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_glow.cpp +** Glowing flats like Doomsday +** +**/ + +#include "w_wad.h" +#include "sc_man.h" +#include "v_video.h" +#include "r_defs.h" +#include "textures/textures.h" + +#include "gl/dynlights/gl_glow.h" + +//=========================================================================== +// +// Reads glow definitions from GLDEFS +// +//=========================================================================== +void gl_InitGlow(FScanner &sc) +{ + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + sc.MustGetString(); + if (sc.Compare("FLATS")) + { + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + sc.MustGetString(); + FTextureID flump=TexMan.CheckForTexture(sc.String, FTexture::TEX_Flat,FTextureManager::TEXMAN_TryAny); + FTexture *tex = TexMan[flump]; + if (tex) tex->gl_info.bGlowing = tex->gl_info.bFullbright = true; + } + } + else if (sc.Compare("WALLS")) + { + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + sc.MustGetString(); + FTextureID flump=TexMan.CheckForTexture(sc.String, FTexture::TEX_Wall,FTextureManager::TEXMAN_TryAny); + FTexture *tex = TexMan[flump]; + if (tex) tex->gl_info.bGlowing = tex->gl_info.bFullbright = true; + } + } + else if (sc.Compare("TEXTURE")) + { + sc.SetCMode(true); + sc.MustGetString(); + FTextureID flump=TexMan.CheckForTexture(sc.String, FTexture::TEX_Flat,FTextureManager::TEXMAN_TryAny); + FTexture *tex = TexMan[flump]; + sc.MustGetStringName(","); + sc.MustGetString(); + PalEntry color = V_GetColor(NULL, sc.String); + //sc.MustGetStringName(","); + //sc.MustGetNumber(); + if (sc.CheckString(",")) + { + if (sc.CheckNumber()) + { + if (tex) tex->gl_info.GlowHeight = sc.Number; + if (!sc.CheckString(",")) goto skip_fb; + } + + sc.MustGetStringName("fullbright"); + if (tex) tex->gl_info.bFullbright = true; + } + skip_fb: + sc.SetCMode(false); + + if (tex && color != 0) + { + tex->gl_info.bGlowing = true; + tex->gl_info.GlowColor = color; + } + } + } +} + + +//========================================================================== +// +// Checks whether a sprite should be affected by a glow +// +//========================================================================== +int gl_CheckSpriteGlow(sector_t *sec, int lightlevel, const DVector3 &pos) +{ + FTextureID floorpic = sec->GetTexture(sector_t::floor); + FTexture *tex = TexMan[floorpic]; + if (tex != NULL && tex->isGlowing()) + { + double floordiff = pos.Z - sec->floorplane.ZatPoint(pos); + if (floordiff < tex->gl_info.GlowHeight && tex->gl_info.GlowHeight != 0) + { + int maxlight = (255 + lightlevel) >> 1; + double lightfrac = floordiff / tex->gl_info.GlowHeight; + if (lightfrac < 0) lightfrac = 0; + lightlevel = int(lightfrac*lightlevel + maxlight*(1 - lightfrac)); + } + } + return lightlevel; +} + diff --git a/src/gl/dynlights/gl_glow.h b/src/gl/dynlights/gl_glow.h new file mode 100644 index 000000000..7d9ae9f7f --- /dev/null +++ b/src/gl/dynlights/gl_glow.h @@ -0,0 +1,10 @@ + +#ifndef __GL_GLOW +#define __GL_GLOW + +struct sector_t; + +void gl_InitGlow(const char * lumpnm); +int gl_CheckSpriteGlow(sector_t *sec, int lightlevel, const DVector3 &pos); + +#endif diff --git a/src/gl/dynlights/gl_lightbuffer.cpp b/src/gl/dynlights/gl_lightbuffer.cpp new file mode 100644 index 000000000..b819a3be6 --- /dev/null +++ b/src/gl/dynlights/gl_lightbuffer.cpp @@ -0,0 +1,211 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2014-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_lightbuffer.cpp +** Buffer data maintenance for dynamic lights +** +**/ + +#include "gl/system/gl_system.h" +#include "gl/shaders/gl_shader.h" +#include "gl/dynlights/gl_lightbuffer.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/system/gl_interface.h" +#include "gl/utility//gl_clock.h" + +static const int INITIAL_BUFFER_SIZE = 160000; // This means 80000 lights per frame and 160000*16 bytes == 2.56 MB. + +float *mMap; + +FLightBuffer::FLightBuffer() +{ + + mBufferSize = INITIAL_BUFFER_SIZE; + mByteSize = mBufferSize * sizeof(float); + if (gl.flags & RFL_SHADER_STORAGE_BUFFER) + { + mBufferType = GL_SHADER_STORAGE_BUFFER; + mBlockAlign = 0; + mBlockSize = mBufferSize; + } + else + { + mBufferType = GL_UNIFORM_BUFFER; + mBlockSize = gl.maxuniformblock / 16; + if (mBlockSize > 2048) mBlockSize = 2048; // we don't really need a larger buffer + mBlockAlign = mBlockSize / 2; + } + + glGenBuffers(1, &mBufferId); + glBindBufferBase(mBufferType, LIGHTBUF_BINDINGPOINT, mBufferId); + glBindBuffer(mBufferType, mBufferId); // Note: Some older AMD drivers don't do that in glBindBufferBase, as they should. + if (gl.lightmethod == LM_DIRECT) + { + glBufferStorage(mBufferType, mByteSize, NULL, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + } + else + { + glBufferData(mBufferType, mByteSize, NULL, GL_DYNAMIC_DRAW); + mBufferPointer = NULL; + } + + Clear(); + mLastMappedIndex = UINT_MAX; +} + +FLightBuffer::~FLightBuffer() +{ + glBindBuffer(mBufferType, 0); + glDeleteBuffers(1, &mBufferId); +} + +void FLightBuffer::Clear() +{ + mIndex = 0; + mIndices.Clear(); + mUploadIndex = 0; +} + +int FLightBuffer::UploadLights(FDynLightData &data) +{ + int size0 = data.arrays[0].Size()/4; + int size1 = data.arrays[1].Size()/4; + int size2 = data.arrays[2].Size()/4; + int totalsize = size0 + size1 + size2 + 1; + + // pointless type casting because some compilers can't print enough warnings. + if (mBlockAlign > 0 && (unsigned int)totalsize + (mIndex % mBlockAlign) > mBlockSize) + { + mIndex = ((mIndex + mBlockAlign) / mBlockAlign) * mBlockAlign; + + // can't be rendered all at once. + if ((unsigned int)totalsize > mBlockSize) + { + int diff = totalsize - (int)mBlockSize; + + size2 -= diff; + if (size2 < 0) + { + size1 += size2; + size2 = 0; + } + if (size1 < 0) + { + size0 += size1; + size1 = 0; + } + totalsize = size0 + size1 + size2 + 1; + } + } + + if (totalsize <= 1) return -1; + + if (mIndex + totalsize > mBufferSize/4) + { + // reallocate the buffer with twice the size + unsigned int newbuffer; + + // first unmap the old buffer + glBindBuffer(mBufferType, mBufferId); + glUnmapBuffer(mBufferType); + + // create and bind the new buffer, bind the old one to a copy target (too bad that DSA is not yet supported well enough to omit this crap.) + glGenBuffers(1, &newbuffer); + glBindBufferBase(mBufferType, LIGHTBUF_BINDINGPOINT, newbuffer); + glBindBuffer(mBufferType, newbuffer); // Note: Some older AMD drivers don't do that in glBindBufferBase, as they should. + glBindBuffer(GL_COPY_READ_BUFFER, mBufferId); + + // create the new buffer's storage (twice as large as the old one) + mBufferSize *= 2; + mByteSize *= 2; + if (gl.lightmethod == LM_DIRECT) + { + glBufferStorage(mBufferType, mByteSize, NULL, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT); + } + else + { + glBufferData(mBufferType, mByteSize, NULL, GL_DYNAMIC_DRAW); + mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT|GL_MAP_INVALIDATE_BUFFER_BIT); + } + + // copy contents and delete the old buffer. + glCopyBufferSubData(GL_COPY_READ_BUFFER, mBufferType, 0, 0, mByteSize/2); + glBindBuffer(GL_COPY_READ_BUFFER, 0); + glDeleteBuffers(1, &mBufferId); + mBufferId = newbuffer; + } + + float *copyptr; + + assert(mBufferPointer != NULL); + if (mBufferPointer == NULL) return -1; + copyptr = mBufferPointer + mIndex * 4; + + float parmcnt[] = { 0, float(size0), float(size0 + size1), float(size0 + size1 + size2) }; + + memcpy(©ptr[0], parmcnt, 4 * sizeof(float)); + memcpy(©ptr[4], &data.arrays[0][0], 4 * size0*sizeof(float)); + memcpy(©ptr[4 + 4*size0], &data.arrays[1][0], 4 * size1*sizeof(float)); + memcpy(©ptr[4 + 4*(size0 + size1)], &data.arrays[2][0], 4 * size2*sizeof(float)); + + unsigned int bufferindex = mIndex; + mIndex += totalsize; + draw_dlight += (totalsize-1) / 2; + return bufferindex; +} + +void FLightBuffer::Begin() +{ + if (gl.lightmethod == LM_DEFERRED) + { + glBindBuffer(mBufferType, mBufferId); + mBufferPointer = (float*)glMapBufferRange(mBufferType, 0, mByteSize, GL_MAP_WRITE_BIT); + } +} + +void FLightBuffer::Finish() +{ + if (gl.lightmethod == LM_DEFERRED) + { + glBindBuffer(mBufferType, mBufferId); + glUnmapBuffer(mBufferType); + mBufferPointer = NULL; + } +} + +int FLightBuffer::BindUBO(unsigned int index) +{ + unsigned int offset = (index / mBlockAlign) * mBlockAlign; + + if (offset != mLastMappedIndex) + { + // this will only get called if a uniform buffer is used. For a shader storage buffer we only need to bind the buffer once at the start to all shader programs + mLastMappedIndex = offset; + glBindBufferRange(GL_UNIFORM_BUFFER, LIGHTBUF_BINDINGPOINT, mBufferId, offset*16, mBlockSize*16); // we go from counting vec4's to counting bytes here. + } + return (index - offset); +} + + + diff --git a/src/gl/dynlights/gl_lightbuffer.h b/src/gl/dynlights/gl_lightbuffer.h new file mode 100644 index 000000000..8781ccb57 --- /dev/null +++ b/src/gl/dynlights/gl_lightbuffer.h @@ -0,0 +1,39 @@ +#ifndef __GL_LIGHTBUFFER_H +#define __GL_LIGHTBUFFER_H + +#include "tarray.h" +struct FDynLightData; + +class FLightBuffer +{ + TArray mIndices; + unsigned int mBufferId; + float * mBufferPointer; + + unsigned int mBufferType; + unsigned int mIndex; + unsigned int mUploadIndex; + unsigned int mLastMappedIndex; + unsigned int mBlockAlign; + unsigned int mBlockSize; + unsigned int mBufferSize; + unsigned int mByteSize; + +public: + + FLightBuffer(); + ~FLightBuffer(); + void Clear(); + int UploadLights(FDynLightData &data); + void Begin(); + void Finish(); + int BindUBO(unsigned int index); + unsigned int GetBlockSize() const { return mBlockSize; } + unsigned int GetBufferType() const { return mBufferType; } + unsigned int GetIndexPtr() const { return mIndices.Size(); } + void StoreIndex(int index) { mIndices.Push(index); } + int GetIndex(int i) const { return mIndices[i]; } +}; + +#endif + diff --git a/src/gl/gl_functions.h b/src/gl/gl_functions.h new file mode 100644 index 000000000..aa08d19be --- /dev/null +++ b/src/gl/gl_functions.h @@ -0,0 +1,13 @@ +#ifndef __GL_FUNCT +#define __GL_FUNCT + +#include "v_palette.h" + +class AActor; + +void gl_PreprocessLevel(); +void gl_CleanLevelData(); +void gl_LinkLights(); +void gl_SetActorLights(AActor *); + +#endif diff --git a/src/gl/hqnx/common.h b/src/gl/hqnx/common.h new file mode 100644 index 000000000..c3e700571 --- /dev/null +++ b/src/gl/hqnx/common.h @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2003 Maxim Stepin ( maxst@hiend3d.com ) + * + * Copyright (C) 2010 Cameron Zemek ( grom@zeminvaders.net) + * Copyright (C) 2011 Francois Gannaz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef __HQX_COMMON_H_ +#define __HQX_COMMON_H_ + +#include +#include + +#define MASK_2 0x0000FF00 +#define MASK_13 0x00FF00FF +#define MASK_RGB 0x00FFFFFF +#define MASK_ALPHA 0xFF000000 + +#define Ymask 0x00FF0000 +#define Umask 0x0000FF00 +#define Vmask 0x000000FF +#define trY 0x00300000 +#define trU 0x00000700 +#define trV 0x00000006 + +/* RGB to YUV lookup table */ +extern uint32_t *RGBtoYUV; + +static inline uint32_t rgb_to_yuv(uint32_t c) +{ + // Mask against MASK_RGB to discard the alpha channel + return RGBtoYUV[MASK_RGB & c]; +} + +/* Test if there is difference in color */ +static inline int yuv_diff(uint32_t yuv1, uint32_t yuv2) { + return (( abs((int64_t)(yuv1 & Ymask) - (int64_t)(yuv2 & Ymask)) > trY ) || + ( abs((int64_t)(yuv1 & Umask) - (int64_t)(yuv2 & Umask)) > trU ) || + ( abs((int64_t)(yuv1 & Vmask) - (int64_t)(yuv2 & Vmask)) > trV ) ); +} + +static inline int Diff(uint32_t c1, uint32_t c2) +{ + return yuv_diff(rgb_to_yuv(c1), rgb_to_yuv(c2)); +} + +/* Interpolate functions */ +static inline uint32_t Interpolate_2(uint32_t c1, int w1, uint32_t c2, int w2, int s) +{ + if (c1 == c2) { + return c1; + } + return + (((((c1 & MASK_ALPHA) >> 24) * w1 + ((c2 & MASK_ALPHA) >> 24) * w2) << (24-s)) & MASK_ALPHA) + + ((((c1 & MASK_2) * w1 + (c2 & MASK_2) * w2) >> s) & MASK_2) + + ((((c1 & MASK_13) * w1 + (c2 & MASK_13) * w2) >> s) & MASK_13); +} + +static inline uint32_t Interpolate_3(uint32_t c1, int w1, uint32_t c2, int w2, uint32_t c3, int w3, int s) +{ + return + (((((c1 & MASK_ALPHA) >> 24) * w1 + ((c2 & MASK_ALPHA) >> 24) * w2 + ((c3 & MASK_ALPHA) >> 24) * w3) << (24-s)) & MASK_ALPHA) + + ((((c1 & MASK_2) * w1 + (c2 & MASK_2) * w2 + (c3 & MASK_2) * w3) >> s) & MASK_2) + + ((((c1 & MASK_13) * w1 + (c2 & MASK_13) * w2 + (c3 & MASK_13) * w3) >> s) & MASK_13); +} + +static inline uint32_t Interp1(uint32_t c1, uint32_t c2) +{ + //(c1*3+c2) >> 2; + return Interpolate_2(c1, 3, c2, 1, 2); +} + +static inline uint32_t Interp2(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*2+c2+c3) >> 2; + return Interpolate_3(c1, 2, c2, 1, c3, 1, 2); +} + +static inline uint32_t Interp3(uint32_t c1, uint32_t c2) +{ + //(c1*7+c2)/8; + return Interpolate_2(c1, 7, c2, 1, 3); +} + +static inline uint32_t Interp4(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*2+(c2+c3)*7)/16; + return Interpolate_3(c1, 2, c2, 7, c3, 7, 4); +} + +static inline uint32_t Interp5(uint32_t c1, uint32_t c2) +{ + //(c1+c2) >> 1; + return Interpolate_2(c1, 1, c2, 1, 1); +} + +static inline uint32_t Interp6(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*5+c2*2+c3)/8; + return Interpolate_3(c1, 5, c2, 2, c3, 1, 3); +} + +static inline uint32_t Interp7(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*6+c2+c3)/8; + return Interpolate_3(c1, 6, c2, 1, c3, 1, 3); +} + +static inline uint32_t Interp8(uint32_t c1, uint32_t c2) +{ + //(c1*5+c2*3)/8; + return Interpolate_2(c1, 5, c2, 3, 3); +} + +static inline uint32_t Interp9(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*2+(c2+c3)*3)/8; + return Interpolate_3(c1, 2, c2, 3, c3, 3, 3); +} + +static inline uint32_t Interp10(uint32_t c1, uint32_t c2, uint32_t c3) +{ + //(c1*14+c2+c3)/16; + return Interpolate_3(c1, 14, c2, 1, c3, 1, 4); +} + +#endif diff --git a/src/gl/hqnx/hq2x.cpp b/src/gl/hqnx/hq2x.cpp new file mode 100644 index 000000000..637d1fb78 --- /dev/null +++ b/src/gl/hqnx/hq2x.cpp @@ -0,0 +1,2808 @@ +/* + * Copyright (C) 2003 Maxim Stepin ( maxst@hiend3d.com ) + * + * Copyright (C) 2010 Cameron Zemek ( grom@zeminvaders.net) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "common.h" +#include "hqx.h" + +#define PIXEL00_0 *dp = w[5]; +#define PIXEL00_10 *dp = Interp1(w[5], w[1]); +#define PIXEL00_11 *dp = Interp1(w[5], w[4]); +#define PIXEL00_12 *dp = Interp1(w[5], w[2]); +#define PIXEL00_20 *dp = Interp2(w[5], w[4], w[2]); +#define PIXEL00_21 *dp = Interp2(w[5], w[1], w[2]); +#define PIXEL00_22 *dp = Interp2(w[5], w[1], w[4]); +#define PIXEL00_60 *dp = Interp6(w[5], w[2], w[4]); +#define PIXEL00_61 *dp = Interp6(w[5], w[4], w[2]); +#define PIXEL00_70 *dp = Interp7(w[5], w[4], w[2]); +#define PIXEL00_90 *dp = Interp9(w[5], w[4], w[2]); +#define PIXEL00_100 *dp = Interp10(w[5], w[4], w[2]); +#define PIXEL01_0 *(dp+1) = w[5]; +#define PIXEL01_10 *(dp+1) = Interp1(w[5], w[3]); +#define PIXEL01_11 *(dp+1) = Interp1(w[5], w[2]); +#define PIXEL01_12 *(dp+1) = Interp1(w[5], w[6]); +#define PIXEL01_20 *(dp+1) = Interp2(w[5], w[2], w[6]); +#define PIXEL01_21 *(dp+1) = Interp2(w[5], w[3], w[6]); +#define PIXEL01_22 *(dp+1) = Interp2(w[5], w[3], w[2]); +#define PIXEL01_60 *(dp+1) = Interp6(w[5], w[6], w[2]); +#define PIXEL01_61 *(dp+1) = Interp6(w[5], w[2], w[6]); +#define PIXEL01_70 *(dp+1) = Interp7(w[5], w[2], w[6]); +#define PIXEL01_90 *(dp+1) = Interp9(w[5], w[2], w[6]); +#define PIXEL01_100 *(dp+1) = Interp10(w[5], w[2], w[6]); +#define PIXEL10_0 *(dp+dpL) = w[5]; +#define PIXEL10_10 *(dp+dpL) = Interp1(w[5], w[7]); +#define PIXEL10_11 *(dp+dpL) = Interp1(w[5], w[8]); +#define PIXEL10_12 *(dp+dpL) = Interp1(w[5], w[4]); +#define PIXEL10_20 *(dp+dpL) = Interp2(w[5], w[8], w[4]); +#define PIXEL10_21 *(dp+dpL) = Interp2(w[5], w[7], w[4]); +#define PIXEL10_22 *(dp+dpL) = Interp2(w[5], w[7], w[8]); +#define PIXEL10_60 *(dp+dpL) = Interp6(w[5], w[4], w[8]); +#define PIXEL10_61 *(dp+dpL) = Interp6(w[5], w[8], w[4]); +#define PIXEL10_70 *(dp+dpL) = Interp7(w[5], w[8], w[4]); +#define PIXEL10_90 *(dp+dpL) = Interp9(w[5], w[8], w[4]); +#define PIXEL10_100 *(dp+dpL) = Interp10(w[5], w[8], w[4]); +#define PIXEL11_0 *(dp+dpL+1) = w[5]; +#define PIXEL11_10 *(dp+dpL+1) = Interp1(w[5], w[9]); +#define PIXEL11_11 *(dp+dpL+1) = Interp1(w[5], w[6]); +#define PIXEL11_12 *(dp+dpL+1) = Interp1(w[5], w[8]); +#define PIXEL11_20 *(dp+dpL+1) = Interp2(w[5], w[6], w[8]); +#define PIXEL11_21 *(dp+dpL+1) = Interp2(w[5], w[9], w[8]); +#define PIXEL11_22 *(dp+dpL+1) = Interp2(w[5], w[9], w[6]); +#define PIXEL11_60 *(dp+dpL+1) = Interp6(w[5], w[8], w[6]); +#define PIXEL11_61 *(dp+dpL+1) = Interp6(w[5], w[6], w[8]); +#define PIXEL11_70 *(dp+dpL+1) = Interp7(w[5], w[6], w[8]); +#define PIXEL11_90 *(dp+dpL+1) = Interp9(w[5], w[6], w[8]); +#define PIXEL11_100 *(dp+dpL+1) = Interp10(w[5], w[6], w[8]); + +HQX_API void HQX_CALLCONV hq2x_32_rb( uint32_t * sp, uint32_t srb, uint32_t * dp, uint32_t drb, int Xres, int Yres ) +{ + int i, j, k; + int prevline, nextline; + uint32_t w[10]; + int dpL = (drb >> 2); + int spL = (srb >> 2); + uint8_t *sRowP = (uint8_t *) sp; + uint8_t *dRowP = (uint8_t *) dp; + uint32_t yuv1, yuv2; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j=0; j0) prevline = -spL; else prevline = 0; + if (j0) + { + w[1] = *(sp + prevline - 1); + w[4] = *(sp - 1); + w[7] = *(sp + nextline - 1); + } + else + { + w[1] = w[2]; + w[4] = w[5]; + w[7] = w[8]; + } + + if (i> 2); + int spL = (srb >> 2); + uint8_t *sRowP = (uint8_t *) sp; + uint8_t *dRowP = (uint8_t *) dp; + uint32_t yuv1, yuv2; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j=0; j0) prevline = -spL; else prevline = 0; + if (j0) + { + w[1] = *(sp + prevline - 1); + w[4] = *(sp - 1); + w[7] = *(sp + nextline - 1); + } + else + { + w[1] = w[2]; + w[4] = w[5]; + w[7] = w[8]; + } + + if (i> 2); + int spL = (srb >> 2); + uint8_t *sRowP = (uint8_t *) sp; + uint8_t *dRowP = (uint8_t *) dp; + uint32_t yuv1, yuv2; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j=0; j0) prevline = -spL; else prevline = 0; + if (j0) + { + w[1] = *(sp + prevline - 1); + w[4] = *(sp - 1); + w[7] = *(sp + nextline - 1); + } + else + { + w[1] = w[2]; + w[4] = w[5]; + w[7] = w[8]; + } + + if (i + +#if defined( __GNUC__ ) + #ifdef __MINGW32__ + #define HQX_CALLCONV __stdcall + #else + #define HQX_CALLCONV + #endif +#else + #define HQX_CALLCONV +#endif + +#if 0 //defined(_WIN32) + #ifdef DLL_EXPORT + #define HQX_API __declspec(dllexport) + #else + #define HQX_API __declspec(dllimport) + #endif +#else + #define HQX_API +#endif + +HQX_API void HQX_CALLCONV hqxInit(void); +HQX_API void HQX_CALLCONV hq2x_32( uint32_t * src, uint32_t * dest, int width, int height ); +HQX_API void HQX_CALLCONV hq3x_32( uint32_t * src, uint32_t * dest, int width, int height ); +HQX_API void HQX_CALLCONV hq4x_32( uint32_t * src, uint32_t * dest, int width, int height ); + +HQX_API void HQX_CALLCONV hq2x_32_rb( uint32_t * src, uint32_t src_rowBytes, uint32_t * dest, uint32_t dest_rowBytes, int width, int height ); +HQX_API void HQX_CALLCONV hq3x_32_rb( uint32_t * src, uint32_t src_rowBytes, uint32_t * dest, uint32_t dest_rowBytes, int width, int height ); +HQX_API void HQX_CALLCONV hq4x_32_rb( uint32_t * src, uint32_t src_rowBytes, uint32_t * dest, uint32_t dest_rowBytes, int width, int height ); + +#endif diff --git a/src/gl/hqnx/init.cpp b/src/gl/hqnx/init.cpp new file mode 100644 index 000000000..0e8c2db1c --- /dev/null +++ b/src/gl/hqnx/init.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2010 Cameron Zemek ( grom@zeminvaders.net) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "hqx.h" + +uint32_t *RGBtoYUV; +uint32_t YUV1, YUV2; + +HQX_API void HQX_CALLCONV hqxInit(void) +{ + /* Initalize RGB to YUV lookup table */ + uint32_t c, r, g, b, y, u, v; + RGBtoYUV = new uint32_t[16777216]; + for (c = 0; c < 16777215; c++) { + r = (c & 0xFF0000) >> 16; + g = (c & 0x00FF00) >> 8; + b = c & 0x0000FF; + y = (uint32_t)(0.299*r + 0.587*g + 0.114*b); + u = (uint32_t)(-0.169*r - 0.331*g + 0.5*b) + 128; + v = (uint32_t)(0.5*r - 0.419*g - 0.081*b) + 128; + RGBtoYUV[c] = (y << 16) + (u << 8) + v; + } +} diff --git a/src/gl/hqnx_asm/hq2x_asm.cpp b/src/gl/hqnx_asm/hq2x_asm.cpp new file mode 100644 index 000000000..65e460377 --- /dev/null +++ b/src/gl/hqnx_asm/hq2x_asm.cpp @@ -0,0 +1,2943 @@ +//hq2x filter demo program +//---------------------------------------------------------- +//Copyright (C) 2003 MaxSt ( maxst@hiend3d.com ) +//Copyright (C) 2012-2014 Alexey Lysiuk +// +//This program is free software; you can redistribute it and/or +//modify it under the terms of the GNU Lesser General Public +//License as published by the Free Software Foundation; either +//version 2.1 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 +//Lesser General Public License for more details. +// +//You should have received a copy of the GNU Lesser General Public +//License along with this program; if not, write to the Free Software +//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +#include "hqnx_asm.h" + +namespace HQnX_asm +{ + +extern int LUT16to32[65536*2]; +extern int RGBtoYUV[65536*2]; + +static const hq_vec const3 = hq_vec::expand(0x0003); +static const hq_vec const5 = hq_vec::expand(0x0005); +static const hq_vec const6 = hq_vec::expand(0x0006); +static const hq_vec const14 = hq_vec::expand(0x000E); + +inline void Interp1(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1*3+c2)/4; + + hq_vec result = hq_vec::load(c1); + + result *= const3; + result += hq_vec::load(c2); + result >> 2; + + result.store(pc); +} + +inline void Interp2(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*2+c2+c3) >> 2; + + hq_vec result = hq_vec::load(c1); + + result << 1; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 2; + + result.store(pc); +} + +inline void Interp5(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1+c2)/2; + + hq_vec result = hq_vec::load(c1); + + result += hq_vec::load(c2); + result >> 1; + + result.store(pc); +} + +inline void Interp6(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*5+c2*2+c3)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const5; + result += hq_vec::load(c2) << 1; + result += hq_vec::load(c3); + result >> 3; + + result.store(pc); +} + +inline void Interp7(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*6+c2+c3)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const6; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 3; + + result.store(pc); +} + +inline void Interp9(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*2+(c2+c3)*3)/8; + + hq_vec result = hq_vec::load(c2); + + result += hq_vec::load(c3); + result *= const3; + result += hq_vec::load(c1) << 1; + result >> 3; + + result.store(pc); +} + +inline void Interp10(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*14+c2+c3)/16; + + hq_vec result = hq_vec::load(c1); + + result *= const14; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 4; + + result.store(pc); +} + +#define PIXEL00_0 *((int*)(pOut)) = c[5]; +#define PIXEL00_10 Interp1(pOut, c[5], c[1]); +#define PIXEL00_11 Interp1(pOut, c[5], c[4]); +#define PIXEL00_12 Interp1(pOut, c[5], c[2]); +#define PIXEL00_20 Interp2(pOut, c[5], c[4], c[2]); +#define PIXEL00_21 Interp2(pOut, c[5], c[1], c[2]); +#define PIXEL00_22 Interp2(pOut, c[5], c[1], c[4]); +#define PIXEL00_60 Interp6(pOut, c[5], c[2], c[4]); +#define PIXEL00_61 Interp6(pOut, c[5], c[4], c[2]); +#define PIXEL00_70 Interp7(pOut, c[5], c[4], c[2]); +#define PIXEL00_90 Interp9(pOut, c[5], c[4], c[2]); +#define PIXEL00_100 Interp10(pOut, c[5], c[4], c[2]); +#define PIXEL01_0 *((int*)(pOut+4)) = c[5]; +#define PIXEL01_10 Interp1(pOut+4, c[5], c[3]); +#define PIXEL01_11 Interp1(pOut+4, c[5], c[2]); +#define PIXEL01_12 Interp1(pOut+4, c[5], c[6]); +#define PIXEL01_20 Interp2(pOut+4, c[5], c[2], c[6]); +#define PIXEL01_21 Interp2(pOut+4, c[5], c[3], c[6]); +#define PIXEL01_22 Interp2(pOut+4, c[5], c[3], c[2]); +#define PIXEL01_60 Interp6(pOut+4, c[5], c[6], c[2]); +#define PIXEL01_61 Interp6(pOut+4, c[5], c[2], c[6]); +#define PIXEL01_70 Interp7(pOut+4, c[5], c[2], c[6]); +#define PIXEL01_90 Interp9(pOut+4, c[5], c[2], c[6]); +#define PIXEL01_100 Interp10(pOut+4, c[5], c[2], c[6]); +#define PIXEL10_0 *((int*)(pOut+BpL)) = c[5]; +#define PIXEL10_10 Interp1(pOut+BpL, c[5], c[7]); +#define PIXEL10_11 Interp1(pOut+BpL, c[5], c[8]); +#define PIXEL10_12 Interp1(pOut+BpL, c[5], c[4]); +#define PIXEL10_20 Interp2(pOut+BpL, c[5], c[8], c[4]); +#define PIXEL10_21 Interp2(pOut+BpL, c[5], c[7], c[4]); +#define PIXEL10_22 Interp2(pOut+BpL, c[5], c[7], c[8]); +#define PIXEL10_60 Interp6(pOut+BpL, c[5], c[4], c[8]); +#define PIXEL10_61 Interp6(pOut+BpL, c[5], c[8], c[4]); +#define PIXEL10_70 Interp7(pOut+BpL, c[5], c[8], c[4]); +#define PIXEL10_90 Interp9(pOut+BpL, c[5], c[8], c[4]); +#define PIXEL10_100 Interp10(pOut+BpL, c[5], c[8], c[4]); +#define PIXEL11_0 *((int*)(pOut+BpL+4)) = c[5]; +#define PIXEL11_10 Interp1(pOut+BpL+4, c[5], c[9]); +#define PIXEL11_11 Interp1(pOut+BpL+4, c[5], c[6]); +#define PIXEL11_12 Interp1(pOut+BpL+4, c[5], c[8]); +#define PIXEL11_20 Interp2(pOut+BpL+4, c[5], c[6], c[8]); +#define PIXEL11_21 Interp2(pOut+BpL+4, c[5], c[9], c[8]); +#define PIXEL11_22 Interp2(pOut+BpL+4, c[5], c[9], c[6]); +#define PIXEL11_60 Interp6(pOut+BpL+4, c[5], c[8], c[6]); +#define PIXEL11_61 Interp6(pOut+BpL+4, c[5], c[6], c[8]); +#define PIXEL11_70 Interp7(pOut+BpL+4, c[5], c[6], c[8]); +#define PIXEL11_90 Interp9(pOut+BpL+4, c[5], c[6], c[8]); +#define PIXEL11_100 Interp10(pOut+BpL+4, c[5], c[6], c[8]); + + +bool Diff(const unsigned int, const unsigned int); + +void DLL hq2x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ) +{ + int i, j, k; + int w[10]; + unsigned int c[10]; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j=0; j0) + { + w[1] = *(pIn - Xres - 1); + } + else + { + w[1] = 0; + } + + w[2] = *(pIn - Xres); + + if (i0) + { + w[4] = *(pIn - 1); + } + else + { + w[4] = 0; + } + + w[5] = *(pIn); + if (i0) + { + w[7] = *(pIn + Xres - 1); + } + else + { + w[7] = 0; + } + + w[8] = *(pIn + Xres); + if (i> 2; + + result.store(pc); +} + +inline void Interp2(unsigned char * pc, int c1, int c2, int c3) +{ +// *((int*)pc) = (c1*2+c2+c3)/4; + + hq_vec result = hq_vec::load(c1); + + result << 1; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 2; + + result.store(pc); +} + +inline void Interp3(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1*7+c2)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const7; + result += hq_vec::load(c2); + result >> 3; + + result.store(pc); +} + +inline void Interp4(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*2+(c2+c3)*7)/16; + + hq_vec result = hq_vec::load(c2); + + result += hq_vec::load(c3); + result *= const7; + result += hq_vec::load(c1) << 1; + result >> 4; + + result.store(pc); +} + +inline void Interp5(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1+c2)/2; + + hq_vec result = hq_vec::load(c1); + + result += hq_vec::load(c2); + result >> 1; + + result.store(pc); +} + +#define PIXEL00_1M Interp1(pOut, c[5], c[1]); +#define PIXEL00_1U Interp1(pOut, c[5], c[2]); +#define PIXEL00_1L Interp1(pOut, c[5], c[4]); +#define PIXEL00_2 Interp2(pOut, c[5], c[4], c[2]); +#define PIXEL00_4 Interp4(pOut, c[5], c[4], c[2]); +#define PIXEL00_5 Interp5(pOut, c[4], c[2]); +#define PIXEL00_C *((int*)(pOut)) = c[5]; + +#define PIXEL01_1 Interp1(pOut+4, c[5], c[2]); +#define PIXEL01_3 Interp3(pOut+4, c[5], c[2]); +#define PIXEL01_6 Interp1(pOut+4, c[2], c[5]); +#define PIXEL01_C *((int*)(pOut+4)) = c[5]; + +#define PIXEL02_1M Interp1(pOut+8, c[5], c[3]); +#define PIXEL02_1U Interp1(pOut+8, c[5], c[2]); +#define PIXEL02_1R Interp1(pOut+8, c[5], c[6]); +#define PIXEL02_2 Interp2(pOut+8, c[5], c[2], c[6]); +#define PIXEL02_4 Interp4(pOut+8, c[5], c[2], c[6]); +#define PIXEL02_5 Interp5(pOut+8, c[2], c[6]); +#define PIXEL02_C *((int*)(pOut+8)) = c[5]; + +#define PIXEL10_1 Interp1(pOut+BpL, c[5], c[4]); +#define PIXEL10_3 Interp3(pOut+BpL, c[5], c[4]); +#define PIXEL10_6 Interp1(pOut+BpL, c[4], c[5]); +#define PIXEL10_C *((int*)(pOut+BpL)) = c[5]; + +#define PIXEL11 *((int*)(pOut+BpL+4)) = c[5]; + +#define PIXEL12_1 Interp1(pOut+BpL+8, c[5], c[6]); +#define PIXEL12_3 Interp3(pOut+BpL+8, c[5], c[6]); +#define PIXEL12_6 Interp1(pOut+BpL+8, c[6], c[5]); +#define PIXEL12_C *((int*)(pOut+BpL+8)) = c[5]; + +#define PIXEL20_1M Interp1(pOut+BpL+BpL, c[5], c[7]); +#define PIXEL20_1D Interp1(pOut+BpL+BpL, c[5], c[8]); +#define PIXEL20_1L Interp1(pOut+BpL+BpL, c[5], c[4]); +#define PIXEL20_2 Interp2(pOut+BpL+BpL, c[5], c[8], c[4]); +#define PIXEL20_4 Interp4(pOut+BpL+BpL, c[5], c[8], c[4]); +#define PIXEL20_5 Interp5(pOut+BpL+BpL, c[8], c[4]); +#define PIXEL20_C *((int*)(pOut+BpL+BpL)) = c[5]; + +#define PIXEL21_1 Interp1(pOut+BpL+BpL+4, c[5], c[8]); +#define PIXEL21_3 Interp3(pOut+BpL+BpL+4, c[5], c[8]); +#define PIXEL21_6 Interp1(pOut+BpL+BpL+4, c[8], c[5]); +#define PIXEL21_C *((int*)(pOut+BpL+BpL+4)) = c[5]; + +#define PIXEL22_1M Interp1(pOut+BpL+BpL+8, c[5], c[9]); +#define PIXEL22_1D Interp1(pOut+BpL+BpL+8, c[5], c[8]); +#define PIXEL22_1R Interp1(pOut+BpL+BpL+8, c[5], c[6]); +#define PIXEL22_2 Interp2(pOut+BpL+BpL+8, c[5], c[6], c[8]); +#define PIXEL22_4 Interp4(pOut+BpL+BpL+8, c[5], c[6], c[8]); +#define PIXEL22_5 Interp5(pOut+BpL+BpL+8, c[6], c[8]); +#define PIXEL22_C *((int*)(pOut+BpL+BpL+8)) = c[5]; + +bool Diff(const unsigned int, const unsigned int); + +void DLL hq3x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ) +{ + int i, j, k; + int w[10]; + unsigned int c[10]; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j=0; j0) w[1] = *(pIn - Xres - 1); else w[1] = 0; + w[2] = *(pIn - Xres); + if (i0) w[4] = *(pIn - 1); else w[4] = 0; + w[5] = *(pIn); + if (i0) w[7] = *(pIn + Xres - 1); else w[7] = 0; + w[8] = *(pIn + Xres); + if (i +#include +#include +#include "hqnx_asm.h" + +namespace HQnX_asm +{ + +int LUT16to32[65536*2]; +int RGBtoYUV[65536*2]; + +static const hq_vec const3 = hq_vec::expand(0x0003); +static const hq_vec const5 = hq_vec::expand(0x0005); +static const hq_vec const6 = hq_vec::expand(0x0006); +static const hq_vec const7 = hq_vec::expand(0x0007); + + +inline void Interp1(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1*3+c2)/4; + + hq_vec result = hq_vec::load(c1); + + result *= const3; + result += hq_vec::load(c2); + result >> 2; + + result.store(pc); +} + +inline void Interp2(unsigned char * pc, int c1, int c2, int c3) +{ +// *((int*)pc) = (c1*2+c2+c3)/4; + + hq_vec result = hq_vec::load(c1); + + result << 1; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 2; + + result.store(pc); +} + +inline void Interp3(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1*7+c2)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const7; + result += hq_vec::load(c2); + result >> 3; + + result.store(pc); +} + +inline void Interp5(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1+c2)/2; + + hq_vec result = hq_vec::load(c1); + + result += hq_vec::load(c2); + result >> 1; + + result.store(pc); +} + +inline void Interp6(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*5+c2*2+c3)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const5; + result += hq_vec::load(c2) << 1; + result += hq_vec::load(c3); + result >> 3; + + result.store(pc); +} + +inline void Interp7(unsigned char * pc, int c1, int c2, int c3) +{ + //*((int*)pc) = (c1*6+c2+c3)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const6; + result += hq_vec::load(c2); + result += hq_vec::load(c3); + result >> 3; + + result.store(pc); +} + +inline void Interp8(unsigned char * pc, int c1, int c2) +{ + //*((int*)pc) = (c1*5+c2*3)/8; + + hq_vec result = hq_vec::load(c1); + + result *= const5; + result += hq_vec::load(c2) * const3; + result >> 3; + + result.store(pc); +} + +#define PIXEL00_0 *((int*)(pOut)) = c[5]; +#define PIXEL00_11 Interp1(pOut, c[5], c[4]); +#define PIXEL00_12 Interp1(pOut, c[5], c[2]); +#define PIXEL00_20 Interp2(pOut, c[5], c[2], c[4]); +#define PIXEL00_50 Interp5(pOut, c[2], c[4]); +#define PIXEL00_80 Interp8(pOut, c[5], c[1]); +#define PIXEL00_81 Interp8(pOut, c[5], c[4]); +#define PIXEL00_82 Interp8(pOut, c[5], c[2]); +#define PIXEL01_0 *((int*)(pOut+4)) = c[5]; +#define PIXEL01_10 Interp1(pOut+4, c[5], c[1]); +#define PIXEL01_12 Interp1(pOut+4, c[5], c[2]); +#define PIXEL01_14 Interp1(pOut+4, c[2], c[5]); +#define PIXEL01_21 Interp2(pOut+4, c[2], c[5], c[4]); +#define PIXEL01_31 Interp3(pOut+4, c[5], c[4]); +#define PIXEL01_50 Interp5(pOut+4, c[2], c[5]); +#define PIXEL01_60 Interp6(pOut+4, c[5], c[2], c[4]); +#define PIXEL01_61 Interp6(pOut+4, c[5], c[2], c[1]); +#define PIXEL01_82 Interp8(pOut+4, c[5], c[2]); +#define PIXEL01_83 Interp8(pOut+4, c[2], c[4]); +#define PIXEL02_0 *((int*)(pOut+8)) = c[5]; +#define PIXEL02_10 Interp1(pOut+8, c[5], c[3]); +#define PIXEL02_11 Interp1(pOut+8, c[5], c[2]); +#define PIXEL02_13 Interp1(pOut+8, c[2], c[5]); +#define PIXEL02_21 Interp2(pOut+8, c[2], c[5], c[6]); +#define PIXEL02_32 Interp3(pOut+8, c[5], c[6]); +#define PIXEL02_50 Interp5(pOut+8, c[2], c[5]); +#define PIXEL02_60 Interp6(pOut+8, c[5], c[2], c[6]); +#define PIXEL02_61 Interp6(pOut+8, c[5], c[2], c[3]); +#define PIXEL02_81 Interp8(pOut+8, c[5], c[2]); +#define PIXEL02_83 Interp8(pOut+8, c[2], c[6]); +#define PIXEL03_0 *((int*)(pOut+12)) = c[5]; +#define PIXEL03_11 Interp1(pOut+12, c[5], c[2]); +#define PIXEL03_12 Interp1(pOut+12, c[5], c[6]); +#define PIXEL03_20 Interp2(pOut+12, c[5], c[2], c[6]); +#define PIXEL03_50 Interp5(pOut+12, c[2], c[6]); +#define PIXEL03_80 Interp8(pOut+12, c[5], c[3]); +#define PIXEL03_81 Interp8(pOut+12, c[5], c[2]); +#define PIXEL03_82 Interp8(pOut+12, c[5], c[6]); +#define PIXEL10_0 *((int*)(pOut+BpL)) = c[5]; +#define PIXEL10_10 Interp1(pOut+BpL, c[5], c[1]); +#define PIXEL10_11 Interp1(pOut+BpL, c[5], c[4]); +#define PIXEL10_13 Interp1(pOut+BpL, c[4], c[5]); +#define PIXEL10_21 Interp2(pOut+BpL, c[4], c[5], c[2]); +#define PIXEL10_32 Interp3(pOut+BpL, c[5], c[2]); +#define PIXEL10_50 Interp5(pOut+BpL, c[4], c[5]); +#define PIXEL10_60 Interp6(pOut+BpL, c[5], c[4], c[2]); +#define PIXEL10_61 Interp6(pOut+BpL, c[5], c[4], c[1]); +#define PIXEL10_81 Interp8(pOut+BpL, c[5], c[4]); +#define PIXEL10_83 Interp8(pOut+BpL, c[4], c[2]); +#define PIXEL11_0 *((int*)(pOut+BpL+4)) = c[5]; +#define PIXEL11_30 Interp3(pOut+BpL+4, c[5], c[1]); +#define PIXEL11_31 Interp3(pOut+BpL+4, c[5], c[4]); +#define PIXEL11_32 Interp3(pOut+BpL+4, c[5], c[2]); +#define PIXEL11_70 Interp7(pOut+BpL+4, c[5], c[4], c[2]); +#define PIXEL12_0 *((int*)(pOut+BpL+8)) = c[5]; +#define PIXEL12_30 Interp3(pOut+BpL+8, c[5], c[3]); +#define PIXEL12_31 Interp3(pOut+BpL+8, c[5], c[2]); +#define PIXEL12_32 Interp3(pOut+BpL+8, c[5], c[6]); +#define PIXEL12_70 Interp7(pOut+BpL+8, c[5], c[6], c[2]); +#define PIXEL13_0 *((int*)(pOut+BpL+12)) = c[5]; +#define PIXEL13_10 Interp1(pOut+BpL+12, c[5], c[3]); +#define PIXEL13_12 Interp1(pOut+BpL+12, c[5], c[6]); +#define PIXEL13_14 Interp1(pOut+BpL+12, c[6], c[5]); +#define PIXEL13_21 Interp2(pOut+BpL+12, c[6], c[5], c[2]); +#define PIXEL13_31 Interp3(pOut+BpL+12, c[5], c[2]); +#define PIXEL13_50 Interp5(pOut+BpL+12, c[6], c[5]); +#define PIXEL13_60 Interp6(pOut+BpL+12, c[5], c[6], c[2]); +#define PIXEL13_61 Interp6(pOut+BpL+12, c[5], c[6], c[3]); +#define PIXEL13_82 Interp8(pOut+BpL+12, c[5], c[6]); +#define PIXEL13_83 Interp8(pOut+BpL+12, c[6], c[2]); +#define PIXEL20_0 *((int*)(pOut+BpL+BpL)) = c[5]; +#define PIXEL20_10 Interp1(pOut+BpL+BpL, c[5], c[7]); +#define PIXEL20_12 Interp1(pOut+BpL+BpL, c[5], c[4]); +#define PIXEL20_14 Interp1(pOut+BpL+BpL, c[4], c[5]); +#define PIXEL20_21 Interp2(pOut+BpL+BpL, c[4], c[5], c[8]); +#define PIXEL20_31 Interp3(pOut+BpL+BpL, c[5], c[8]); +#define PIXEL20_50 Interp5(pOut+BpL+BpL, c[4], c[5]); +#define PIXEL20_60 Interp6(pOut+BpL+BpL, c[5], c[4], c[8]); +#define PIXEL20_61 Interp6(pOut+BpL+BpL, c[5], c[4], c[7]); +#define PIXEL20_82 Interp8(pOut+BpL+BpL, c[5], c[4]); +#define PIXEL20_83 Interp8(pOut+BpL+BpL, c[4], c[8]); +#define PIXEL21_0 *((int*)(pOut+BpL+BpL+4)) = c[5]; +#define PIXEL21_30 Interp3(pOut+BpL+BpL+4, c[5], c[7]); +#define PIXEL21_31 Interp3(pOut+BpL+BpL+4, c[5], c[8]); +#define PIXEL21_32 Interp3(pOut+BpL+BpL+4, c[5], c[4]); +#define PIXEL21_70 Interp7(pOut+BpL+BpL+4, c[5], c[4], c[8]); +#define PIXEL22_0 *((int*)(pOut+BpL+BpL+8)) = c[5]; +#define PIXEL22_30 Interp3(pOut+BpL+BpL+8, c[5], c[9]); +#define PIXEL22_31 Interp3(pOut+BpL+BpL+8, c[5], c[6]); +#define PIXEL22_32 Interp3(pOut+BpL+BpL+8, c[5], c[8]); +#define PIXEL22_70 Interp7(pOut+BpL+BpL+8, c[5], c[6], c[8]); +#define PIXEL23_0 *((int*)(pOut+BpL+BpL+12)) = c[5]; +#define PIXEL23_10 Interp1(pOut+BpL+BpL+12, c[5], c[9]); +#define PIXEL23_11 Interp1(pOut+BpL+BpL+12, c[5], c[6]); +#define PIXEL23_13 Interp1(pOut+BpL+BpL+12, c[6], c[5]); +#define PIXEL23_21 Interp2(pOut+BpL+BpL+12, c[6], c[5], c[8]); +#define PIXEL23_32 Interp3(pOut+BpL+BpL+12, c[5], c[8]); +#define PIXEL23_50 Interp5(pOut+BpL+BpL+12, c[6], c[5]); +#define PIXEL23_60 Interp6(pOut+BpL+BpL+12, c[5], c[6], c[8]); +#define PIXEL23_61 Interp6(pOut+BpL+BpL+12, c[5], c[6], c[9]); +#define PIXEL23_81 Interp8(pOut+BpL+BpL+12, c[5], c[6]); +#define PIXEL23_83 Interp8(pOut+BpL+BpL+12, c[6], c[8]); +#define PIXEL30_0 *((int*)(pOut+BpL+BpL+BpL)) = c[5]; +#define PIXEL30_11 Interp1(pOut+BpL+BpL+BpL, c[5], c[8]); +#define PIXEL30_12 Interp1(pOut+BpL+BpL+BpL, c[5], c[4]); +#define PIXEL30_20 Interp2(pOut+BpL+BpL+BpL, c[5], c[8], c[4]); +#define PIXEL30_50 Interp5(pOut+BpL+BpL+BpL, c[8], c[4]); +#define PIXEL30_80 Interp8(pOut+BpL+BpL+BpL, c[5], c[7]); +#define PIXEL30_81 Interp8(pOut+BpL+BpL+BpL, c[5], c[8]); +#define PIXEL30_82 Interp8(pOut+BpL+BpL+BpL, c[5], c[4]); +#define PIXEL31_0 *((int*)(pOut+BpL+BpL+BpL+4)) = c[5]; +#define PIXEL31_10 Interp1(pOut+BpL+BpL+BpL+4, c[5], c[7]); +#define PIXEL31_11 Interp1(pOut+BpL+BpL+BpL+4, c[5], c[8]); +#define PIXEL31_13 Interp1(pOut+BpL+BpL+BpL+4, c[8], c[5]); +#define PIXEL31_21 Interp2(pOut+BpL+BpL+BpL+4, c[8], c[5], c[4]); +#define PIXEL31_32 Interp3(pOut+BpL+BpL+BpL+4, c[5], c[4]); +#define PIXEL31_50 Interp5(pOut+BpL+BpL+BpL+4, c[8], c[5]); +#define PIXEL31_60 Interp6(pOut+BpL+BpL+BpL+4, c[5], c[8], c[4]); +#define PIXEL31_61 Interp6(pOut+BpL+BpL+BpL+4, c[5], c[8], c[7]); +#define PIXEL31_81 Interp8(pOut+BpL+BpL+BpL+4, c[5], c[8]); +#define PIXEL31_83 Interp8(pOut+BpL+BpL+BpL+4, c[8], c[4]); +#define PIXEL32_0 *((int*)(pOut+BpL+BpL+BpL+8)) = c[5]; +#define PIXEL32_10 Interp1(pOut+BpL+BpL+BpL+8, c[5], c[9]); +#define PIXEL32_12 Interp1(pOut+BpL+BpL+BpL+8, c[5], c[8]); +#define PIXEL32_14 Interp1(pOut+BpL+BpL+BpL+8, c[8], c[5]); +#define PIXEL32_21 Interp2(pOut+BpL+BpL+BpL+8, c[8], c[5], c[6]); +#define PIXEL32_31 Interp3(pOut+BpL+BpL+BpL+8, c[5], c[6]); +#define PIXEL32_50 Interp5(pOut+BpL+BpL+BpL+8, c[8], c[5]); +#define PIXEL32_60 Interp6(pOut+BpL+BpL+BpL+8, c[5], c[8], c[6]); +#define PIXEL32_61 Interp6(pOut+BpL+BpL+BpL+8, c[5], c[8], c[9]); +#define PIXEL32_82 Interp8(pOut+BpL+BpL+BpL+8, c[5], c[8]); +#define PIXEL32_83 Interp8(pOut+BpL+BpL+BpL+8, c[8], c[6]); +#define PIXEL33_0 *((int*)(pOut+BpL+BpL+BpL+12)) = c[5]; +#define PIXEL33_11 Interp1(pOut+BpL+BpL+BpL+12, c[5], c[6]); +#define PIXEL33_12 Interp1(pOut+BpL+BpL+BpL+12, c[5], c[8]); +#define PIXEL33_20 Interp2(pOut+BpL+BpL+BpL+12, c[5], c[8], c[6]); +#define PIXEL33_50 Interp5(pOut+BpL+BpL+BpL+12, c[8], c[6]); +#define PIXEL33_80 Interp8(pOut+BpL+BpL+BpL+12, c[5], c[9]); +#define PIXEL33_81 Interp8(pOut+BpL+BpL+BpL+12, c[5], c[6]); +#define PIXEL33_82 Interp8(pOut+BpL+BpL+BpL+12, c[5], c[8]); + +bool Diff(const unsigned int rgb1, const unsigned int rgb2) +{ + if (rgb1 == rgb2) + { + return false; + } + + static const hq_vec THRESHOLD = 0x00300706; + + const hq_vec yuv1 = RGBtoYUV[rgb1]; + const hq_vec yuv2 = RGBtoYUV[rgb2]; + + const hq_vec delta1 = yuv1 - yuv2; + const hq_vec delta2 = yuv2 - yuv1; + + const hq_vec delta = delta1 | delta2; + const hq_vec result = delta - THRESHOLD; + + return 0 != result; +} + +void DLL hq4x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ) +{ + int i, j, k; + int w[10]; + int c[10]; + + // +----+----+----+ + // | | | | + // | w1 | w2 | w3 | + // +----+----+----+ + // | | | | + // | w4 | w5 | w6 | + // +----+----+----+ + // | | | | + // | w7 | w8 | w9 | + // +----+----+----+ + + for (j = 0; j < Yres; j++) + { + for (i = 0; i < Xres; i++) + { + if (j == 0) + { + w[1] = 0; + w[2] = 0; + w[3] = 0; + } + else + { + if (i > 0) + w[1] = *(pIn - Xres - 1); + else + w[1] = 0; + + w[2] = *(pIn - Xres); + + if (i < Xres - 1) + w[3] = *(pIn - Xres + 1); + else + w[3] = 0; + } + + if (i > 0) + w[4] = *(pIn - 1); + else + w[4] = 0; + + w[5] = *(pIn); + + if (i < Xres - 1) + w[6] = *(pIn + 1); + else + w[6] = 0; + + if (j == Yres - 1) + { + w[7] = 0; + w[8] = 0; + w[9] = 0; + } + else + { + if (i > 0) + w[7] = *(pIn + Xres - 1); + else + w[7] = 0; + + w[8] = *(pIn + Xres); + + if (i < Xres-1) + w[9] = *(pIn + Xres + 1); + else + w[9] = 0; + } + + int pattern = 0; + + if ( Diff(w[5],w[1]) ) pattern |= 0x0001; + if ( Diff(w[5],w[2]) ) pattern |= 0x0002; + if ( Diff(w[5],w[3]) ) pattern |= 0x0004; + if ( Diff(w[5],w[4]) ) pattern |= 0x0008; + if ( Diff(w[5],w[6]) ) pattern |= 0x0010; + if ( Diff(w[5],w[7]) ) pattern |= 0x0020; + if ( Diff(w[5],w[8]) ) pattern |= 0x0040; + if ( Diff(w[5],w[9]) ) pattern |= 0x0080; + + for (k=1; k<=9; k++) + c[k] = LUT16to32[w[k]]; + + switch (pattern) + { + case 0: + case 1: + case 4: + case 32: + case 128: + case 5: + case 132: + case 160: + case 33: + case 129: + case 36: + case 133: + case 164: + case 161: + case 37: + case 165: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 2: + case 34: + case 130: + case 162: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 16: + case 17: + case 48: + case 49: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 64: + case 65: + case 68: + case 69: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 8: + case 12: + case 136: + case 140: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 3: + case 35: + case 131: + case 163: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_61 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 6: + case 38: + case 134: + case 166: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_61 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 20: + case 21: + case 52: + case 53: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + PIXEL03_81 + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL13_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 144: + case 145: + case 176: + case 177: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL23_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + PIXEL33_82 + break; + } + case 192: + case 193: + case 196: + case 197: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_61 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 96: + case 97: + case 100: + case 101: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_61 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 40: + case 44: + case 168: + case 172: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + PIXEL20_31 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL30_81 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 9: + case 13: + case 137: + case 141: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL10_32 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 18: + case 50: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL12_0 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 80: + case 81: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_61 + PIXEL21_30 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 72: + case 76: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_50 + PIXEL21_0 + PIXEL30_50 + PIXEL31_50 + } + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 10: + case 138: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + PIXEL11_0 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_61 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 66: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 24: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 7: + case 39: + case 135: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 148: + case 149: + case 180: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + PIXEL03_81 + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL13_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL23_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + PIXEL33_82 + break; + } + case 224: + case 228: + case 225: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 41: + case 169: + case 45: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL10_32 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL20_31 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL30_81 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 22: + case 54: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL12_0 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 208: + case 209: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_61 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 104: + case 108: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 11: + case 139: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_61 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 19: + case 51: + { + if (Diff(w[2], w[6])) + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL00_12 + PIXEL01_14 + PIXEL02_83 + PIXEL03_50 + PIXEL12_70 + PIXEL13_21 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 146: + case 178: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + PIXEL23_32 + PIXEL33_82 + } + else + { + PIXEL02_21 + PIXEL03_50 + PIXEL12_70 + PIXEL13_83 + PIXEL23_13 + PIXEL33_11 + } + PIXEL10_61 + PIXEL11_30 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + break; + } + case 84: + case 85: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + if (Diff(w[6], w[8])) + { + PIXEL03_81 + PIXEL13_31 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL03_12 + PIXEL13_14 + PIXEL22_70 + PIXEL23_83 + PIXEL32_21 + PIXEL33_50 + } + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL20_61 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + break; + } + case 112: + case 113: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_70 + PIXEL23_21 + PIXEL30_11 + PIXEL31_13 + PIXEL32_83 + PIXEL33_50 + } + break; + } + case 200: + case 204: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + } + else + { + PIXEL20_21 + PIXEL21_70 + PIXEL30_50 + PIXEL31_83 + PIXEL32_14 + PIXEL33_12 + } + PIXEL22_31 + PIXEL23_81 + break; + } + case 73: + case 77: + { + if (Diff(w[8], w[4])) + { + PIXEL00_82 + PIXEL10_32 + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL00_11 + PIXEL10_13 + PIXEL20_83 + PIXEL21_70 + PIXEL30_50 + PIXEL31_21 + } + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 42: + case 170: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + PIXEL20_31 + PIXEL30_81 + } + else + { + PIXEL00_50 + PIXEL01_21 + PIXEL10_83 + PIXEL11_70 + PIXEL20_14 + PIXEL30_12 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_61 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 14: + case 142: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_50 + PIXEL01_83 + PIXEL02_13 + PIXEL03_11 + PIXEL10_21 + PIXEL11_70 + } + PIXEL12_32 + PIXEL13_82 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 67: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_61 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 70: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_61 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 28: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 152: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 194: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + PIXEL20_61 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 98: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_61 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 56: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 25: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 26: + case 31: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL11_0 + PIXEL12_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 82: + case 214: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL12_0 + PIXEL20_61 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 88: + case 248: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + break; + } + case 74: + case 107: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_61 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 27: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 86: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL12_0 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 216: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 106: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 30: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_10 + PIXEL11_30 + PIXEL12_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 210: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_61 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 120: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 75: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_61 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 29: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_61 + PIXEL32_61 + PIXEL33_80 + break; + } + case 198: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_61 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + PIXEL20_61 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 184: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_61 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 99: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_61 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_61 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 57: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 71: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_61 + PIXEL21_30 + PIXEL22_30 + PIXEL23_61 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 156: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 226: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_61 + PIXEL11_30 + PIXEL12_30 + PIXEL13_61 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 60: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 195: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_61 + PIXEL20_61 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 102: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_61 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_61 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 153: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 58: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 83: + { + PIXEL00_81 + PIXEL01_31 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_61 + PIXEL21_30 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 92: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 202: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_61 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_31 + PIXEL23_81 + PIXEL32_31 + PIXEL33_81 + break; + } + case 78: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + PIXEL02_32 + PIXEL03_82 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 154: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 114: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL10_61 + PIXEL11_30 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + PIXEL30_82 + PIXEL31_32 + break; + } + case 89: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 90: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 55: + case 23: + { + if (Diff(w[2], w[6])) + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_0 + PIXEL03_0 + PIXEL12_0 + PIXEL13_0 + } + else + { + PIXEL00_12 + PIXEL01_14 + PIXEL02_83 + PIXEL03_50 + PIXEL12_70 + PIXEL13_21 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_30 + PIXEL23_10 + PIXEL30_20 + PIXEL31_60 + PIXEL32_61 + PIXEL33_80 + break; + } + case 182: + case 150: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL12_0 + PIXEL13_0 + PIXEL23_32 + PIXEL33_82 + } + else + { + PIXEL02_21 + PIXEL03_50 + PIXEL12_70 + PIXEL13_83 + PIXEL23_13 + PIXEL33_11 + } + PIXEL10_61 + PIXEL11_30 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + break; + } + case 213: + case 212: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + if (Diff(w[6], w[8])) + { + PIXEL03_81 + PIXEL13_31 + PIXEL22_0 + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL03_12 + PIXEL13_14 + PIXEL22_70 + PIXEL23_83 + PIXEL32_21 + PIXEL33_50 + } + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL20_61 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + break; + } + case 241: + case 240: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_61 + PIXEL03_80 + PIXEL10_60 + PIXEL11_70 + PIXEL12_30 + PIXEL13_10 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_0 + PIXEL23_0 + PIXEL30_82 + PIXEL31_32 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL22_70 + PIXEL23_21 + PIXEL30_11 + PIXEL31_13 + PIXEL32_83 + PIXEL33_50 + } + break; + } + case 236: + case 232: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_60 + PIXEL03_20 + PIXEL10_10 + PIXEL11_30 + PIXEL12_70 + PIXEL13_60 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL21_0 + PIXEL30_0 + PIXEL31_0 + PIXEL32_31 + PIXEL33_81 + } + else + { + PIXEL20_21 + PIXEL21_70 + PIXEL30_50 + PIXEL31_83 + PIXEL32_14 + PIXEL33_12 + } + PIXEL22_31 + PIXEL23_81 + break; + } + case 109: + case 105: + { + if (Diff(w[8], w[4])) + { + PIXEL00_82 + PIXEL10_32 + PIXEL20_0 + PIXEL21_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL00_11 + PIXEL10_13 + PIXEL20_83 + PIXEL21_70 + PIXEL30_50 + PIXEL31_21 + } + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 171: + case 43: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + PIXEL11_0 + PIXEL20_31 + PIXEL30_81 + } + else + { + PIXEL00_50 + PIXEL01_21 + PIXEL10_83 + PIXEL11_70 + PIXEL20_14 + PIXEL30_12 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_61 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 143: + case 15: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL02_32 + PIXEL03_82 + PIXEL10_0 + PIXEL11_0 + } + else + { + PIXEL00_50 + PIXEL01_83 + PIXEL02_13 + PIXEL03_11 + PIXEL10_21 + PIXEL11_70 + } + PIXEL12_32 + PIXEL13_82 + PIXEL20_10 + PIXEL21_30 + PIXEL22_70 + PIXEL23_60 + PIXEL30_80 + PIXEL31_61 + PIXEL32_60 + PIXEL33_20 + break; + } + case 124: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 203: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_61 + PIXEL20_10 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 62: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_10 + PIXEL11_30 + PIXEL12_0 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 211: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_10 + PIXEL20_61 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 118: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL12_0 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_10 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 217: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 110: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_10 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 155: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 188: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 185: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 61: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 157: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 103: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_61 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 227: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_61 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 230: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_61 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 199: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_61 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 220: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + break; + } + case 158: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL12_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 234: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_61 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_31 + PIXEL23_81 + PIXEL32_31 + PIXEL33_81 + break; + } + case 242: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL10_61 + PIXEL11_30 + PIXEL20_82 + PIXEL21_32 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_82 + PIXEL31_32 + break; + } + case 59: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL11_0 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 121: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 87: + { + PIXEL00_81 + PIXEL01_31 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_81 + PIXEL11_31 + PIXEL12_0 + PIXEL20_61 + PIXEL21_30 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 79: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_32 + PIXEL03_82 + PIXEL11_0 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 122: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 94: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL12_0 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 218: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + break; + } + case 91: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL11_0 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 229: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_60 + PIXEL03_20 + PIXEL10_60 + PIXEL11_70 + PIXEL12_70 + PIXEL13_60 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 167: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_60 + PIXEL21_70 + PIXEL22_70 + PIXEL23_60 + PIXEL30_20 + PIXEL31_60 + PIXEL32_60 + PIXEL33_20 + break; + } + case 173: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL10_32 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL20_31 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL30_81 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 181: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + PIXEL03_81 + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL13_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL23_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + PIXEL33_82 + break; + } + case 186: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 115: + { + PIXEL00_81 + PIXEL01_31 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + PIXEL30_82 + PIXEL31_32 + break; + } + case 93: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + break; + } + case 206: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + PIXEL02_32 + PIXEL03_82 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_31 + PIXEL23_81 + PIXEL32_31 + PIXEL33_81 + break; + } + case 205: + case 201: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL10_32 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + if (Diff(w[8], w[4])) + { + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + } + else + { + PIXEL20_12 + PIXEL21_0 + PIXEL30_20 + PIXEL31_11 + } + PIXEL22_31 + PIXEL23_81 + PIXEL32_31 + PIXEL33_81 + break; + } + case 174: + case 46: + { + if (Diff(w[4], w[2])) + { + PIXEL00_80 + PIXEL01_10 + PIXEL10_10 + PIXEL11_30 + } + else + { + PIXEL00_20 + PIXEL01_12 + PIXEL10_11 + PIXEL11_0 + } + PIXEL02_32 + PIXEL03_82 + PIXEL12_32 + PIXEL13_82 + PIXEL20_31 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL30_81 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 179: + case 147: + { + PIXEL00_81 + PIXEL01_31 + if (Diff(w[2], w[6])) + { + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + } + else + { + PIXEL02_11 + PIXEL03_20 + PIXEL12_0 + PIXEL13_12 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL23_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + PIXEL33_82 + break; + } + case 117: + case 116: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + PIXEL03_81 + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL13_31 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + } + else + { + PIXEL22_0 + PIXEL23_11 + PIXEL32_12 + PIXEL33_20 + } + PIXEL30_82 + PIXEL31_32 + break; + } + case 189: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 231: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_32 + PIXEL03_82 + PIXEL10_81 + PIXEL11_31 + PIXEL12_32 + PIXEL13_82 + PIXEL20_82 + PIXEL21_32 + PIXEL22_31 + PIXEL23_81 + PIXEL30_82 + PIXEL31_32 + PIXEL32_31 + PIXEL33_81 + break; + } + case 126: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_10 + PIXEL11_30 + PIXEL12_0 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 219: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_10 + PIXEL20_10 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 125: + { + if (Diff(w[8], w[4])) + { + PIXEL00_82 + PIXEL10_32 + PIXEL20_0 + PIXEL21_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL00_11 + PIXEL10_13 + PIXEL20_83 + PIXEL21_70 + PIXEL30_50 + PIXEL31_21 + } + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 221: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + if (Diff(w[6], w[8])) + { + PIXEL03_81 + PIXEL13_31 + PIXEL22_0 + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL03_12 + PIXEL13_14 + PIXEL22_70 + PIXEL23_83 + PIXEL32_21 + PIXEL33_50 + } + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL20_10 + PIXEL21_30 + PIXEL30_80 + PIXEL31_10 + break; + } + case 207: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL02_32 + PIXEL03_82 + PIXEL10_0 + PIXEL11_0 + } + else + { + PIXEL00_50 + PIXEL01_83 + PIXEL02_13 + PIXEL03_11 + PIXEL10_21 + PIXEL11_70 + } + PIXEL12_32 + PIXEL13_82 + PIXEL20_10 + PIXEL21_30 + PIXEL22_31 + PIXEL23_81 + PIXEL30_80 + PIXEL31_10 + PIXEL32_31 + PIXEL33_81 + break; + } + case 238: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_32 + PIXEL03_82 + PIXEL10_10 + PIXEL11_30 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL21_0 + PIXEL30_0 + PIXEL31_0 + PIXEL32_31 + PIXEL33_81 + } + else + { + PIXEL20_21 + PIXEL21_70 + PIXEL30_50 + PIXEL31_83 + PIXEL32_14 + PIXEL33_12 + } + PIXEL22_31 + PIXEL23_81 + break; + } + case 190: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL12_0 + PIXEL13_0 + PIXEL23_32 + PIXEL33_82 + } + else + { + PIXEL02_21 + PIXEL03_50 + PIXEL12_70 + PIXEL13_83 + PIXEL23_13 + PIXEL33_11 + } + PIXEL10_10 + PIXEL11_30 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + break; + } + case 187: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + PIXEL11_0 + PIXEL20_31 + PIXEL30_81 + } + else + { + PIXEL00_50 + PIXEL01_21 + PIXEL10_83 + PIXEL11_70 + PIXEL20_14 + PIXEL30_12 + } + PIXEL02_10 + PIXEL03_80 + PIXEL12_30 + PIXEL13_10 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 243: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_10 + PIXEL03_80 + PIXEL10_81 + PIXEL11_31 + PIXEL12_30 + PIXEL13_10 + PIXEL20_82 + PIXEL21_32 + if (Diff(w[6], w[8])) + { + PIXEL22_0 + PIXEL23_0 + PIXEL30_82 + PIXEL31_32 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL22_70 + PIXEL23_21 + PIXEL30_11 + PIXEL31_13 + PIXEL32_83 + PIXEL33_50 + } + break; + } + case 119: + { + if (Diff(w[2], w[6])) + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_0 + PIXEL03_0 + PIXEL12_0 + PIXEL13_0 + } + else + { + PIXEL00_12 + PIXEL01_14 + PIXEL02_83 + PIXEL03_50 + PIXEL12_70 + PIXEL13_21 + } + PIXEL10_81 + PIXEL11_31 + PIXEL20_82 + PIXEL21_32 + PIXEL22_30 + PIXEL23_10 + PIXEL30_82 + PIXEL31_32 + PIXEL32_10 + PIXEL33_80 + break; + } + case 237: + case 233: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_60 + PIXEL03_20 + PIXEL10_32 + PIXEL11_32 + PIXEL12_70 + PIXEL13_60 + PIXEL20_0 + PIXEL21_0 + PIXEL22_31 + PIXEL23_81 + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + PIXEL32_31 + PIXEL33_81 + break; + } + case 175: + case 47: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + PIXEL02_32 + PIXEL03_82 + PIXEL10_0 + PIXEL11_0 + PIXEL12_32 + PIXEL13_82 + PIXEL20_31 + PIXEL21_31 + PIXEL22_70 + PIXEL23_60 + PIXEL30_81 + PIXEL31_81 + PIXEL32_60 + PIXEL33_20 + break; + } + case 183: + case 151: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL10_81 + PIXEL11_31 + PIXEL12_0 + PIXEL13_0 + PIXEL20_60 + PIXEL21_70 + PIXEL22_32 + PIXEL23_32 + PIXEL30_20 + PIXEL31_60 + PIXEL32_82 + PIXEL33_82 + break; + } + case 245: + case 244: + { + PIXEL00_20 + PIXEL01_60 + PIXEL02_81 + PIXEL03_81 + PIXEL10_60 + PIXEL11_70 + PIXEL12_31 + PIXEL13_31 + PIXEL20_82 + PIXEL21_32 + PIXEL22_0 + PIXEL23_0 + PIXEL30_82 + PIXEL31_32 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 250: + { + PIXEL00_80 + PIXEL01_10 + PIXEL02_10 + PIXEL03_80 + PIXEL10_10 + PIXEL11_30 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + break; + } + case 123: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_10 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 95: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL11_0 + PIXEL12_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_30 + PIXEL23_10 + PIXEL30_80 + PIXEL31_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 222: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_10 + PIXEL11_30 + PIXEL12_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 252: + { + PIXEL00_80 + PIXEL01_61 + PIXEL02_81 + PIXEL03_81 + PIXEL10_10 + PIXEL11_30 + PIXEL12_31 + PIXEL13_31 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_0 + PIXEL23_0 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 249: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_61 + PIXEL03_80 + PIXEL10_32 + PIXEL11_32 + PIXEL12_30 + PIXEL13_10 + PIXEL20_0 + PIXEL21_0 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + break; + } + case 235: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_61 + PIXEL20_0 + PIXEL21_0 + PIXEL22_31 + PIXEL23_81 + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + PIXEL32_31 + PIXEL33_81 + break; + } + case 111: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + PIXEL02_32 + PIXEL03_82 + PIXEL10_0 + PIXEL11_0 + PIXEL12_32 + PIXEL13_82 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_61 + PIXEL32_10 + PIXEL33_80 + break; + } + case 63: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_0 + PIXEL11_0 + PIXEL12_0 + PIXEL20_31 + PIXEL21_31 + PIXEL22_30 + PIXEL23_10 + PIXEL30_81 + PIXEL31_81 + PIXEL32_61 + PIXEL33_80 + break; + } + case 159: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL11_0 + PIXEL12_0 + PIXEL13_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_32 + PIXEL23_32 + PIXEL30_80 + PIXEL31_61 + PIXEL32_82 + PIXEL33_82 + break; + } + case 215: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL10_81 + PIXEL11_31 + PIXEL12_0 + PIXEL13_0 + PIXEL20_61 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 246: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_61 + PIXEL11_30 + PIXEL12_0 + PIXEL20_82 + PIXEL21_32 + PIXEL22_0 + PIXEL23_0 + PIXEL30_82 + PIXEL31_32 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 254: + { + PIXEL00_80 + PIXEL01_10 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_10 + PIXEL11_30 + PIXEL12_0 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_0 + PIXEL23_0 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 253: + { + PIXEL00_82 + PIXEL01_82 + PIXEL02_81 + PIXEL03_81 + PIXEL10_32 + PIXEL11_32 + PIXEL12_31 + PIXEL13_31 + PIXEL20_0 + PIXEL21_0 + PIXEL22_0 + PIXEL23_0 + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 251: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_10 + PIXEL03_80 + PIXEL11_0 + PIXEL12_30 + PIXEL13_10 + PIXEL20_0 + PIXEL21_0 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + break; + } + case 239: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + PIXEL02_32 + PIXEL03_82 + PIXEL10_0 + PIXEL11_0 + PIXEL12_32 + PIXEL13_82 + PIXEL20_0 + PIXEL21_0 + PIXEL22_31 + PIXEL23_81 + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + PIXEL32_31 + PIXEL33_81 + break; + } + case 127: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + if (Diff(w[2], w[6])) + { + PIXEL02_0 + PIXEL03_0 + PIXEL13_0 + } + else + { + PIXEL02_50 + PIXEL03_50 + PIXEL13_50 + } + PIXEL10_0 + PIXEL11_0 + PIXEL12_0 + if (Diff(w[8], w[4])) + { + PIXEL20_0 + PIXEL30_0 + PIXEL31_0 + } + else + { + PIXEL20_50 + PIXEL30_50 + PIXEL31_50 + } + PIXEL21_0 + PIXEL22_30 + PIXEL23_10 + PIXEL32_10 + PIXEL33_80 + break; + } + case 191: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL10_0 + PIXEL11_0 + PIXEL12_0 + PIXEL13_0 + PIXEL20_31 + PIXEL21_31 + PIXEL22_32 + PIXEL23_32 + PIXEL30_81 + PIXEL31_81 + PIXEL32_82 + PIXEL33_82 + break; + } + case 223: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + PIXEL01_0 + PIXEL10_0 + } + else + { + PIXEL00_50 + PIXEL01_50 + PIXEL10_50 + } + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL11_0 + PIXEL12_0 + PIXEL13_0 + PIXEL20_10 + PIXEL21_30 + PIXEL22_0 + if (Diff(w[6], w[8])) + { + PIXEL23_0 + PIXEL32_0 + PIXEL33_0 + } + else + { + PIXEL23_50 + PIXEL32_50 + PIXEL33_50 + } + PIXEL30_80 + PIXEL31_10 + break; + } + case 247: + { + PIXEL00_81 + PIXEL01_31 + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL10_81 + PIXEL11_31 + PIXEL12_0 + PIXEL13_0 + PIXEL20_82 + PIXEL21_32 + PIXEL22_0 + PIXEL23_0 + PIXEL30_82 + PIXEL31_32 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + case 255: + { + if (Diff(w[4], w[2])) + { + PIXEL00_0 + } + else + { + PIXEL00_20 + } + PIXEL01_0 + PIXEL02_0 + if (Diff(w[2], w[6])) + { + PIXEL03_0 + } + else + { + PIXEL03_20 + } + PIXEL10_0 + PIXEL11_0 + PIXEL12_0 + PIXEL13_0 + PIXEL20_0 + PIXEL21_0 + PIXEL22_0 + PIXEL23_0 + if (Diff(w[8], w[4])) + { + PIXEL30_0 + } + else + { + PIXEL30_20 + } + PIXEL31_0 + PIXEL32_0 + if (Diff(w[6], w[8])) + { + PIXEL33_0 + } + else + { + PIXEL33_20 + } + break; + } + } + pIn++; // next source pixel (just increment since it's an int*) + pOut += 16; // skip 4 pixels (4 bytes * 4 pixels) + } + pOut += BpL; // skip next 3 rows + pOut += BpL; + pOut += BpL; + } + hq_vec::reset(); +} + +void DLL InitLUTs() +{ + int i, j, k, r, g, b, Y, u, v; + +#if 0 // colorOutlines() after hqresize + for (i=0; i<65536; i++) + LUT16to32[i] = 0x00404040; + for (i=0; i<65536; i++) + LUT16to32[i+65536] = 0xFF000000 + ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3); +#else // colorOutlines() before hqresize + for (i=0; i<65536; i++) + LUT16to32[i] = ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3); + for (i=0; i<65536; i++) + LUT16to32[i+65536] = 0xFF000000 + LUT16to32[i]; +#endif + + for (i=0; i<65536; i++) + RGBtoYUV[i] = 0xFF000000; + + for (i=0; i<32; i++) + for (j=0; j<64; j++) + for (k=0; k<32; k++) + { + r = i << 3; + g = j << 2; + b = k << 3; + Y = (r + g + b) >> 2; + u = 128 + ((r - b) >> 2); + v = 128 + ((-r + 2*g -b)>>3); + RGBtoYUV[ 65536 + (i << 11) + (j << 5) + k ] = (Y<<16) + (u<<8) + v; + } +} + +/* +int DLL hq4x_32 ( CImage &ImageIn, CImage &ImageOut ) +{ + if ( ImageIn.Convert32To17() != 0 ) + { + printf( "ERROR: conversion to 17 bit failed\n" ); + return 1; + } + + if ( ImageOut.Init( ImageIn.m_Xres*4, ImageIn.m_Yres*4, 32 ) != 0 ) + { + printf( "ERROR: ImageOut.Init()\n" ); + return 1; + }; + + InitLUTs(); + hq4x_32( (int*)ImageIn.m_pBitmap, ImageOut.m_pBitmap, ImageIn.m_Xres, ImageIn.m_Yres, ImageOut.m_Xres*4 ); + + printf( "\nOK\n" ); + return 0; +} +*/ + +} \ No newline at end of file diff --git a/src/gl/hqnx_asm/hqnx_asm.h b/src/gl/hqnx_asm/hqnx_asm.h new file mode 100644 index 000000000..9ced349fa --- /dev/null +++ b/src/gl/hqnx_asm/hqnx_asm.h @@ -0,0 +1,234 @@ +//hqnx filter library +//---------------------------------------------------------- +//Copyright (C) 2003 MaxSt ( maxst@hiend3d.com ) +//Copyright (C) 2009 Benjamin Berkels +//Copyright (C) 2012-2014 Alexey Lysiuk +// +//This program is free software; you can redistribute it and/or +//modify it under the terms of the GNU Lesser General Public +//License as published by the Free Software Foundation; either +//version 2.1 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 +//Lesser General Public License for more details. +// +//You should have received a copy of the GNU Lesser General Public +//License along with this program; if not, write to the Free Software +//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +#ifndef __HQNX_H__ +#define __HQNX_H__ + +#ifdef _MSC_VER +#pragma warning(disable:4799) +#endif // _MSC_VER + +#include "hqnx_asm_Image.h" + +// IMPORTANT NOTE! +// The following is not a generic vectorized math class +// Each member function or overloaded operator does specific task to simplify client code +// To re-implement this class for different platform you need check very carefully +// the Intel C++ Intrinsic Reference at http://software.intel.com/file/18072/ + +#if defined _MSC_VER && defined _M_X64 + +// Implementation via SSE2 intrinsics +// MSVC doesn't support MMX intrinsics on x64 + +#include + +class hq_vec +{ +public: + hq_vec(const int value) + : m_value(_mm_cvtsi32_si128(value)) + { + } + + static hq_vec load(const int source) + { + return _mm_unpacklo_epi8(_mm_cvtsi32_si128(source), _mm_cvtsi32_si128(0)); + } + + static hq_vec expand(const short source) + { + return _mm_set_epi16(source, source, source, source, source, source, source, source); + } + + void store(unsigned char* const destination) const + { + *reinterpret_cast(destination) = _mm_cvtsi128_si32(_mm_packus_epi16(m_value, _mm_cvtsi32_si128(0))); + } + + static void reset() + { + } + + hq_vec& operator+=(const hq_vec& right) + { + m_value = _mm_add_epi16(m_value, right.m_value); + return *this; + } + + hq_vec& operator*=(const hq_vec& right) + { + m_value = _mm_mullo_epi16(m_value, right.m_value); + return *this; + } + + hq_vec& operator<<(const int count) + { + m_value = _mm_sll_epi16(m_value, _mm_cvtsi32_si128(count)); + return *this; + } + + hq_vec& operator>>(const int count) + { + m_value = _mm_srl_epi16(m_value, _mm_cvtsi32_si128(count)); + return *this; + } + +private: + __m128i m_value; + + hq_vec(const __m128i value) + : m_value(value) + { + } + + friend hq_vec operator- (const hq_vec&, const hq_vec&); + friend hq_vec operator* (const hq_vec&, const hq_vec&); + friend hq_vec operator| (const hq_vec&, const hq_vec&); + friend bool operator!=(const int, const hq_vec&); +}; + +inline hq_vec operator-(const hq_vec& left, const hq_vec& right) +{ + return _mm_subs_epu8(left.m_value, right.m_value); +} + +inline hq_vec operator*(const hq_vec& left, const hq_vec& right) +{ + return _mm_mullo_epi16(left.m_value, right.m_value); +} + +inline hq_vec operator|(const hq_vec& left, const hq_vec& right) +{ + return _mm_or_si128(left.m_value, right.m_value); +} + +inline bool operator!=(const int left, const hq_vec& right) +{ + return left != _mm_cvtsi128_si32(right.m_value); +} + +#else // _M_X64 + +// Implementation via MMX intrinsics + +#include + +class hq_vec +{ +public: + hq_vec(const int value) + : m_value(_mm_cvtsi32_si64(value)) + { + } + + static hq_vec load(const int source) + { + return _mm_unpacklo_pi8(_mm_cvtsi32_si64(source), _mm_cvtsi32_si64(0)); + } + + static hq_vec expand(const short source) + { + return _mm_set_pi16(source, source, source, source); + } + + void store(unsigned char* const destination) const + { + *reinterpret_cast(destination) = _mm_cvtsi64_si32(_mm_packs_pu16(m_value, _mm_cvtsi32_si64(0))); + } + + static void reset() + { + _mm_empty(); + } + + hq_vec& operator+=(const hq_vec& right) + { + m_value = _mm_add_pi16(m_value, right.m_value); + return *this; + } + + hq_vec& operator*=(const hq_vec& right) + { + m_value = _mm_mullo_pi16(m_value, right.m_value); + return *this; + } + + hq_vec& operator<<(const int count) + { + m_value = _mm_sll_pi16(m_value, _mm_cvtsi32_si64(count)); + return *this; + } + + hq_vec& operator>>(const int count) + { + m_value = _mm_srl_pi16(m_value, _mm_cvtsi32_si64(count)); + return *this; + } + +private: + __m64 m_value; + + hq_vec(const __m64 value) + : m_value(value) + { + } + + friend hq_vec operator- (const hq_vec&, const hq_vec&); + friend hq_vec operator* (const hq_vec&, const hq_vec&); + friend hq_vec operator| (const hq_vec&, const hq_vec&); + friend bool operator!=(const int, const hq_vec&); +}; + +inline hq_vec operator-(const hq_vec& left, const hq_vec& right) +{ + return _mm_subs_pu8(left.m_value, right.m_value); +} + +inline hq_vec operator*(const hq_vec& left, const hq_vec& right) +{ + return _mm_mullo_pi16(left.m_value, right.m_value); +} + +inline hq_vec operator|(const hq_vec& left, const hq_vec& right) +{ + return _mm_or_si64(left.m_value, right.m_value); +} + +inline bool operator!=(const int left, const hq_vec& right) +{ + return left != _mm_cvtsi64_si32(right.m_value); +} + +#endif // _MSC_VER && _M_X64 + +namespace HQnX_asm +{ +void DLL hq2x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ); +void DLL hq3x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ); +void DLL hq4x_32( int * pIn, unsigned char * pOut, int Xres, int Yres, int BpL ); +int DLL hq4x_32 ( CImage &ImageIn, CImage &ImageOut ); + +void DLL InitLUTs(); + +} + + +#endif //__HQNX_H__ \ No newline at end of file diff --git a/src/gl/hqnx_asm/hqnx_asm_Image.cpp b/src/gl/hqnx_asm/hqnx_asm_Image.cpp new file mode 100644 index 000000000..7af120173 --- /dev/null +++ b/src/gl/hqnx_asm/hqnx_asm_Image.cpp @@ -0,0 +1,1183 @@ +//CImage class - loading and saving BMP and TGA files +//---------------------------------------------------------- +//Copyright (C) 2003 MaxSt ( maxst@hiend3d.com ) +// +//This program is free software; you can redistribute it and/or +//modify it under the terms of the GNU Lesser General Public +//License as published by the Free Software Foundation; either +//version 2.1 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 +//Lesser General Public License for more details. +// +//You should have received a copy of the GNU Lesser General Public +//License along with this program; if not, write to the Free Software +//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +#include +#include +#include "hqnx_asm_Image.h" + +#ifndef _MSC_VER +#define _stricmp strcasecmp +#endif + +namespace HQnX_asm +{ + +DLL CImage::CImage() +{ + m_Xres = m_Yres = m_NumPixel = 0; + m_pBitmap = NULL; +} + +DLL CImage::~CImage() +{ + Destroy(); +} + +int DLL CImage::Init( int X, int Y, unsigned short BitPerPixel ) +{ + if (m_pBitmap != NULL) + free(m_pBitmap); + + m_Xres = X; + m_Yres = Y; + m_BitPerPixel = BitPerPixel<=8 ? 8 : BitPerPixel<=16 ? 16 : BitPerPixel<=24 ? 24 : 32; + m_BytePerPixel = m_BitPerPixel >> 3; + m_NumPixel = m_Xres*m_Yres; + int size = m_NumPixel*((m_BitPerPixel+7)/8); + m_pBitmap=(unsigned char *)malloc(size); + return (m_pBitmap != NULL) ? 0 : 1; +} + +int DLL CImage::SetImage(unsigned char *img, int width, int height, int bpp) +{ + Init(width, height, bpp); + + memcpy(m_pBitmap, img, m_NumPixel * m_BytePerPixel); + + return 0; +} + +int DLL CImage::Destroy() +{ + if (m_pBitmap) + { + free(m_pBitmap); + m_pBitmap = NULL; + } + m_Xres = 0; + m_Yres = 0; + m_NumPixel = 0; + m_BitPerPixel = 0; + return 0; +} + +int DLL CImage::Convert32To17( void ) +{ + int nRes = eConvUnknownFormat; + + if ( m_BitPerPixel == 32 ) + { + if ( m_pBitmap != NULL ) + { + unsigned char * pTemp8 = m_pBitmap; + unsigned int * pTemp32 = (unsigned int *)m_pBitmap; + unsigned int a, r, g, b; + for ( int i=0; i> 3; + g = (*(pTemp8++)) >> 2; + r = (*(pTemp8++)) >> 3; + a = *(pTemp8++); + *pTemp32 = (r << 11) + (g << 5) + b + (a > 127 ? 0x10000 : 0); + pTemp32++; + } + } + else + nRes = eConvSourceMemory; + + nRes = 0; + } + + return nRes; +} + +int DLL CImage::ConvertTo32( void ) +{ + int nRes = eConvUnknownFormat; + + if ( m_pBitmap == NULL ) + return eConvSourceMemory; + + switch ( m_BitPerPixel ) + { + case 8: + { + nRes = 0; + m_BitPerPixel = 32; + unsigned char * pNewBitmap = (unsigned char *)malloc(m_NumPixel*4); + if ( pNewBitmap != NULL ) + { + unsigned char * pTemp8 = m_pBitmap; + unsigned char * pTemp32 = pNewBitmap; + unsigned char c; + for ( int i=0; i> 3); + *(pTemp24++) = ((rgb & 0xF800) >> 8); + } + free(m_pBitmap); + m_pBitmap = pNewBitmap; + } + else + nRes = eConvDestMemory; + + break; + } + case 32: + { + nRes = 0; + m_BitPerPixel = 24; + unsigned char * pNewBitmap = (unsigned char *)malloc(m_NumPixel*3); + if ( pNewBitmap != NULL ) + { + unsigned char * pTemp32 = m_pBitmap; + unsigned char * pTemp24 = pNewBitmap; + for ( int i=0; i> 3; + g = m_Pal[c].g >> 2; + b = m_Pal[c].b >> 3; + *(pTemp16++) = (r << 11) + (g << 5) + b; + } + free(m_pBitmap); + m_pBitmap = pNewBitmap; + } + else + nRes = eConvDestMemory; + + break; + } + case 24: + { + nRes = 0; + m_BitPerPixel = 16; + unsigned char * pNewBitmap = (unsigned char *)malloc(m_NumPixel*2); + if ( pNewBitmap != NULL ) + { + unsigned char * pTemp24 = m_pBitmap; + unsigned short * pTemp16 = (unsigned short *)pNewBitmap; + unsigned short r, g, b; + for ( int i=0; i> 3; + g = (*(pTemp24++)) >> 2; + r = (*(pTemp24++)) >> 3; + *(pTemp16++) = (r << 11) + (g << 5) + b; + } + free(m_pBitmap); + m_pBitmap = pNewBitmap; + } + else + nRes = eConvDestMemory; + + break; + } + case 32: + { + nRes = 0; + m_BitPerPixel = 16; + unsigned char * pNewBitmap = (unsigned char *)malloc(m_NumPixel*2); + if ( pNewBitmap != NULL ) + { + unsigned char * pTemp32 = m_pBitmap; + unsigned short * pTemp16 = (unsigned short *)pNewBitmap; + unsigned short r, g, b; + for ( int i=0; i> 3; + g = (*(pTemp32++)) >> 2; + r = (*(pTemp32++)) >> 3; + pTemp32++; + *(pTemp16++) = (r << 11) + (g << 5) + b; + } + free(m_pBitmap); + m_pBitmap = pNewBitmap; + } + else + nRes = eConvDestMemory; + + break; + } + } + + return nRes; +} + +int CImage::Convert8To17( int transindex ) +{ + int nRes = eConvUnknownFormat; + + if ( m_BitPerPixel == 8 ) + { + m_BitPerPixel = 32; + unsigned char * pNewBitmap = (unsigned char *)malloc(m_NumPixel*4); + if ( pNewBitmap != NULL ) + { + unsigned char * pTemp8 = m_pBitmap; + unsigned int * pTemp32 = (unsigned int *)pNewBitmap; + unsigned int r, g, b; + unsigned char c; + for ( int i=0; i> 3; + g = m_Pal[c].g >> 2; + b = m_Pal[c].b >> 3; + *(pTemp32++) = (r << 11) + (g << 5) + b + (transindex != c ? 0x10000 : 0); + } + free(m_pBitmap); + m_pBitmap = pNewBitmap; + } + else + nRes = eConvDestMemory; + + nRes = 0; + } + + return nRes; +} + +int CImage::SaveBmp(char *szFilename) +{ + _BMPFILEHEADER fh; + _BMPIMAGEHEADER ih; + unsigned char BmpPal[256][4]; + long int SuffLen; + long int Dummy = 0; + unsigned char * pBuf; + short i; + + if (!(f = fopen(szFilename, "wb"))) return eSaveBmpFileOpen; + if ( m_pBitmap == NULL ) return eSaveBmpSourceMemory; + + fh.bfType=0x4D42; + if (m_BitPerPixel==8) + { + SuffLen=((m_Xres+3)/4)*4-m_Xres; + ih.biSize=0x28; + ih.biWidth=m_Xres; + ih.biHeight=m_Yres; + ih.biPlanes=1; + ih.biBitCount=8; + ih.biCompression=0; + ih.biSizeImage=(m_Xres+SuffLen)*m_Yres; + ih.biXPelsPerMeter=ih.biYPelsPerMeter=0x2E23; // 300dpi (pixels per meter) + ih.biClrUsed=ih.biClrImportant=0; + fh.bfSize=(ih.biSizeImage)+0x0436; + fh.bfRes1=0; + fh.bfOffBits=0x0436; + if (fwrite(&fh, 14, 1, f) != 1) return eSaveBmpFileWrite; + if (fwrite(&ih, 40, 1, f) != 1) return eSaveBmpFileWrite; + for (i=0; i<256; i++) + { + BmpPal[i][0]=m_Pal[i].b; + BmpPal[i][1]=m_Pal[i].g; + BmpPal[i][2]=m_Pal[i].r; + BmpPal[i][3]=0; + } + if (fwrite(&BmpPal, 1024, 1, f) != 1) return eSaveBmpFileWrite; + pBuf=m_pBitmap; + pBuf+=m_NumPixel; + for (i=0; i0) + { + if (fwrite(&Dummy, SuffLen, 1, f) != 1) return eSaveBmpFileWrite; + } + } + } + else + if (m_BitPerPixel==24) + { + SuffLen=((m_Xres*3+3)/4)*4-m_Xres*3; + ih.biSize=0x28; + ih.biWidth=m_Xres; + ih.biHeight=m_Yres; + ih.biPlanes=1; + ih.biBitCount=24; + ih.biCompression=0; + ih.biSizeImage=(m_Xres*3+SuffLen)*m_Yres; + ih.biXPelsPerMeter=ih.biYPelsPerMeter=0x2E23; // 300dpi (pixels per meter) + ih.biClrUsed=ih.biClrImportant=0; + fh.bfSize=(ih.biSizeImage)+0x0036; + fh.bfRes1=0; + fh.bfOffBits=0x0036; + if (fwrite(&fh, 14, 1, f) != 1) return eSaveBmpFileWrite; + if (fwrite(&ih, 40, 1, f) != 1) return eSaveBmpFileWrite; + pBuf=m_pBitmap; + pBuf+=m_NumPixel*3; + for (i=0; i0) + { + if (fwrite(&Dummy, SuffLen, 1, f) != 1) return eSaveBmpFileWrite; + } + } + } + else + return eSaveBmpColorDepth; + + fclose(f); + + return 0; +} + +int CImage::LoadBmp(char *szFilename) +{ + _BMPFILEHEADER fh; + _BMPIMAGEHEADEROLD ih_old; + _BMPIMAGEHEADER ih; + unsigned char BmpPal[256][4]; + long int biSize; + long int SuffLen; + long int Dummy = 0; + unsigned char * pBuf; + short i; + long int xres, yres; + unsigned short bits; + + if (!(f = fopen(szFilename, "rb"))) return eLoadBmpFileOpen; + if (fread(&fh, 14, 1, f) != 1) return eLoadBmpFileRead; + if (fh.bfType != 0x4D42) return eLoadBmpBadFormat; + if (fread(&biSize, 4, 1, f) != 1) return eLoadBmpFileRead; + if (biSize > 12) + { + fseek( f, -4, SEEK_CUR ); + if (fread(&ih, biSize, 1, f) != 1) return eLoadBmpFileRead; + xres = ih.biWidth; + yres = ih.biHeight; + bits = ih.biBitCount; + } + else + { + fseek( f, -4, SEEK_CUR ); + if (fread(&ih_old, biSize, 1, f) != 1) return eLoadBmpFileRead; + xres = ih_old.biWidth; + yres = ih_old.biHeight; + bits = ih_old.biBitCount; + } + + if ( Init( xres, yres, bits ) != 0 ) return eLoadBmpInit; + if (m_BitPerPixel==8) + { + SuffLen=((m_Xres+3)/4)*4-m_Xres; + if (fread(&BmpPal, 1024, 1, f) != 1) return eLoadBmpFileRead; + for (i=0; i<256; i++) + { + m_Pal[i].b=BmpPal[i][0]; + m_Pal[i].g=BmpPal[i][1]; + m_Pal[i].r=BmpPal[i][2]; + } + pBuf=m_pBitmap; + pBuf+=m_NumPixel; + for (i=0; i0) + { + if (fread(&Dummy, SuffLen, 1, f) != 1) return eLoadBmpFileRead; + } + } + } + else + if (m_BitPerPixel==24) + { + SuffLen=((m_Xres*3+3)/4)*4-(m_Xres*3); + pBuf=m_pBitmap; + pBuf+=m_NumPixel*3; + for (i=0; i0) + { + if (fread(&Dummy, SuffLen, 1, f) != 1) return eLoadBmpFileRead; + } + } + } + else + return eLoadBmpColorDepth; + + fclose(f); + + return 0; +} + +void CImage::Output( void ) +{ + fwrite(m_cBuf, m_nCount, 1, f); + m_nCount=0; +} + +void CImage::Output( char c ) +{ + if ( m_nCount == sizeof(m_cBuf) ) + { + fwrite(m_cBuf, m_nCount, 1, f); + m_nCount=0; + } + m_cBuf[m_nCount++] = c; +} + +void CImage::Output( char * pcData, int nSize ) +{ + for ( int i=0; i 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+i-nDif-nRep), nDif ); + } + nDif = 1; + } + } + else + { + if ( bEqual && (nRep<127) ) + nRep++; + else + { + Output( nRep+128 ); + Output( (char*)&colOld, 1 ); + nRep = 0; + nDif = 1; + } + } + } + + if ( nRep == 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+m_Xres-nDif), nDif ); + } + else + { + Output( nRep+128 ); + Output( (char*)&colOld, 1 ); + } + Output(); + } + } + } + else + if (m_BitPerPixel==24) + { + fh.tiImageType = bCompressed ? 10 : 2; + if (fwrite(&fh, sizeof(fh), 1, f) != 1) return eSaveTgaFileWrite; + + _BGR * pcolBuf = (_BGR *)m_pBitmap; + pcolBuf += m_NumPixel; + + if ( !bCompressed ) + { + for (j=0; j 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+i-nDif-nRep), sizeof(_BGR)*nDif ); + } + nDif = 1; + } + } + else + { + if ( bEqual && (nRep<127) ) + nRep++; + else + { + Output( nRep+128 ); + Output( (char*)&colOld, sizeof(_BGR) ); + nRep = 0; + nDif = 1; + } + } + } + + if ( nRep == 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+m_Xres-nDif), sizeof(_BGR)*nDif ); + } + else + { + Output( nRep+128 ); + Output( (char*)&colOld, sizeof(_BGR) ); + } + Output(); + } + } + } + else + if (m_BitPerPixel==32) + { + fh.tiImageType = bCompressed ? 10 : 2; + fh.tiAttrBits = 8; + if (fwrite(&fh, sizeof(fh), 1, f) != 1) return eSaveTgaFileWrite; + + _BGRA * pcolBuf = (_BGRA *)m_pBitmap; + pcolBuf += m_NumPixel; + + if ( !bCompressed ) + { + for (j=0; j 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+i-nDif-nRep), sizeof(_BGRA)*nDif ); + } + nDif = 1; + } + } + else + { + if ( bEqual && (nRep<127) ) + nRep++; + else + { + Output( nRep+128 ); + Output( (char*)&colOld, sizeof(_BGRA) ); + nRep = 0; + nDif = 1; + } + } + } + + if ( nRep == 0 ) + { + Output( nDif-1 ); + Output( (char*)(pcolBuf+m_Xres-nDif), sizeof(_BGRA)*nDif ); + } + else + { + Output( nRep+128 ); + Output( (char*)&colOld, sizeof(_BGRA) ); + } + Output(); + } + } + } + else + return eSaveTgaColorDepth; + + fclose(f); + + return 0; +} + +int CImage::LoadTga(char *szFilename) +{ + _TGAHEADER fh; + int i, j, k; + unsigned char nCount; + + if (!(f = fopen(szFilename, "rb"))) return eLoadTgaFileOpen; + if (fread(&fh, sizeof(fh), 1, f) != 1) return eLoadTgaFileRead; + bool bCompressed = (( fh.tiImageType & 8 ) != 0); + if ((fh.tiBitPerPixel<=0) || (fh.tiBitPerPixel>32)) + return eLoadTgaBadFormat; + + if ( Init( fh.tiXres, fh.tiYres, fh.tiBitPerPixel ) != 0 ) + return eLoadTgaInit; + + if ( m_BitPerPixel == 8 ) + { + if ( fh.tiPaletteIncluded == 1 ) + { + if ( fh.tiPaletteBpp == 24) + { + if (fread(&m_Pal, 3, fh.tiPaletteSize, f) != fh.tiPaletteSize) + return eLoadTgaFileRead; + } + else + if ( fh.tiPaletteBpp == 32) + { + unsigned char BmpPal[256][4]; + + if (fread(&BmpPal, 4, fh.tiPaletteSize, f) != fh.tiPaletteSize) + return eLoadTgaFileRead; + + for (i=0; i= m_pBitmap ) + { + nCount = Input(); + if ((nCount & 128)==0) + { + for (k=0; k<=nCount; k++) + { + colCur = Input(); + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + else + { + colCur = Input(); + for (k=0; k<=nCount-128; k++) + { + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + } + } + } + else + if ( m_BitPerPixel == 24 ) + { + _BGR * pcolBuf = (_BGR *)m_pBitmap; + pcolBuf += m_NumPixel; + + if ( !bCompressed ) + { + for (j=0; j= (_BGR *)m_pBitmap ) + { + nCount = Input(); + if ((nCount & 128)==0) + { + for (k=0; k<=nCount; k++) + { + colCur.b = Input(); + colCur.g = Input(); + colCur.r = Input(); + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + else + { + colCur.b = Input(); + colCur.g = Input(); + colCur.r = Input(); + for (k=0; k<=nCount-128; k++) + { + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + } + } + } + else + if ( m_BitPerPixel == 32 ) + { + _BGRA * pcolBuf = (_BGRA *)m_pBitmap; + pcolBuf += m_NumPixel; + + if ( !bCompressed ) + { + for (j=0; j= (_BGRA *)m_pBitmap ) + { + nCount = Input(); + if ((nCount & 128)==0) + { + for (k=0; k<=nCount; k++) + { + colCur.b = Input(); + colCur.g = Input(); + colCur.r = Input(); + colCur.a = Input(); + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + else + { + colCur.b = Input(); + colCur.g = Input(); + colCur.r = Input(); + colCur.a = Input(); + for (k=0; k<=nCount-128; k++) + { + *(pcolBuf+i) = colCur; + if ( (++i) == m_Xres ) + { + i=0; + pcolBuf -= m_Xres; + break; + } + } + } + } + } + } + else + return eLoadTgaColorDepth; + + fclose(f); + + return 0; +} + +int DLL CImage::Load(char *szFilename) +{ + int nRes = 0; + + if ( szFilename != NULL ) + { + char * szExt = strrchr( szFilename, '.' ); + int nNotTGA = 1; + + if ( szExt != NULL ) + nNotTGA = _stricmp( szExt, ".tga" ); + + if ( nNotTGA != 0 ) + nRes = LoadBmp( szFilename ); + else + nRes = LoadTga( szFilename ); + } + else + nRes = eLoadFilename; + + return nRes; +} + +int DLL CImage::Save(char *szFilename) +{ + int nRes = 0; + int nNotTGA = 1; + + if ( szFilename != NULL ) + { + char * szExt = strrchr( szFilename, '.' ); + + if ( szExt != NULL ) + nNotTGA = _stricmp( szExt, ".tga" ); + + if ( nNotTGA != 0 ) + { + if (( m_BitPerPixel == 16 ) || ( m_BitPerPixel == 32 )) + nRes = ConvertTo24(); + + if (nRes == 0) + nRes = SaveBmp( szFilename ); + } + else + { + if ( m_BitPerPixel == 16 ) + nRes = ConvertTo24(); + + if (nRes == 0) + nRes = SaveTga( szFilename, true ); + } + } + else + nRes = eSaveFilename; + + return nRes; +} + +} \ No newline at end of file diff --git a/src/gl/hqnx_asm/hqnx_asm_Image.h b/src/gl/hqnx_asm/hqnx_asm_Image.h new file mode 100644 index 000000000..38f0f1d6a --- /dev/null +++ b/src/gl/hqnx_asm/hqnx_asm_Image.h @@ -0,0 +1,152 @@ +//CImage class - loading and saving BMP and TGA files +//---------------------------------------------------------- +//Copyright (C) 2003 MaxSt ( maxst@hiend3d.com ) +// +//This program is free software; you can redistribute it and/or +//modify it under the terms of the GNU Lesser General Public +//License as published by the Free Software Foundation; either +//version 2.1 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 +//Lesser General Public License for more details. +// +//You should have received a copy of the GNU Lesser General Public +//License along with this program; if not, write to the Free Software +//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +//#ifdef WIN32 +//#define DLL __declspec(dllexport) +//#else +#define DLL +//#endif + +#include +#pragma once +#ifdef _MSC_VER +#pragma warning(disable: 4103) +#endif // _MSC_VER +#pragma pack(1) + +namespace HQnX_asm +{ + +typedef struct { unsigned char b, g, r; } _BGR; +typedef struct { unsigned char b, g, r, a; } _BGRA; + +class CImage +{ + public: + DLL CImage(); + DLL ~CImage(); + + enum CImageErrors + { + eConvUnknownFormat = 10, + eConvSourceMemory = 11, + eConvDestMemory = 12, + + eSaveBmpFileOpen = 20, + eSaveBmpFileWrite = 21, + eSaveBmpSourceMemory = 22, + eSaveBmpColorDepth = 23, + + eLoadBmpFileOpen = 30, + eLoadBmpFileRead = 31, + eLoadBmpBadFormat = 32, + eLoadBmpInit = 33, + eLoadBmpColorDepth = 34, + + eSaveTgaFileOpen = 40, + eSaveTgaFileWrite = 41, + eSaveTgaSourceMemory = 42, + eSaveTgaColorDepth = 43, + + eLoadTgaFileOpen = 50, + eLoadTgaFileRead = 51, + eLoadTgaBadFormat = 52, + eLoadTgaInit = 53, + eLoadTgaColorDepth = 54, + + eLoadFilename = 60, + eSaveFilename = 61, + }; + + struct _BMPFILEHEADER + { + unsigned short bfType; + long int bfSize, bfRes1, bfOffBits; + }; + + struct _BMPIMAGEHEADEROLD + { + long int biSize; + unsigned short biWidth, biHeight; + unsigned short biPlanes, biBitCount; + }; + + struct _BMPIMAGEHEADER + { + long int biSize, biWidth, biHeight; + unsigned short biPlanes, biBitCount; + long int biCompression, biSizeImage; + long int biXPelsPerMeter, biYPelsPerMeter; + long int biClrUsed, biClrImportant; + }; + + struct _TGAHEADER + { + unsigned char tiIdentSize; + unsigned char tiPaletteIncluded; + unsigned char tiImageType; + unsigned short tiPaletteStart; + unsigned short tiPaletteSize; + unsigned char tiPaletteBpp; + unsigned short tiX0; + unsigned short tiY0; + unsigned short tiXres; + unsigned short tiYres; + unsigned char tiBitPerPixel; + unsigned char tiAttrBits; + }; + + public: + int DLL Init( int Xres, int Yres, unsigned short BitPerPixel ); + int DLL SetImage(unsigned char *img, int width, int height, int bpp); + int DLL Destroy(); + int DLL ConvertTo32( void ); + int DLL ConvertTo24( void ); + int DLL ConvertTo16( void ); + int DLL Convert8To17( int transindex ); + int DLL Convert32To17( void ); + int SaveBmp(char *szFilename); + int LoadBmp(char *szFilename); + int SaveTga(char *szFilename, bool bCompressed ); + int LoadTga(char *szFilename); + int DLL Load(char *szFilename); + int DLL Save(char *szFilename); + + private: + void Output( char * pcData, int nSize ); + void Output( char c ); + void Output( void ); + unsigned char Input( void ); + + public: + int m_Xres, m_Yres; + unsigned short m_BitPerPixel; + unsigned short m_BytePerPixel; + unsigned char * m_pBitmap; + _BGR m_Pal[256]; + + private: + int m_NumPixel; + FILE * f; + int m_nCount; + char m_cBuf[32768]; +}; + +#pragma pack() + +} \ No newline at end of file diff --git a/src/gl/models/gl_models.cpp b/src/gl/models/gl_models.cpp new file mode 100644 index 000000000..f3dfbd569 --- /dev/null +++ b/src/gl/models/gl_models.cpp @@ -0,0 +1,1131 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_models.cpp +** +** General model handling code +** +**/ + +#include "gl/system/gl_system.h" +#include "w_wad.h" +#include "cmdlib.h" +#include "sc_man.h" +#include "m_crc32.h" +#include "c_console.h" +#include "g_game.h" +#include "doomstat.h" +#include "g_level.h" +#include "r_state.h" +#include "d_player.h" +//#include "resources/voxels.h" +//#include "gl/gl_intern.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/models/gl_models.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_geometric.h" +#include "gl/utility/gl_convert.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/shaders/gl_shader.h" + +static inline float GetTimeFloat() +{ + return (float)I_MSTime() * (float)TICRATE / 1000.0f; +} + +CVAR(Bool, gl_interpolate_model_frames, true, CVAR_ARCHIVE) +CVAR(Bool, gl_light_models, true, CVAR_ARCHIVE) +EXTERN_CVAR(Int, gl_fogmode) + +extern TDeletingArray Voxels; +extern TDeletingArray VoxelDefs; + +DeletingModelArray Models; + + +void gl_LoadModels() +{ + /* + for (int i = Models.Size() - 1; i >= 0; i--) + { + Models[i]->BuildVertexBuffer(); + } + */ +} + +void gl_FlushModels() +{ + for (int i = Models.Size() - 1; i >= 0; i--) + { + Models[i]->DestroyVertexBuffer(); + } +} + +//=========================================================================== +// +// Uses a hardware buffer if either single frame (i.e. no interpolation needed) +// or shading is available (interpolation is done by the vertex shader) +// +// If interpolation has to be done on the CPU side this will fall back +// to CPU-side arrays. +// +//=========================================================================== + +FModelVertexBuffer::FModelVertexBuffer(bool needindex, bool singleframe) + : FVertexBuffer(singleframe || !gl.legacyMode) +{ + vbo_ptr = nullptr; + ibo_id = 0; + if (needindex) + { + glGenBuffers(1, &ibo_id); // The index buffer can always be a real buffer. + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FModelVertexBuffer::BindVBO() +{ + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_id); + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + if (!gl.legacyMode) + { + glEnableVertexAttribArray(VATTR_VERTEX); + glEnableVertexAttribArray(VATTR_TEXCOORD); + glEnableVertexAttribArray(VATTR_VERTEX2); + glEnableVertexAttribArray(VATTR_NORMAL); + glDisableVertexAttribArray(VATTR_COLOR); + } + else + { + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FModelVertexBuffer::~FModelVertexBuffer() +{ + if (ibo_id != 0) + { + glDeleteBuffers(1, &ibo_id); + } + if (vbo_ptr != nullptr) + { + delete[] vbo_ptr; + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FModelVertex *FModelVertexBuffer::LockVertexBuffer(unsigned int size) +{ + if (vbo_id > 0) + { + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glBufferData(GL_ARRAY_BUFFER, size * sizeof(FModelVertex), nullptr, GL_STATIC_DRAW); + if (!gl.legacyMode) + return (FModelVertex*)glMapBufferRange(GL_ARRAY_BUFFER, 0, size * sizeof(FModelVertex), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + else + return (FModelVertex*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); + } + else + { + if (vbo_ptr != nullptr) delete[] vbo_ptr; + vbo_ptr = new FModelVertex[size]; + memset(vbo_ptr, 0, size * sizeof(FModelVertex)); + return vbo_ptr; + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FModelVertexBuffer::UnlockVertexBuffer() +{ + if (vbo_id > 0) + { + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glUnmapBuffer(GL_ARRAY_BUFFER); + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +unsigned int *FModelVertexBuffer::LockIndexBuffer(unsigned int size) +{ + if (ibo_id != 0) + { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_id); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size * sizeof(unsigned int), NULL, GL_STATIC_DRAW); + if (!gl.legacyMode) + return (unsigned int*)glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, size * sizeof(unsigned int), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + else + return (unsigned int*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY); + } + else + { + return nullptr; + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FModelVertexBuffer::UnlockIndexBuffer() +{ + if (ibo_id > 0) + { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_id); + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + } +} + + +//=========================================================================== +// +// Sets up the buffer starts for frame interpolation +// This must be called after gl_RenderState.Apply! +// +//=========================================================================== +static TArray iBuffer; + +unsigned int FModelVertexBuffer::SetupFrame(unsigned int frame1, unsigned int frame2, unsigned int size) +{ + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + if (vbo_id > 0) + { + if (!gl.legacyMode) + { + glVertexAttribPointer(VATTR_VERTEX, 3, GL_FLOAT, false, sizeof(FModelVertex), &VMO[frame1].x); + glVertexAttribPointer(VATTR_TEXCOORD, 2, GL_FLOAT, false, sizeof(FModelVertex), &VMO[frame1].u); + glVertexAttribPointer(VATTR_VERTEX2, 3, GL_FLOAT, false, sizeof(FModelVertex), &VMO[frame2].x); + glVertexAttribPointer(VATTR_NORMAL, 4, GL_UNSIGNED_INT_2_10_10_10_REV, false, sizeof(FModelVertex), &VMO[frame2].packedNormal); + } + else + { + // only used for single frame models so there is no vertex2 here, which has no use without a shader. + glVertexPointer(3, GL_FLOAT, sizeof(FModelVertex), &VMO[frame1].x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FModelVertex), &VMO[frame1].u); + } + } + else if (frame1 == frame2 || size == 0 || gl_RenderState.GetInterpolationFactor() == 0.f) + { + glVertexPointer(3, GL_FLOAT, sizeof(FModelVertex), &vbo_ptr[frame1].x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FModelVertex), &vbo_ptr[frame1].u); + } + else + { + // must interpolate + iBuffer.Resize(size); + glVertexPointer(3, GL_FLOAT, sizeof(FModelVertex), &iBuffer[0].x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FModelVertex), &vbo_ptr[frame1].u); + float frac = gl_RenderState.GetInterpolationFactor(); + for (unsigned i = 0; i < size; i++) + { + iBuffer[i].x = vbo_ptr[frame1 + i].x * (1.f - frac) + vbo_ptr[frame2 + i].x * frac; + iBuffer[i].y = vbo_ptr[frame1 + i].y * (1.f - frac) + vbo_ptr[frame2 + i].y * frac; + iBuffer[i].z = vbo_ptr[frame1 + i].z * (1.f - frac) + vbo_ptr[frame2 + i].z * frac; + } + } + return frame1; +} + +//=========================================================================== +// +// FModel::~FModel +// +//=========================================================================== + +FModel::~FModel() +{ + if (mVBuf != nullptr) delete mVBuf; +} + + + + +static TArray SpriteModelFrames; +static int * SpriteModelHash; +//TArray StateModelFrames; + +static void DeleteModelHash() +{ + if (SpriteModelHash != nullptr) delete [] SpriteModelHash; + SpriteModelHash = nullptr; +} + +//=========================================================================== +// +// FindGFXFile +// +//=========================================================================== + +static int FindGFXFile(FString & fn) +{ + int lump = Wads.CheckNumForFullName(fn); // if we find something that matches the name plus the extension, return it and do not enter the substitution logic below. + if (lump != -1) return lump; + + int best = -1; + int dot = fn.LastIndexOf('.'); + int slash = fn.LastIndexOf('/'); + if (dot > slash) fn.Truncate(dot); + + static const char * extensions[] = { ".png", ".jpg", ".tga", ".pcx", nullptr }; + + for (const char ** extp=extensions; *extp; extp++) + { + int lump = Wads.CheckNumForFullName(fn + *extp); + if (lump >= best) best = lump; + } + return best; +} + + +//=========================================================================== +// +// LoadSkin +// +//=========================================================================== + +FTextureID LoadSkin(const char * path, const char * fn) +{ + FString buffer; + + buffer.Format("%s%s", path, fn); + + int texlump = FindGFXFile(buffer); + if (texlump>=0) + { + return TexMan.CheckForTexture(Wads.GetLumpFullName(texlump), FTexture::TEX_Any, FTextureManager::TEXMAN_TryAny); + } + else + { + return FNullTextureID(); + } +} + +//=========================================================================== +// +// ModelFrameHash +// +//=========================================================================== + +static int ModelFrameHash(FSpriteModelFrame * smf) +{ + const uint32_t *table = GetCRCTable (); + uint32_t hash = 0xffffffff; + + const char * s = (const char *)(&smf->type); // this uses type, sprite and frame for hashing + const char * se= (const char *)(&smf->hashnext); + + for (; smFileName.CompareNoCase(fullname)) return i; + } + + int len = Wads.LumpLength(lump); + FMemLump lumpd = Wads.ReadLump(lump); + char * buffer = (char*)lumpd.GetMem(); + + if (!memcmp(buffer, "DMDM", 4)) + { + model = new FDMDModel; + } + else if (!memcmp(buffer, "IDP2", 4)) + { + model = new FMD2Model; + } + else if (!memcmp(buffer, "IDP3", 4)) + { + model = new FMD3Model; + } + + if (model != nullptr) + { + if (!model->Load(path, lump, buffer, len)) + { + delete model; + return -1; + } + } + else + { + // try loading as a voxel + FVoxel *voxel = R_LoadKVX(lump); + if (voxel != nullptr) + { + model = new FVoxelModel(voxel, true); + } + else + { + Printf("LoadModel: Unknown model format in '%s'\n", fullname.GetChars()); + return -1; + } + } + // The vertex buffer cannot be initialized here because this gets called before OpenGL is initialized + model->mFileName = fullname; + return Models.Push(model); +} + +//=========================================================================== +// +// gl_InitModels +// +//=========================================================================== + +void gl_InitModels() +{ + int Lump, lastLump; + FString path; + int index, surface; + int i; + + FSpriteModelFrame smf; + + lastLump = 0; + + for(unsigned i=0;iVoxelIndex = Models.Push(md); + } + // now create GL model frames for the voxeldefs + for (unsigned i = 0; i < VoxelDefs.Size(); i++) + { + FVoxelModel *md = (FVoxelModel*)Models[VoxelDefs[i]->Voxel->VoxelIndex]; + memset(&smf, 0, sizeof(smf)); + smf.modelIDs[1] = smf.modelIDs[2] = smf.modelIDs[3] = -1; + smf.modelIDs[0] = VoxelDefs[i]->Voxel->VoxelIndex; + smf.skinIDs[0] = md->GetPaletteTexture(); + smf.xscale = smf.yscale = smf.zscale = VoxelDefs[i]->Scale; + smf.angleoffset = VoxelDefs[i]->AngleOffset.Degrees; + if (VoxelDefs[i]->PlacedSpin != 0) + { + smf.yrotate = 1.f; + smf.rotationSpeed = VoxelDefs[i]->PlacedSpin / 55.55f; + smf.flags |= MDL_ROTATING; + } + VoxelDefs[i]->VoxeldefIndex = SpriteModelFrames.Push(smf); + if (VoxelDefs[i]->PlacedSpin != VoxelDefs[i]->DroppedSpin) + { + if (VoxelDefs[i]->DroppedSpin != 0) + { + smf.yrotate = 1.f; + smf.rotationSpeed = VoxelDefs[i]->DroppedSpin / 55.55f; + smf.flags |= MDL_ROTATING; + } + else + { + smf.yrotate = 0; + smf.rotationSpeed = 0; + smf.flags &= ~MDL_ROTATING; + } + SpriteModelFrames.Push(smf); + } + } + + memset(&smf, 0, sizeof(smf)); + smf.modelIDs[0] = smf.modelIDs[1] = smf.modelIDs[2] = smf.modelIDs[3] = -1; + while ((Lump = Wads.FindLump("MODELDEF", &lastLump)) != -1) + { + FScanner sc(Lump); + while (sc.GetString()) + { + if (sc.Compare("model")) + { + path = ""; + sc.MustGetString(); + memset(&smf, 0, sizeof(smf)); + smf.modelIDs[1] = smf.modelIDs[2] = smf.modelIDs[3] = -1; + smf.xscale=smf.yscale=smf.zscale=1.f; + + smf.type = PClass::FindClass(sc.String); + if (!smf.type || smf.type->Defaults == nullptr) + { + sc.ScriptError("MODELDEF: Unknown actor type '%s'\n", sc.String); + } + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + sc.MustGetString(); + if (sc.Compare("path")) + { + sc.MustGetString(); + FixPathSeperator(sc.String); + path = sc.String; + if (path[(int)path.Len()-1]!='/') path+='/'; + } + else if (sc.Compare("model")) + { + sc.MustGetNumber(); + index = sc.Number; + if (index < 0 || index >= MAX_MODELS_PER_FRAME) + { + sc.ScriptError("Too many models in %s", smf.type->TypeName.GetChars()); + } + sc.MustGetString(); + FixPathSeperator(sc.String); + smf.modelIDs[index] = FindModel(path.GetChars(), sc.String); + if (smf.modelIDs[index] == -1) + { + Printf("%s: model not found in %s\n", sc.String, path.GetChars()); + } + } + else if (sc.Compare("scale")) + { + sc.MustGetFloat(); + smf.xscale = sc.Float; + sc.MustGetFloat(); + smf.yscale = sc.Float; + sc.MustGetFloat(); + smf.zscale = sc.Float; + } + // [BB] Added zoffset reading. + // Now it must be considered deprecated. + else if (sc.Compare("zoffset")) + { + sc.MustGetFloat(); + smf.zoffset=sc.Float; + } + // Offset reading. + else if (sc.Compare("offset")) + { + sc.MustGetFloat(); + smf.xoffset = sc.Float; + sc.MustGetFloat(); + smf.yoffset = sc.Float; + sc.MustGetFloat(); + smf.zoffset = sc.Float; + } + // angleoffset, pitchoffset and rolloffset reading. + else if (sc.Compare("angleoffset")) + { + sc.MustGetFloat(); + smf.angleoffset = sc.Float; + } + else if (sc.Compare("pitchoffset")) + { + sc.MustGetFloat(); + smf.pitchoffset = sc.Float; + } + else if (sc.Compare("rolloffset")) + { + sc.MustGetFloat(); + smf.rolloffset = sc.Float; + } + // [BB] Added model flags reading. + else if (sc.Compare("ignoretranslation")) + { + smf.flags |= MDL_IGNORETRANSLATION; + } + else if (sc.Compare("pitchfrommomentum")) + { + smf.flags |= MDL_PITCHFROMMOMENTUM; + } + else if (sc.Compare("inheritactorpitch")) + { + smf.flags |= MDL_USEACTORPITCH | MDL_BADROTATION; + } + else if (sc.Compare("inheritactorroll")) + { + smf.flags |= MDL_USEACTORROLL; + } + else if (sc.Compare("useactorpitch")) + { + smf.flags |= MDL_USEACTORPITCH; + } + else if (sc.Compare("useactorroll")) + { + smf.flags |= MDL_USEACTORROLL; + } + else if (sc.Compare("rotating")) + { + smf.flags |= MDL_ROTATING; + smf.xrotate = 0.; + smf.yrotate = 1.; + smf.zrotate = 0.; + smf.rotationCenterX = 0.; + smf.rotationCenterY = 0.; + smf.rotationCenterZ = 0.; + smf.rotationSpeed = 1.; + } + else if (sc.Compare("rotation-speed")) + { + sc.MustGetFloat(); + smf.rotationSpeed = sc.Float; + } + else if (sc.Compare("rotation-vector")) + { + sc.MustGetFloat(); + smf.xrotate = sc.Float; + sc.MustGetFloat(); + smf.yrotate = sc.Float; + sc.MustGetFloat(); + smf.zrotate = sc.Float; + } + else if (sc.Compare("rotation-center")) + { + sc.MustGetFloat(); + smf.rotationCenterX = sc.Float; + sc.MustGetFloat(); + smf.rotationCenterY = sc.Float; + sc.MustGetFloat(); + smf.rotationCenterZ = sc.Float; + } + else if (sc.Compare("interpolatedoubledframes")) + { + smf.flags |= MDL_INTERPOLATEDOUBLEDFRAMES; + } + else if (sc.Compare("nointerpolation")) + { + smf.flags |= MDL_NOINTERPOLATION; + } + else if (sc.Compare("skin")) + { + sc.MustGetNumber(); + index=sc.Number; + if (index<0 || index>=MAX_MODELS_PER_FRAME) + { + sc.ScriptError("Too many models in %s", smf.type->TypeName.GetChars()); + } + sc.MustGetString(); + FixPathSeperator(sc.String); + if (sc.Compare("")) + { + smf.skinIDs[index]=FNullTextureID(); + } + else + { + smf.skinIDs[index] = LoadSkin(path.GetChars(), sc.String); + if (!smf.skinIDs[index].isValid()) + { + Printf("Skin '%s' not found in '%s'\n", + sc.String, smf.type->TypeName.GetChars()); + } + } + } + else if (sc.Compare("surfaceskin")) + { + sc.MustGetNumber(); + index = sc.Number; + sc.MustGetNumber(); + surface = sc.Number; + + if (index<0 || index >= MAX_MODELS_PER_FRAME) + { + sc.ScriptError("Too many models in %s", smf.type->TypeName.GetChars()); + } + + if (surface<0 || surface >= MD3_MAX_SURFACES) + { + sc.ScriptError("Invalid MD3 Surface %d in %s", MD3_MAX_SURFACES, smf.type->TypeName.GetChars()); + } + + sc.MustGetString(); + FixPathSeperator(sc.String); + if (sc.Compare("")) + { + smf.surfaceskinIDs[index][surface] = FNullTextureID(); + } + else + { + smf.surfaceskinIDs[index][surface] = LoadSkin(path.GetChars(), sc.String); + if (!smf.surfaceskinIDs[index][surface].isValid()) + { + Printf("Surface Skin '%s' not found in '%s'\n", + sc.String, smf.type->TypeName.GetChars()); + } + } + } + else if (sc.Compare("frameindex") || sc.Compare("frame")) + { + bool isframe=!!sc.Compare("frame"); + + sc.MustGetString(); + smf.sprite = -1; + for (i = 0; i < (int)sprites.Size (); ++i) + { + if (strnicmp (sprites[i].name, sc.String, 4) == 0) + { + if (sprites[i].numframes==0) + { + //sc.ScriptError("Sprite %s has no frames", sc.String); + } + smf.sprite = i; + break; + } + } + if (smf.sprite==-1) + { + sc.ScriptError("Unknown sprite %s in model definition for %s", sc.String, smf.type->TypeName.GetChars()); + } + + sc.MustGetString(); + FString framechars = sc.String; + + sc.MustGetNumber(); + index=sc.Number; + if (index<0 || index>=MAX_MODELS_PER_FRAME) + { + sc.ScriptError("Too many models in %s", smf.type->TypeName.GetChars()); + } + if (isframe) + { + sc.MustGetString(); + if (smf.modelIDs[index] != -1) + { + FModel *model = Models[smf.modelIDs[index]]; + smf.modelframes[index] = model->FindFrame(sc.String); + if (smf.modelframes[index]==-1) sc.ScriptError("Unknown frame '%s' in %s", sc.String, smf.type->TypeName.GetChars()); + } + else smf.modelframes[index] = -1; + } + else + { + sc.MustGetNumber(); + smf.modelframes[index] = sc.Number; + } + + for(i=0; framechars[i]>0; i++) + { + char map[29]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + int c = toupper(framechars[i])-'A'; + + if (c<0 || c>=29) + { + sc.ScriptError("Invalid frame character %c found", c+'A'); + } + if (map[c]) continue; + smf.frame=c; + SpriteModelFrames.Push(smf); + GetDefaultByType(smf.type)->hasmodel = true; + map[c]=1; + } + } + else + { + sc.ScriptMessage("Unrecognized string \"%s\"", sc.String); + } + } + } + } + } + + // create a hash table for quick access + SpriteModelHash = new int[SpriteModelFrames.Size ()]; + atterm(DeleteModelHash); + memset(SpriteModelHash, 0xff, SpriteModelFrames.Size () * sizeof(int)); + + for (i = 0; i < (int)SpriteModelFrames.Size (); i++) + { + int j = ModelFrameHash(&SpriteModelFrames[i]) % SpriteModelFrames.Size (); + + SpriteModelFrames[i].hashnext = SpriteModelHash[j]; + SpriteModelHash[j]=i; + } +} + + +//=========================================================================== +// +// gl_FindModelFrame +// +//=========================================================================== +EXTERN_CVAR (Bool, r_drawvoxels) + +FSpriteModelFrame * gl_FindModelFrame(const PClass * ti, int sprite, int frame, bool dropped) +{ + if (GetDefaultByType(ti)->hasmodel) + { + FSpriteModelFrame smf; + + memset(&smf, 0, sizeof(smf)); + smf.type=ti; + smf.sprite=sprite; + smf.frame=frame; + + int hash = SpriteModelHash[ModelFrameHash(&smf) % SpriteModelFrames.Size()]; + + while (hash>=0) + { + FSpriteModelFrame * smff = &SpriteModelFrames[hash]; + if (smff->type==ti && smff->sprite==sprite && smff->frame==frame) return smff; + hash=smff->hashnext; + } + } + + // Check for voxel replacements + if (r_drawvoxels) + { + spritedef_t *sprdef = &sprites[sprite]; + if (frame < sprdef->numframes) + { + spriteframe_t *sprframe = &SpriteFrames[sprdef->spriteframes + frame]; + if (sprframe->Voxel != nullptr) + { + int index = sprframe->Voxel->VoxeldefIndex; + if (dropped && sprframe->Voxel->DroppedSpin !=sprframe->Voxel->PlacedSpin) index++; + return &SpriteModelFrames[index]; + } + } + } + return nullptr; +} + + +//=========================================================================== +// +// gl_RenderModel +// +//=========================================================================== + +void gl_RenderFrameModels( const FSpriteModelFrame *smf, + const FState *curState, + const int curTics, + const PClass *ti, + Matrix3x4 *normaltransform, + int translation) +{ + // [BB] Frame interpolation: Find the FSpriteModelFrame smfNext which follows after smf in the animation + // and the scalar value inter ( element of [0,1) ), both necessary to determine the interpolated frame. + FSpriteModelFrame * smfNext = nullptr; + double inter = 0.; + if( gl_interpolate_model_frames && !(smf->flags & MDL_NOINTERPOLATION) ) + { + FState *nextState = curState->GetNextState( ); + if( curState != nextState && nextState ) + { + // [BB] To interpolate at more than 35 fps we take tic fractions into account. + float ticFraction = 0.; + // [BB] In case the tic counter is frozen we have to leave ticFraction at zero. + if ( ConsoleState == c_up && menuactive != MENU_On && !(level.flags2 & LEVEL2_FROZEN) ) + { + float time = GetTimeFloat(); + ticFraction = (time - static_cast(time)); + } + inter = static_cast(curState->Tics - curTics - ticFraction)/static_cast(curState->Tics); + + // [BB] For some actors (e.g. ZPoisonShroom) spr->actor->tics can be bigger than curState->Tics. + // In this case inter is negative and we need to set it to zero. + if ( inter < 0. ) + inter = 0.; + else + { + // [BB] Workaround for actors that use the same frame twice in a row. + // Most of the standard Doom monsters do this in their see state. + if ( (smf->flags & MDL_INTERPOLATEDOUBLEDFRAMES) ) + { + const FState *prevState = curState - 1; + if ( (curState->sprite == prevState->sprite) && ( curState->Frame == prevState->Frame) ) + { + inter /= 2.; + inter += 0.5; + } + if ( (curState->sprite == nextState->sprite) && ( curState->Frame == nextState->Frame) ) + { + inter /= 2.; + nextState = nextState->GetNextState( ); + } + } + if ( inter != 0.0 ) + smfNext = gl_FindModelFrame(ti, nextState->sprite, nextState->Frame, false); + } + } + } + + for(int i=0; imodelIDs[i] != -1) + { + FModel * mdl = Models[smf->modelIDs[i]]; + FTexture *tex = smf->skinIDs[i].isValid()? TexMan(smf->skinIDs[i]) : nullptr; + mdl->BuildVertexBuffer(); + gl_RenderState.SetVertexBuffer(mdl->mVBuf); + + mdl->PushSpriteMDLFrame(smf, i); + + if ( smfNext && smf->modelframes[i] != smfNext->modelframes[i] ) + mdl->RenderFrame(tex, smf->modelframes[i], smfNext->modelframes[i], inter, translation); + else + mdl->RenderFrame(tex, smf->modelframes[i], smf->modelframes[i], 0.f, translation); + + gl_RenderState.SetVertexBuffer(GLRenderer->mVBO); + } + } +} + +void gl_RenderModel(GLSprite * spr) +{ + FSpriteModelFrame * smf = spr->modelframe; + + + // Setup transformation. + glDepthFunc(GL_LEQUAL); + gl_RenderState.EnableTexture(true); + // [BB] In case the model should be rendered translucent, do back face culling. + // This solves a few of the problems caused by the lack of depth sorting. + // TO-DO: Implement proper depth sorting. + if (!( spr->actor->RenderStyle == LegacyRenderStyles[STYLE_Normal] )) + { + glEnable(GL_CULL_FACE); + glFrontFace(GL_CW); + } + + int translation = 0; + if ( !(smf->flags & MDL_IGNORETRANSLATION) ) + translation = spr->actor->Translation; + + + // y scale for a sprite means height, i.e. z in the world! + float scaleFactorX = spr->actor->Scale.X * smf->xscale; + float scaleFactorY = spr->actor->Scale.X * smf->yscale; + float scaleFactorZ = spr->actor->Scale.Y * smf->zscale; + float pitch = 0; + float roll = 0; + float rotateOffset = 0; + float angle = spr->actor->Angles.Yaw.Degrees; + + // [BB] Workaround for the missing pitch information. + if ( (smf->flags & MDL_PITCHFROMMOMENTUM) ) + { + const double x = spr->actor->Vel.X; + const double y = spr->actor->Vel.Y; + const double z = spr->actor->Vel.Z; + + if (spr->actor->Vel.LengthSquared() > EQUAL_EPSILON) + { + // [BB] Calculate the pitch using spherical coordinates. + if (z || x || y) pitch = float(atan(z / sqrt(x*x + y*y)) / M_PI * 180); + + // Correcting pitch if model is moving backwards + if (fabs(x) > EQUAL_EPSILON || fabs(y) > EQUAL_EPSILON) + { + if ((x * cos(angle * M_PI / 180) + y * sin(angle * M_PI / 180)) / sqrt(x * x + y * y) < 0) pitch *= -1; + } + else pitch = fabs(pitch); + } + } + + if( smf->flags & MDL_ROTATING ) + { + const float time = smf->rotationSpeed*GetTimeFloat()/200.f; + rotateOffset = float((time - xs_FloorToInt(time)) *360.f ); + } + + // Added MDL_USEACTORPITCH and MDL_USEACTORROLL flags processing. + // If both flags MDL_USEACTORPITCH and MDL_PITCHFROMMOMENTUM are set, the pitch sums up the actor pitch and the momentum vector pitch. + if (smf->flags & MDL_USEACTORPITCH) + { + double d = spr->actor->Angles.Pitch.Degrees; + if (smf->flags & MDL_BADROTATION) pitch -= d; + else pitch += d; + } + if(smf->flags & MDL_USEACTORROLL) roll += spr->actor->Angles.Roll.Degrees; + + gl_RenderState.mModelMatrix.loadIdentity(); + + // Model space => World space + gl_RenderState.mModelMatrix.translate(spr->x, spr->z, spr->y ); + + // Applying model transformations: + // 1) Applying actor angle, pitch and roll to the model + gl_RenderState.mModelMatrix.rotate(-angle, 0, 1, 0); + gl_RenderState.mModelMatrix.rotate(pitch, 0, 0, 1); + gl_RenderState.mModelMatrix.rotate(-roll, 1, 0, 0); + + // 2) Applying Doomsday like rotation of the weapon pickup models + // The rotation angle is based on the elapsed time. + + if( smf->flags & MDL_ROTATING ) + { + gl_RenderState.mModelMatrix.translate(smf->rotationCenterX, smf->rotationCenterY, smf->rotationCenterZ); + gl_RenderState.mModelMatrix.rotate(rotateOffset, smf->xrotate, smf->yrotate, smf->zrotate); + gl_RenderState.mModelMatrix.translate(-smf->rotationCenterX, -smf->rotationCenterY, -smf->rotationCenterZ); + } + + // 3) Scaling model. + gl_RenderState.mModelMatrix.scale(scaleFactorX, scaleFactorZ, scaleFactorY); + + // 4) Aplying model offsets (model offsets do not depend on model scalings). + gl_RenderState.mModelMatrix.translate(smf->xoffset / smf->xscale, smf->zoffset / smf->zscale, smf->yoffset / smf->yscale); + + // 5) Applying model rotations. + gl_RenderState.mModelMatrix.rotate(-smf->angleoffset, 0, 1, 0); + gl_RenderState.mModelMatrix.rotate(smf->pitchoffset, 0, 0, 1); + gl_RenderState.mModelMatrix.rotate(-smf->rolloffset, 1, 0, 0); + + // consider the pixel stretching. For non-voxels this must be factored out here + float stretch = (smf->modelIDs[0] != -1 ? Models[smf->modelIDs[0]]->getAspectFactor() : 1.f) / glset.pixelstretch; + gl_RenderState.mModelMatrix.scale(1, stretch, 1); + + + gl_RenderState.EnableModelMatrix(true); + gl_RenderFrameModels( smf, spr->actor->state, spr->actor->tics, spr->actor->GetClass(), nullptr, translation ); + gl_RenderState.EnableModelMatrix(false); + + glDepthFunc(GL_LESS); + if (!( spr->actor->RenderStyle == LegacyRenderStyles[STYLE_Normal] )) + glDisable(GL_CULL_FACE); +} + + +//=========================================================================== +// +// gl_RenderHUDModel +// +//=========================================================================== + +void gl_RenderHUDModel(DPSprite *psp, float ofsX, float ofsY) +{ + AActor * playermo=players[consoleplayer].camera; + FSpriteModelFrame *smf = gl_FindModelFrame(playermo->player->ReadyWeapon->GetClass(), psp->GetState()->sprite, psp->GetState()->GetFrame(), false); + + // [BB] No model found for this sprite, so we can't render anything. + if ( smf == nullptr ) + return; + + glDepthFunc(GL_LEQUAL); + + // [BB] In case the model should be rendered translucent, do back face culling. + // This solves a few of the problems caused by the lack of depth sorting. + // TO-DO: Implement proper depth sorting. + if (!( playermo->RenderStyle == LegacyRenderStyles[STYLE_Normal] )) + { + glEnable(GL_CULL_FACE); + glFrontFace(GL_CCW); + } + + // [BB] The model has to be drawn independently from the position of the player, + // so we have to reset the view matrix. + gl_RenderState.mViewMatrix.loadIdentity(); + + // Scaling model (y scale for a sprite means height, i.e. z in the world!). + gl_RenderState.mViewMatrix.scale(smf->xscale, smf->zscale, smf->yscale); + + // Aplying model offsets (model offsets do not depend on model scalings). + gl_RenderState.mViewMatrix.translate(smf->xoffset / smf->xscale, smf->zoffset / smf->zscale, smf->yoffset / smf->yscale); + + // [BB] Weapon bob, very similar to the normal Doom weapon bob. + gl_RenderState.mViewMatrix.rotate(ofsX/4, 0, 1, 0); + gl_RenderState.mViewMatrix.rotate((ofsY-WEAPONTOP)/-4., 1, 0, 0); + + // [BB] For some reason the jDoom models need to be rotated. + gl_RenderState.mViewMatrix.rotate(90.f, 0, 1, 0); + + // Applying angleoffset, pitchoffset, rolloffset. + gl_RenderState.mViewMatrix.rotate(-smf->angleoffset, 0, 1, 0); + gl_RenderState.mViewMatrix.rotate(smf->pitchoffset, 0, 0, 1); + gl_RenderState.mViewMatrix.rotate(-smf->rolloffset, 1, 0, 0); + gl_RenderState.ApplyMatrices(); + + gl_RenderFrameModels( smf, psp->GetState(), psp->GetTics(), playermo->player->ReadyWeapon->GetClass(), nullptr, 0 ); + + glDepthFunc(GL_LESS); + if (!( playermo->RenderStyle == LegacyRenderStyles[STYLE_Normal] )) + glDisable(GL_CULL_FACE); +} + +//=========================================================================== +// +// gl_IsHUDModelForPlayerAvailable +// +//=========================================================================== + +bool gl_IsHUDModelForPlayerAvailable (player_t * player) +{ + if (player == nullptr || player->ReadyWeapon == nullptr) + return false; + + DPSprite *psp = player->FindPSprite(PSP_WEAPON); + + if (psp == nullptr || psp->GetState() == nullptr) + return false; + + FState* state = psp->GetState(); + FSpriteModelFrame *smf = gl_FindModelFrame(player->ReadyWeapon->GetClass(), state->sprite, state->GetFrame(), false); + return ( smf != nullptr ); +} + diff --git a/src/gl/models/gl_models.h b/src/gl/models/gl_models.h new file mode 100644 index 000000000..f0267b891 --- /dev/null +++ b/src/gl/models/gl_models.h @@ -0,0 +1,425 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#ifndef __GL_MODELS_H_ +#define __GL_MODELS_H_ + +#include "tarray.h" +#include "gl/utility/gl_geometric.h" +#include "gl/data/gl_vertexbuffer.h" +#include "p_pspr.h" +#include "r_data/voxels.h" + + +#define MAX_LODS 4 + +enum { VX, VZ, VY }; + +#define MD2_MAGIC 0x32504449 +#define DMD_MAGIC 0x4D444D44 +#define MD3_MAGIC 0x33504449 +#define NUMVERTEXNORMALS 162 +#define MD3_MAX_SURFACES 32 + +FTextureID LoadSkin(const char * path, const char * fn); + +// [JM] Necessary forward declaration +typedef struct FSpriteModelFrame FSpriteModelFrame; + +class FModel +{ +public: + + FModel() + { + mVBuf = NULL; + } + virtual ~FModel(); + + virtual bool Load(const char * fn, int lumpnum, const char * buffer, int length) = 0; + virtual int FindFrame(const char * name) = 0; + virtual void RenderFrame(FTexture * skin, int frame, int frame2, double inter, int translation=0) = 0; + virtual void BuildVertexBuffer() = 0; + virtual void AddSkins(BYTE *hitlist) = 0; + void DestroyVertexBuffer() + { + delete mVBuf; + mVBuf = NULL; + } + virtual float getAspectFactor() { return 1.f; } + + const FSpriteModelFrame *curSpriteMDLFrame; + int curMDLIndex; + void PushSpriteMDLFrame(const FSpriteModelFrame *smf, int index) { curSpriteMDLFrame = smf; curMDLIndex = index; }; + + FModelVertexBuffer *mVBuf; + FString mFileName; +}; + +class FDMDModel : public FModel +{ +protected: + + struct FTriangle + { + unsigned short vertexIndices[3]; + unsigned short textureIndices[3]; + }; + + + struct DMDHeader + { + int magic; + int version; + int flags; + }; + + struct DMDModelVertex + { + float xyz[3]; + }; + + struct FTexCoord + { + short s, t; + }; + + struct FGLCommandVertex + { + float s, t; + int index; + }; + + struct DMDInfo + { + int skinWidth; + int skinHeight; + int frameSize; + int numSkins; + int numVertices; + int numTexCoords; + int numFrames; + int numLODs; + int offsetSkins; + int offsetTexCoords; + int offsetFrames; + int offsetLODs; + int offsetEnd; + }; + + struct ModelFrame + { + char name[16]; + unsigned int vindex; + }; + + struct ModelFrameVertexData + { + DMDModelVertex *vertices; + DMDModelVertex *normals; + }; + + struct DMDLoDInfo + { + int numTriangles; + int numGlCommands; + int offsetTriangles; + int offsetGlCommands; + }; + + struct DMDLoD + { + FTriangle * triangles; + }; + + + int mLumpNum; + DMDHeader header; + DMDInfo info; + FTextureID * skins; + ModelFrame * frames; + bool allowTexComp; // Allow texture compression with this. + + // Temp data only needed for buffer construction + FTexCoord * texCoords; + ModelFrameVertexData *framevtx; + DMDLoDInfo lodInfo[MAX_LODS]; + DMDLoD lods[MAX_LODS]; + +public: + FDMDModel() + { + mLumpNum = -1; + frames = NULL; + skins = NULL; + for (int i = 0; i < MAX_LODS; i++) + { + lods[i].triangles = NULL; + } + info.numLODs = 0; + texCoords = NULL; + framevtx = NULL; + } + virtual ~FDMDModel(); + + virtual bool Load(const char * fn, int lumpnum, const char * buffer, int length); + virtual int FindFrame(const char * name); + virtual void RenderFrame(FTexture * skin, int frame, int frame2, double inter, int translation=0); + virtual void LoadGeometry(); + virtual void AddSkins(BYTE *hitlist); + + void UnloadGeometry(); + void BuildVertexBuffer(); + +}; + +// This uses the same internal representation as DMD +class FMD2Model : public FDMDModel +{ +public: + FMD2Model() {} + virtual ~FMD2Model(); + + virtual bool Load(const char * fn, int lumpnum, const char * buffer, int length); + virtual void LoadGeometry(); + +}; + + +class FMD3Model : public FModel +{ + struct MD3Tag + { + // Currently I have no use for this + }; + + struct MD3TexCoord + { + float s,t; + }; + + struct MD3Vertex + { + float x,y,z; + float nx,ny,nz; + }; + + struct MD3Triangle + { + int VertIndex[3]; + }; + + struct MD3Surface + { + int numVertices; + int numTriangles; + int numSkins; + + FTextureID * skins; + MD3Triangle * tris; + MD3TexCoord * texcoords; + MD3Vertex * vertices; + + unsigned int vindex; // contains numframes arrays of vertices + unsigned int iindex; + + MD3Surface() + { + tris=NULL; + vertices=NULL; + texcoords=NULL; + vindex = iindex = UINT_MAX; + } + + ~MD3Surface() + { + if (skins) delete [] skins; + UnloadGeometry(); + } + + void UnloadGeometry() + { + if (tris) delete [] tris; + if (vertices) delete [] vertices; + if (texcoords) delete [] texcoords; + tris = NULL; + vertices = NULL; + texcoords = NULL; + } + }; + + struct MD3Frame + { + // The bounding box information is of no use in the Doom engine + // That will still be done with the actor's size information. + char Name[16]; + float origin[3]; + }; + + int numFrames; + int numTags; + int numSurfaces; + int mLumpNum; + + MD3Frame * frames; + MD3Surface * surfaces; + +public: + FMD3Model() { } + virtual ~FMD3Model(); + + virtual bool Load(const char * fn, int lumpnum, const char * buffer, int length); + virtual int FindFrame(const char * name); + virtual void RenderFrame(FTexture * skin, int frame, int frame2, double inter, int translation=0); + void LoadGeometry(); + void BuildVertexBuffer(); + virtual void AddSkins(BYTE *hitlist); +}; + +struct FVoxelVertexHash +{ + // Returns the hash value for a key. + hash_t Hash(const FModelVertex &key) + { + int ix = xs_RoundToInt(key.x); + int iy = xs_RoundToInt(key.y); + int iz = xs_RoundToInt(key.z); + return (hash_t)(ix + (iy<<9) + (iz<<18)); + } + + // Compares two keys, returning zero if they are the same. + int Compare(const FModelVertex &left, const FModelVertex &right) + { + return left.x != right.x || left.y != right.y || left.z != right.z || left.u != right.u || left.v != right.v; + } +}; + +struct FIndexInit +{ + void Init(unsigned int &value) + { + value = 0xffffffff; + } +}; + +typedef TMap FVoxelMap; + + +class FVoxelModel : public FModel +{ +protected: + FVoxel *mVoxel; + bool mOwningVoxel; // if created through MODELDEF deleting this object must also delete the voxel object + FTextureID mPalette; + unsigned int mNumIndices; + TArray mVertices; + TArray mIndices; + + void MakeSlabPolys(int x, int y, kvxslab_t *voxptr, FVoxelMap &check); + void AddFace(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3, int x4, int y4, int z4, BYTE color, FVoxelMap &check); + unsigned int AddVertex(FModelVertex &vert, FVoxelMap &check); + +public: + FVoxelModel(FVoxel *voxel, bool owned); + ~FVoxelModel(); + bool Load(const char * fn, int lumpnum, const char * buffer, int length); + void Initialize(); + virtual int FindFrame(const char * name); + virtual void RenderFrame(FTexture * skin, int frame, int frame2, double inter, int translation=0); + virtual void AddSkins(BYTE *hitlist); + FTextureID GetPaletteTexture() const { return mPalette; } + void BuildVertexBuffer(); + float getAspectFactor(); +}; + + + +#define MAX_MODELS_PER_FRAME 4 + +// +// [BB] Model rendering flags. +// +enum +{ + // [BB] Color translations for the model skin are ignored. This is + // useful if the skin texture is not using the game palette. + MDL_IGNORETRANSLATION = 1, + MDL_PITCHFROMMOMENTUM = 2, + MDL_ROTATING = 4, + MDL_INTERPOLATEDOUBLEDFRAMES = 8, + MDL_NOINTERPOLATION = 16, + MDL_USEACTORPITCH = 32, + MDL_USEACTORROLL = 64, + MDL_BADROTATION = 128, +}; + +struct FSpriteModelFrame +{ + int modelIDs[MAX_MODELS_PER_FRAME]; + FTextureID skinIDs[MAX_MODELS_PER_FRAME]; + FTextureID surfaceskinIDs[MAX_MODELS_PER_FRAME][MD3_MAX_SURFACES]; + int modelframes[MAX_MODELS_PER_FRAME]; + float xscale, yscale, zscale; + // [BB] Added zoffset, rotation parameters and flags. + // Added xoffset, yoffset + float xoffset, yoffset, zoffset; + float xrotate, yrotate, zrotate; + float rotationCenterX, rotationCenterY, rotationCenterZ; + float rotationSpeed; + unsigned int flags; + const PClass * type; + short sprite; + short frame; + FState * state; // for later! + int hashnext; + float angleoffset; + // added pithoffset, rolloffset. + float pitchoffset, rolloffset; // I don't want to bother with type transformations, so I made this variables float. +}; + +class GLSprite; + +FSpriteModelFrame * gl_FindModelFrame(const PClass * ti, int sprite, int frame, bool dropped); + +void gl_RenderModel(GLSprite * spr); +// [BB] HUD weapon model rendering functions. +void gl_RenderHUDModel(DPSprite *psp, float ofsx, float ofsy); +bool gl_IsHUDModelForPlayerAvailable (player_t * player); + + +class DeletingModelArray : public TArray +{ +public: + + ~DeletingModelArray() + { + for (unsigned i = 0; i> 9) / 127.0f - 0.5f) * M_PI; + float cosp = (float) cos(pitch); + + vec[VX] = (float) cos(yaw) * cosp; + vec[VY] = (float) sin(yaw) * cosp; + vec[VZ] = (float) sin(pitch); +} + + +//=========================================================================== +// +// DMD file structure +// +//=========================================================================== + +struct dmd_chunk_t +{ + int type; + int length; // Next chunk follows... +}; + +#pragma pack(1) +struct dmd_packedVertex_t +{ + byte vertex[3]; + unsigned short normal; // Yaw and pitch. +}; + +struct dmd_packedFrame_t +{ + float scale[3]; + float translate[3]; + char name[16]; + dmd_packedVertex_t vertices[1]; +}; +#pragma pack() + +// Chunk types. +enum +{ + DMC_END, // Must be the last chunk. + DMC_INFO // Required; will be expected to exist. +}; + +//=========================================================================== +// +// FDMDModel::Load +// +//=========================================================================== + +bool FDMDModel::Load(const char * path, int lumpnum, const char * buffer, int length) +{ + dmd_chunk_t * chunk = (dmd_chunk_t*)(buffer + 12); + char *temp; + ModelFrame *frame; + int i; + + int fileoffset = 12 + sizeof(dmd_chunk_t); + + chunk->type = LittleLong(chunk->type); + while (chunk->type != DMC_END) + { + switch (chunk->type) + { + case DMC_INFO: // Standard DMD information chunk. + memcpy(&info, buffer + fileoffset, LittleLong(chunk->length)); + info.skinWidth = LittleLong(info.skinWidth); + info.skinHeight = LittleLong(info.skinHeight); + info.frameSize = LittleLong(info.frameSize); + info.numSkins = LittleLong(info.numSkins); + info.numVertices = LittleLong(info.numVertices); + info.numTexCoords = LittleLong(info.numTexCoords); + info.numFrames = LittleLong(info.numFrames); + info.numLODs = LittleLong(info.numLODs); + info.offsetSkins = LittleLong(info.offsetSkins); + info.offsetTexCoords = LittleLong(info.offsetTexCoords); + info.offsetFrames = LittleLong(info.offsetFrames); + info.offsetLODs = LittleLong(info.offsetLODs); + info.offsetEnd = LittleLong(info.offsetEnd); + fileoffset += chunk->length; + break; + + default: + // Just skip all unknown chunks. + fileoffset += chunk->length; + break; + } + // Read the next chunk header. + chunk = (dmd_chunk_t*)(buffer + fileoffset); + chunk->type = LittleLong(chunk->type); + fileoffset += sizeof(dmd_chunk_t); + } + + // Allocate and load in the data. + skins = new FTextureID[info.numSkins]; + + for (i = 0; i < info.numSkins; i++) + { + skins[i] = LoadSkin(path, buffer + info.offsetSkins + i * 64); + } + temp = (char*)buffer + info.offsetFrames; + frames = new ModelFrame[info.numFrames]; + + for (i = 0, frame = frames; i < info.numFrames; i++, frame++) + { + dmd_packedFrame_t *pfr = (dmd_packedFrame_t *)(temp + info.frameSize * i); + + memcpy(frame->name, pfr->name, sizeof(pfr->name)); + frame->vindex = UINT_MAX; + } + mLumpNum = lumpnum; + return true; +} + +//=========================================================================== +// +// FDMDModel::LoadGeometry +// +//=========================================================================== + +void FDMDModel::LoadGeometry() +{ + static int axis[3] = { VX, VY, VZ }; + FMemLump lumpdata = Wads.ReadLump(mLumpNum); + const char *buffer = (const char *)lumpdata.GetMem(); + texCoords = new FTexCoord[info.numTexCoords]; + memcpy(texCoords, buffer + info.offsetTexCoords, info.numTexCoords * sizeof(FTexCoord)); + + const char *temp = buffer + info.offsetFrames; + framevtx= new ModelFrameVertexData[info.numFrames]; + + ModelFrameVertexData *framev; + int i, k, c; + for(i = 0, framev = framevtx; i < info.numFrames; i++, framev++) + { + dmd_packedFrame_t *pfr = (dmd_packedFrame_t *) (temp + info.frameSize * i); + dmd_packedVertex_t *pVtx; + + framev->vertices = new DMDModelVertex[info.numVertices]; + framev->normals = new DMDModelVertex[info.numVertices]; + + // Translate each vertex. + for(k = 0, pVtx = pfr->vertices; k < info.numVertices; k++, pVtx++) + { + UnpackVector((unsigned short)(pVtx->normal), framev->normals[k].xyz); + for(c = 0; c < 3; c++) + { + framev->vertices[k].xyz[axis[c]] = + (pVtx->vertex[c] * FLOAT(pfr->scale[c]) + FLOAT(pfr->translate[c])); + } + } + } + + memcpy(lodInfo, buffer+info.offsetLODs, info.numLODs * sizeof(DMDLoDInfo)); + for(i = 0; i < info.numLODs; i++) + { + lodInfo[i].numTriangles = LittleLong(lodInfo[i].numTriangles); + lodInfo[i].offsetTriangles = LittleLong(lodInfo[i].offsetTriangles); + if (lodInfo[i].numTriangles > 0) + { + lods[i].triangles = new FTriangle[lodInfo[i].numTriangles]; + memcpy(lods[i].triangles, buffer + lodInfo[i].offsetTriangles, lodInfo[i].numTriangles * sizeof(FTriangle)); + for (int j = 0; j < lodInfo[i].numTriangles; j++) + { + for (int k = 0; k < 3; k++) + { + lods[i].triangles[j].textureIndices[k] = LittleShort(lods[i].triangles[j].textureIndices[k]); + lods[i].triangles[j].vertexIndices[k] = LittleShort(lods[i].triangles[j].vertexIndices[k]); + } + } + } + } + +} + +//=========================================================================== +// +// Deletes everything that's no longer needed after building the vertex buffer +// +//=========================================================================== + +void FDMDModel::UnloadGeometry() +{ + int i; + + if (framevtx != NULL) + { + for (i=0;iLockVertexBuffer(VertexBufferSize); + + for (int i = 0; i < info.numFrames; i++) + { + DMDModelVertex *vert = framevtx[i].vertices; + DMDModelVertex *norm = framevtx[i].normals; + + frames[i].vindex = vindex; + + FTriangle *tri = lods[0].triangles; + + for (int i = 0; i < lodInfo[0].numTriangles; i++) + { + for (int j = 0; j < 3; j++) + { + + int ti = tri->textureIndices[j]; + int vi = tri->vertexIndices[j]; + + FModelVertex *bvert = &vertptr[vindex++]; + bvert->Set(vert[vi].xyz[0], vert[vi].xyz[1], vert[vi].xyz[2], (float)texCoords[ti].s / info.skinWidth, (float)texCoords[ti].t / info.skinHeight); + bvert->SetNormal(norm[vi].xyz[0], norm[vi].xyz[1], norm[vi].xyz[2]); + } + tri++; + } + } + mVBuf->UnlockVertexBuffer(); + UnloadGeometry(); + } +} + +//=========================================================================== +// +// for skin precaching +// +//=========================================================================== + +void FDMDModel::AddSkins(BYTE *hitlist) +{ + for (int i = 0; i < info.numSkins; i++) + { + if (skins[i].isValid()) + { + hitlist[skins[i].GetIndex()] |= FTexture::TEX_Flat; + } + } +} + +//=========================================================================== +// +// FDMDModel::FindFrame +// +//=========================================================================== +int FDMDModel::FindFrame(const char * name) +{ + for (int i=0;i= info.numFrames || frameno2 >= info.numFrames) return; + + if (!skin) + { + if (info.numSkins == 0 || !skins[0].isValid()) return; + skin = TexMan(skins[0]); + if (!skin) return; + } + + FMaterial * tex = FMaterial::ValidateTexture(skin, false); + + gl_RenderState.SetMaterial(tex, CLAMP_NONE, translation, -1, false); + gl_RenderState.SetInterpolationFactor((float)inter); + + gl_RenderState.Apply(); + mVBuf->SetupFrame(frames[frameno].vindex, frames[frameno2].vindex, lodInfo[0].numTriangles * 3); + glDrawArrays(GL_TRIANGLES, 0, lodInfo[0].numTriangles * 3); + gl_RenderState.SetInterpolationFactor(0.f); +} + + + +//=========================================================================== +// +// Internal data structures of MD2 files - only used during loading +// +//=========================================================================== + +struct md2_header_t +{ + int magic; + int version; + int skinWidth; + int skinHeight; + int frameSize; + int numSkins; + int numVertices; + int numTexCoords; + int numTriangles; + int numGlCommands; + int numFrames; + int offsetSkins; + int offsetTexCoords; + int offsetTriangles; + int offsetFrames; + int offsetGlCommands; + int offsetEnd; +}; + +struct md2_triangleVertex_t +{ + byte vertex[3]; + byte lightNormalIndex; +}; + +struct md2_packedFrame_t +{ + float scale[3]; + float translate[3]; + char name[16]; + md2_triangleVertex_t vertices[1]; +}; + +//=========================================================================== +// +// FMD2Model::Load +// +//=========================================================================== + +bool FMD2Model::Load(const char * path, int lumpnum, const char * buffer, int length) +{ + md2_header_t * md2header = (md2_header_t *)buffer; + ModelFrame *frame; + byte *md2_frames; + int i; + + // Convert it to DMD. + header.magic = MD2_MAGIC; + header.version = 8; + header.flags = 0; + info.skinWidth = LittleLong(md2header->skinWidth); + info.skinHeight = LittleLong(md2header->skinHeight); + info.frameSize = LittleLong(md2header->frameSize); + info.numLODs = 1; + info.numSkins = LittleLong(md2header->numSkins); + info.numTexCoords = LittleLong(md2header->numTexCoords); + info.numVertices = LittleLong(md2header->numVertices); + info.numFrames = LittleLong(md2header->numFrames); + info.offsetSkins = LittleLong(md2header->offsetSkins); + info.offsetTexCoords = LittleLong(md2header->offsetTexCoords); + info.offsetFrames = LittleLong(md2header->offsetFrames); + info.offsetLODs = LittleLong(md2header->offsetEnd); // Doesn't exist. + lodInfo[0].numTriangles = LittleLong(md2header->numTriangles); + lodInfo[0].numGlCommands = LittleLong(md2header->numGlCommands); + lodInfo[0].offsetTriangles = LittleLong(md2header->offsetTriangles); + lodInfo[0].offsetGlCommands = LittleLong(md2header->offsetGlCommands); + info.offsetEnd = LittleLong(md2header->offsetEnd); + + if (info.offsetFrames + info.frameSize * info.numFrames > length) + { + Printf("LoadModel: Model '%s' file too short\n", path); + return false; + } + if (lodInfo[0].numGlCommands <= 0) + { + Printf("LoadModel: Model '%s' invalid NumGLCommands\n", path); + return false; + } + + skins = new FTextureID[info.numSkins]; + + for (i = 0; i < info.numSkins; i++) + { + skins[i] = LoadSkin(path, buffer + info.offsetSkins + i * 64); + } + + // The frames need to be unpacked. + md2_frames = (byte*)buffer + info.offsetFrames; + frames = new ModelFrame[info.numFrames]; + + for (i = 0, frame = frames; i < info.numFrames; i++, frame++) + { + md2_packedFrame_t *pfr = (md2_packedFrame_t *)(md2_frames + info.frameSize * i); + + memcpy(frame->name, pfr->name, sizeof(pfr->name)); + frame->vindex = UINT_MAX; + } + mLumpNum = lumpnum; + return true; +} + +//=========================================================================== +// +// FMD2Model::LoadGeometry +// +//=========================================================================== + +void FMD2Model::LoadGeometry() +{ + static int axis[3] = { VX, VY, VZ }; + byte *md2_frames; + FMemLump lumpdata = Wads.ReadLump(mLumpNum); + const char *buffer = (const char *)lumpdata.GetMem(); + + texCoords = new FTexCoord[info.numTexCoords]; + memcpy(texCoords, (byte*)buffer + info.offsetTexCoords, info.numTexCoords * sizeof(FTexCoord)); + + md2_frames = (byte*)buffer + info.offsetFrames; + framevtx = new ModelFrameVertexData[info.numFrames]; + ModelFrameVertexData *framev; + int i, k, c; + + for(i = 0, framev = framevtx; i < info.numFrames; i++, framev++) + { + md2_packedFrame_t *pfr = (md2_packedFrame_t *) (md2_frames + info.frameSize * i); + md2_triangleVertex_t *pVtx; + + framev->vertices = new DMDModelVertex[info.numVertices]; + framev->normals = new DMDModelVertex[info.numVertices]; + + // Translate each vertex. + for(k = 0, pVtx = pfr->vertices; k < info.numVertices; k++, pVtx++) + { + memcpy(framev->normals[k].xyz, + avertexnormals[pVtx->lightNormalIndex], sizeof(float) * 3); + + for(c = 0; c < 3; c++) + { + framev->vertices[k].xyz[axis[c]] = + (pVtx->vertex[c] * pfr->scale[c] + pfr->translate[c]); + } + } + } + + lods[0].triangles = new FTriangle[lodInfo[0].numTriangles]; + + int cnt = lodInfo[0].numTriangles; + memcpy(lods[0].triangles, buffer + lodInfo[0].offsetTriangles, sizeof(FTriangle) * cnt); + for (int j = 0; j < cnt; j++) + { + for (int k = 0; k < 3; k++) + { + lods[0].triangles[j].textureIndices[k] = LittleShort(lods[0].triangles[j].textureIndices[k]); + lods[0].triangles[j].vertexIndices[k] = LittleShort(lods[0].triangles[j].vertexIndices[k]); + } + } +} + +FMD2Model::~FMD2Model() +{ +} + diff --git a/src/gl/models/gl_models_md3.cpp b/src/gl/models/gl_models_md3.cpp new file mode 100644 index 000000000..b91473714 --- /dev/null +++ b/src/gl/models/gl_models_md3.cpp @@ -0,0 +1,393 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2006-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "w_wad.h" +#include "cmdlib.h" +#include "sc_man.h" +#include "m_crc32.h" + +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/models/gl_models.h" +#include "gl/textures/gl_material.h" +#include "gl/shaders/gl_shader.h" + +#define MAX_QPATH 64 + +//=========================================================================== +// +// decode the lat/lng normal to a 3 float normal +// +//=========================================================================== + +static void UnpackVector(unsigned short packed, float & nx, float & ny, float & nz) +{ + double lat = ( packed >> 8 ) & 0xff; + double lng = ( packed & 0xff ); + lat *= M_PI/128; + lng *= M_PI/128; + + nx = cos(lat) * sin(lng); + ny = sin(lat) * sin(lng); + nz = cos(lng); +} + +//=========================================================================== +// +// MD3 File structure +// +//=========================================================================== + +#pragma pack(4) +struct md3_header_t +{ + uint32_t Magic; + uint32_t Version; + char Name[MAX_QPATH]; + uint32_t Flags; + uint32_t Num_Frames; + uint32_t Num_Tags; + uint32_t Num_Surfaces; + uint32_t Num_Skins; + uint32_t Ofs_Frames; + uint32_t Ofs_Tags; + uint32_t Ofs_Surfaces; + uint32_t Ofs_Eof; +}; + +struct md3_surface_t +{ + uint32_t Magic; + char Name[MAX_QPATH]; + uint32_t Flags; + uint32_t Num_Frames; + uint32_t Num_Shaders; + uint32_t Num_Verts; + uint32_t Num_Triangles; + uint32_t Ofs_Triangles; + uint32_t Ofs_Shaders; + uint32_t Ofs_Texcoord; + uint32_t Ofs_XYZNormal; + uint32_t Ofs_End; +}; + +struct md3_triangle_t +{ + uint32_t vt_index[3]; +}; + +struct md3_shader_t +{ + char Name[MAX_QPATH]; + uint32_t index; +}; + +struct md3_texcoord_t +{ + float s, t; +}; + +struct md3_vertex_t +{ + short x, y, z, n; +}; + +struct md3_frame_t +{ + float min_Bounds[3]; + float max_Bounds[3]; + float localorigin[3]; + float radius; + char Name[16]; +}; +#pragma pack() + + +//=========================================================================== +// +// +// +//=========================================================================== + +bool FMD3Model::Load(const char * path, int lumpnum, const char * buffer, int length) +{ + md3_header_t * hdr = (md3_header_t *)buffer; + + numFrames = LittleLong(hdr->Num_Frames); + numTags = LittleLong(hdr->Num_Tags); + numSurfaces = LittleLong(hdr->Num_Surfaces); + + md3_frame_t * frm = (md3_frame_t*)(buffer + LittleLong(hdr->Ofs_Frames)); + + frames = new MD3Frame[numFrames]; + for (int i = 0; i < numFrames; i++) + { + strncpy(frames[i].Name, frm[i].Name, 16); + for (int j = 0; j < 3; j++) frames[i].origin[j] = frm[i].localorigin[j]; + } + + md3_surface_t * surf = (md3_surface_t*)(buffer + LittleLong(hdr->Ofs_Surfaces)); + + surfaces = new MD3Surface[numSurfaces]; + + for (int i = 0; i < numSurfaces; i++) + { + MD3Surface * s = &surfaces[i]; + md3_surface_t * ss = surf; + + surf = (md3_surface_t *)(((char*)surf) + LittleLong(surf->Ofs_End)); + + s->numSkins = LittleLong(ss->Num_Shaders); + s->numTriangles = LittleLong(ss->Num_Triangles); + s->numVertices = LittleLong(ss->Num_Verts); + + // copy shaders (skins) + md3_shader_t * shader = (md3_shader_t*)(((char*)ss) + LittleLong(ss->Ofs_Shaders)); + s->skins = new FTextureID[s->numSkins]; + + for (int i = 0; i < s->numSkins; i++) + { + // [BB] According to the MD3 spec, Name is supposed to include the full path. + s->skins[i] = LoadSkin("", shader[i].Name); + // [BB] Fall back and check if Name is relative. + if (!s->skins[i].isValid()) + s->skins[i] = LoadSkin(path, shader[i].Name); + } + } + mLumpNum = lumpnum; + return true; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FMD3Model::LoadGeometry() +{ + FMemLump lumpdata = Wads.ReadLump(mLumpNum); + const char *buffer = (const char *)lumpdata.GetMem(); + md3_header_t * hdr = (md3_header_t *)buffer; + md3_surface_t * surf = (md3_surface_t*)(buffer + LittleLong(hdr->Ofs_Surfaces)); + + for(int i=0;iOfs_End)); + + // copy triangle indices + md3_triangle_t * tris = (md3_triangle_t*)(((char*)ss)+LittleLong(ss->Ofs_Triangles)); + s->tris = new MD3Triangle[s->numTriangles]; + + for(int i=0;inumTriangles;i++) for (int j=0;j<3;j++) + { + s->tris[i].VertIndex[j]=LittleLong(tris[i].vt_index[j]); + } + + // Load texture coordinates + md3_texcoord_t * tc = (md3_texcoord_t*)(((char*)ss)+LittleLong(ss->Ofs_Texcoord)); + s->texcoords = new MD3TexCoord[s->numVertices]; + + for(int i=0;inumVertices;i++) + { + s->texcoords[i].s = tc[i].s; + s->texcoords[i].t = tc[i].t; + } + + // Load vertices and texture coordinates + md3_vertex_t * vt = (md3_vertex_t*)(((char*)ss)+LittleLong(ss->Ofs_XYZNormal)); + s->vertices = new MD3Vertex[s->numVertices * numFrames]; + + for(int i=0;inumVertices * numFrames;i++) + { + s->vertices[i].x = LittleShort(vt[i].x)/64.f; + s->vertices[i].y = LittleShort(vt[i].y)/64.f; + s->vertices[i].z = LittleShort(vt[i].z)/64.f; + UnpackVector( LittleShort(vt[i].n), s->vertices[i].nx, s->vertices[i].ny, s->vertices[i].nz); + } + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FMD3Model::BuildVertexBuffer() +{ + if (mVBuf == nullptr) + { + LoadGeometry(); + + unsigned int vbufsize = 0; + unsigned int ibufsize = 0; + + for (int i = 0; i < numSurfaces; i++) + { + MD3Surface * surf = &surfaces[i]; + vbufsize += numFrames * surf->numVertices; + ibufsize += 3 * surf->numTriangles; + } + + mVBuf = new FModelVertexBuffer(true, numFrames == 1); + FModelVertex *vertptr = mVBuf->LockVertexBuffer(vbufsize); + unsigned int *indxptr = mVBuf->LockIndexBuffer(ibufsize); + + assert(vertptr != nullptr && indxptr != nullptr); + + unsigned int vindex = 0, iindex = 0; + + for (int i = 0; i < numSurfaces; i++) + { + MD3Surface * surf = &surfaces[i]; + + surf->vindex = vindex; + surf->iindex = iindex; + for (int j = 0; j < numFrames * surf->numVertices; j++) + { + MD3Vertex* vert = surf->vertices + j; + + FModelVertex *bvert = &vertptr[vindex++]; + + int tc = j % surf->numVertices; + bvert->Set(vert->x, vert->z, vert->y, surf->texcoords[tc].s, surf->texcoords[tc].t); + bvert->SetNormal(vert->nx, vert->nz, vert->ny); + } + + for (int k = 0; k < surf->numTriangles; k++) + { + for (int l = 0; l < 3; l++) + { + indxptr[iindex++] = surf->tris[k].VertIndex[l]; + } + } + surf->UnloadGeometry(); + } + mVBuf->UnlockVertexBuffer(); + mVBuf->UnlockIndexBuffer(); + } +} + + +//=========================================================================== +// +// for skin precaching +// +//=========================================================================== + +void FMD3Model::AddSkins(BYTE *hitlist) +{ + for (int i = 0; i < numSurfaces; i++) + { + if (curSpriteMDLFrame->surfaceskinIDs[curMDLIndex][i].isValid()) + { + hitlist[curSpriteMDLFrame->surfaceskinIDs[curMDLIndex][i].GetIndex()] |= FTexture::TEX_Flat; + } + + MD3Surface * surf = &surfaces[i]; + for (int j = 0; j < surf->numSkins; j++) + { + if (surf->skins[j].isValid()) + { + hitlist[surf->skins[j].GetIndex()] |= FTexture::TEX_Flat; + } + } + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +int FMD3Model::FindFrame(const char * name) +{ + for (int i=0;i=numFrames || frameno2>=numFrames) return; + + gl_RenderState.SetInterpolationFactor((float)inter); + for(int i=0;isurfaceskinIDs[curMDLIndex][i].isValid()) + { + surfaceSkin = TexMan(curSpriteMDLFrame->surfaceskinIDs[curMDLIndex][i]); + } + else if(surf->numSkins > 0 && surf->skins[0].isValid()) + { + surfaceSkin = TexMan(surf->skins[0]); + } + + if (!surfaceSkin) return; + } + + FMaterial * tex = FMaterial::ValidateTexture(surfaceSkin, false); + + gl_RenderState.SetMaterial(tex, CLAMP_NONE, translation, -1, false); + + gl_RenderState.Apply(); + mVBuf->SetupFrame(surf->vindex + frameno * surf->numVertices, surf->vindex + frameno2 * surf->numVertices, surf->numVertices); + glDrawElements(GL_TRIANGLES, surf->numTriangles * 3, GL_UNSIGNED_INT, (void*)(intptr_t)(surf->iindex * sizeof(unsigned int))); + } + gl_RenderState.SetInterpolationFactor(0.f); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FMD3Model::~FMD3Model() +{ + if (frames) delete [] frames; + if (surfaces) delete [] surfaces; + frames = nullptr; + surfaces = nullptr; +} diff --git a/src/gl/models/gl_voxels.cpp b/src/gl/models/gl_voxels.cpp new file mode 100644 index 000000000..6e84bd7ab --- /dev/null +++ b/src/gl/models/gl_voxels.cpp @@ -0,0 +1,450 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2010-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_voxels.cpp +** +** Voxel management +** +**/ + +#include "gl/system/gl_system.h" +#include "w_wad.h" +#include "cmdlib.h" +#include "sc_man.h" +#include "m_crc32.h" +#include "c_console.h" +#include "g_game.h" +#include "doomstat.h" +#include "g_level.h" +#include "colormatcher.h" +#include "textures/bitmap.h" +//#include "gl/gl_intern.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/models/gl_models.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_geometric.h" +#include "gl/utility/gl_convert.h" +#include "gl/renderer/gl_renderstate.h" + + +//=========================================================================== +// +// Creates a 16x16 texture from the palette so that we can +// use the existing palette manipulation code to render the voxel +// Otherwise all shaders had to be duplicated and the non-shader code +// would be a lot less efficient. +// +//=========================================================================== + +class FVoxelTexture : public FTexture +{ +public: + + FVoxelTexture(FVoxel *voxel); + ~FVoxelTexture(); + const BYTE *GetColumn (unsigned int column, const Span **spans_out); + const BYTE *GetPixels (); + void Unload (); + + int CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf); + bool UseBasePalette() { return false; } + +protected: + FVoxel *SourceVox; + BYTE *Pixels; + +}; + +//=========================================================================== +// +// +// +//=========================================================================== + +FVoxelTexture::FVoxelTexture(FVoxel *vox) +{ + SourceVox = vox; + Width = 16; + Height = 16; + WidthBits = 4; + HeightBits = 4; + WidthMask = 15; + Pixels = NULL; + gl_info.bNoFilter = true; + gl_info.bNoCompress = true; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FVoxelTexture::~FVoxelTexture() +{ +} + +const BYTE *FVoxelTexture::GetColumn (unsigned int column, const Span **spans_out) +{ + // not needed + return NULL; +} + +const BYTE *FVoxelTexture::GetPixels () +{ + // GetPixels gets called when a translated palette is used so we still need to implement it here. + if (Pixels == NULL) + { + Pixels = new BYTE[256]; + + BYTE *pp = SourceVox->Palette; + + if(pp != NULL) + { + for(int i=0;i<256;i++, pp+=3) + { + PalEntry pe; + pe.r = (pp[0] << 2) | (pp[0] >> 4); + pe.g = (pp[1] << 2) | (pp[1] >> 4); + pe.b = (pp[2] << 2) | (pp[2] >> 4); + Pixels[i] = ColorMatcher.Pick(pe); + } + } + else + { + for(int i=0;i<256;i++, pp+=3) + { + Pixels[i] = (BYTE)i; + } + } + } + return Pixels; +} + +void FVoxelTexture::Unload () +{ + if (Pixels != NULL) + { + delete[] Pixels; + Pixels = NULL; + } +} + +//=========================================================================== +// +// FVoxelTexture::CopyTrueColorPixels +// +// This creates a dummy 16x16 paletted bitmap and converts that using the +// voxel palette +// +//=========================================================================== + +int FVoxelTexture::CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf) +{ + PalEntry pe[256]; + BYTE bitmap[256]; + BYTE *pp = SourceVox->Palette; + + if(pp != NULL) + { + for(int i=0;i<256;i++, pp+=3) + { + bitmap[i] = (BYTE)i; + pe[i].r = (pp[0] << 2) | (pp[0] >> 4); + pe[i].g = (pp[1] << 2) | (pp[1] >> 4); + pe[i].b = (pp[2] << 2) | (pp[2] >> 4); + pe[i].a = 255; + } + } + else + { + for(int i=0;i<256;i++, pp+=3) + { + bitmap[i] = (BYTE)i; + pe[i] = GPalette.BaseColors[i]; + pe[i].a = 255; + } + } + bmp->CopyPixelData(x, y, bitmap, Width, Height, 1, 16, rotate, pe, inf); + return 0; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FVoxelModel::FVoxelModel(FVoxel *voxel, bool owned) +{ + mVoxel = voxel; + mOwningVoxel = owned; + mPalette = TexMan.AddTexture(new FVoxelTexture(voxel)); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FVoxelModel::~FVoxelModel() +{ + if (mOwningVoxel) delete mVoxel; +} + + +//=========================================================================== +// +// +// +//=========================================================================== + +unsigned int FVoxelModel::AddVertex(FModelVertex &vert, FVoxelMap &check) +{ + unsigned int index = check[vert]; + if (index == 0xffffffff) + { + index = check[vert] =mVertices.Push(vert); + } + return index; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FVoxelModel::AddFace(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3, int x4, int y4, int z4, BYTE col, FVoxelMap &check) +{ + float PivotX = mVoxel->Mips[0].Pivot.X; + float PivotY = mVoxel->Mips[0].Pivot.Y; + float PivotZ = mVoxel->Mips[0].Pivot.Z; + int h = mVoxel->Mips[0].SizeZ; + FModelVertex vert; + unsigned int indx[4]; + + vert.packedNormal = 0; // currently this is not being used for voxels. + vert.u = (((col & 15) * 255 / 16) + 7) / 255.f; + vert.v = (((col / 16) * 255 / 16) + 7) / 255.f; + + vert.x = x1 - PivotX; + vert.z = -y1 + PivotY; + vert.y = -z1 + PivotZ; + indx[0] = AddVertex(vert, check); + + vert.x = x2 - PivotX; + vert.z = -y2 + PivotY; + vert.y = -z2 + PivotZ; + indx[1] = AddVertex(vert, check); + + vert.x = x4 - PivotX; + vert.z = -y4 + PivotY; + vert.y = -z4 + PivotZ; + indx[2] = AddVertex(vert, check); + + vert.x = x3 - PivotX; + vert.z = -y3 + PivotY; + vert.y = -z3 + PivotZ; + indx[3] = AddVertex(vert, check); + + + mIndices.Push(indx[0]); + mIndices.Push(indx[1]); + mIndices.Push(indx[3]); + mIndices.Push(indx[1]); + mIndices.Push(indx[2]); + mIndices.Push(indx[3]); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FVoxelModel::MakeSlabPolys(int x, int y, kvxslab_t *voxptr, FVoxelMap &check) +{ + const BYTE *col = voxptr->col; + int zleng = voxptr->zleng; + int ztop = voxptr->ztop; + int cull = voxptr->backfacecull; + + if (cull & 16) + { + AddFace(x, y, ztop, x+1, y, ztop, x, y+1, ztop, x+1, y+1, ztop, *col, check); + } + int z = ztop; + while (z < ztop+zleng) + { + int c = 0; + while (z+c < ztop+zleng && col[c] == col[0]) c++; + + if (cull & 1) + { + AddFace(x, y, z, x, y+1, z, x, y, z+c, x, y+1, z+c, *col, check); + } + if (cull & 2) + { + AddFace(x+1, y+1, z, x+1, y, z, x+1, y+1, z+c, x+1, y, z+c, *col, check); + } + if (cull & 4) + { + AddFace(x+1, y, z, x, y, z, x+1, y, z+c, x, y, z+c, *col, check); + } + if (cull & 8) + { + AddFace(x, y+1, z, x+1, y+1, z, x, y+1, z+c, x+1, y+1, z+c, *col, check); + } + z+=c; + col+=c; + } + if (cull & 32) + { + int z = ztop+zleng-1; + AddFace(x+1, y, z+1, x, y, z+1, x+1, y+1, z+1, x, y+1, z+1, voxptr->col[zleng-1], check); + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FVoxelModel::Initialize() +{ + FVoxelMap check; + FVoxelMipLevel *mip = &mVoxel->Mips[0]; + for (int x = 0; x < mip->SizeX; x++) + { + BYTE *slabxoffs = &mip->SlabData[mip->OffsetX[x]]; + short *xyoffs = &mip->OffsetXY[x * (mip->SizeY + 1)]; + for (int y = 0; y < mip->SizeY; y++) + { + kvxslab_t *voxptr = (kvxslab_t *)(slabxoffs + xyoffs[y]); + kvxslab_t *voxend = (kvxslab_t *)(slabxoffs + xyoffs[y+1]); + for (; voxptr < voxend; voxptr = (kvxslab_t *)((BYTE *)voxptr + voxptr->zleng + 3)) + { + MakeSlabPolys(x, y, voxptr, check); + } + } + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FVoxelModel::BuildVertexBuffer() +{ + if (mVBuf == NULL) + { + Initialize(); + + mVBuf = new FModelVertexBuffer(true, true); + FModelVertex *vertptr = mVBuf->LockVertexBuffer(mVertices.Size()); + unsigned int *indxptr = mVBuf->LockIndexBuffer(mIndices.Size()); + + memcpy(vertptr, &mVertices[0], sizeof(FModelVertex)* mVertices.Size()); + memcpy(indxptr, &mIndices[0], sizeof(unsigned int)* mIndices.Size()); + + mVBuf->UnlockVertexBuffer(); + mVBuf->UnlockIndexBuffer(); + mNumIndices = mIndices.Size(); + + // delete our temporary buffers + mVertices.Clear(); + mIndices.Clear(); + mVertices.ShrinkToFit(); + mIndices.ShrinkToFit(); + } +} + + +//=========================================================================== +// +// for skin precaching +// +//=========================================================================== + +void FVoxelModel::AddSkins(BYTE *hitlist) +{ + hitlist[mPalette.GetIndex()] |= FTexture::TEX_Flat; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +bool FVoxelModel::Load(const char * fn, int lumpnum, const char * buffer, int length) +{ + return false; // not needed +} + +//=========================================================================== +// +// Voxels don't have frames so always return 0 +// +//=========================================================================== + +int FVoxelModel::FindFrame(const char * name) +{ + return 0; +} + +//=========================================================================== +// +// Voxels need aspect ratio correction according to the current map's setting +// +//=========================================================================== + +float FVoxelModel::getAspectFactor() +{ + return glset.pixelstretch; +} + +//=========================================================================== +// +// Voxels never interpolate between frames, they only have one. +// +//=========================================================================== + +void FVoxelModel::RenderFrame(FTexture * skin, int frame, int frame2, double inter, int translation) +{ + FMaterial * tex = FMaterial::ValidateTexture(skin, false); + gl_RenderState.SetMaterial(tex, CLAMP_NOFILTER, translation, -1, false); + + gl_RenderState.Apply(); + mVBuf->SetupFrame(0, 0, 0); + glDrawElements(GL_TRIANGLES, mNumIndices, GL_UNSIGNED_INT, (void*)(intptr_t)0); +} + diff --git a/src/gl/models/tab_anorms.h b/src/gl/models/tab_anorms.h new file mode 100644 index 000000000..46467b460 --- /dev/null +++ b/src/gl/models/tab_anorms.h @@ -0,0 +1,489 @@ +#ifdef WIN32 +#pragma warning(disable:4305) +#endif + +{ +-0.525731, 0.000000, 0.850651}, + +{ +-0.442863, 0.238856, 0.864188}, + +{ +-0.295242, 0.000000, 0.955423}, + +{ +-0.309017, 0.500000, 0.809017}, + +{ +-0.162460, 0.262866, 0.951056}, + +{ +0.000000, 0.000000, 1.000000}, + +{ +0.000000, 0.850651, 0.525731}, + +{ +-0.147621, 0.716567, 0.681718}, + +{ +0.147621, 0.716567, 0.681718}, + +{ +0.000000, 0.525731, 0.850651}, + +{ +0.309017, 0.500000, 0.809017}, + +{ +0.525731, 0.000000, 0.850651}, + +{ +0.295242, 0.000000, 0.955423}, + +{ +0.442863, 0.238856, 0.864188}, + +{ +0.162460, 0.262866, 0.951056}, + +{ +-0.681718, 0.147621, 0.716567}, + +{ +-0.809017, 0.309017, 0.500000}, + +{ +-0.587785, 0.425325, 0.688191}, + +{ +-0.850651, 0.525731, 0.000000}, + +{ +-0.864188, 0.442863, 0.238856}, + +{ +-0.716567, 0.681718, 0.147621}, + +{ +-0.688191, 0.587785, 0.425325}, + +{ +-0.500000, 0.809017, 0.309017}, + +{ +-0.238856, 0.864188, 0.442863}, + +{ +-0.425325, 0.688191, 0.587785}, + +{ +-0.716567, 0.681718, -0.147621}, + +{ +-0.500000, 0.809017, -0.309017}, + +{ +-0.525731, 0.850651, 0.000000}, + +{ +0.000000, 0.850651, -0.525731}, + +{ +-0.238856, 0.864188, -0.442863}, + +{ +0.000000, 0.955423, -0.295242}, + +{ +-0.262866, 0.951056, -0.162460}, + +{ +0.000000, 1.000000, 0.000000}, + +{ +0.000000, 0.955423, 0.295242}, + +{ +-0.262866, 0.951056, 0.162460}, + +{ +0.238856, 0.864188, 0.442863}, + +{ +0.262866, 0.951056, 0.162460}, + +{ +0.500000, 0.809017, 0.309017}, + +{ +0.238856, 0.864188, -0.442863}, + +{ +0.262866, 0.951056, -0.162460}, + +{ +0.500000, 0.809017, -0.309017}, + +{ +0.850651, 0.525731, 0.000000}, + +{ +0.716567, 0.681718, 0.147621}, + +{ +0.716567, 0.681718, -0.147621}, + +{ +0.525731, 0.850651, 0.000000}, + +{ +0.425325, 0.688191, 0.587785}, + +{ +0.864188, 0.442863, 0.238856}, + +{ +0.688191, 0.587785, 0.425325}, + +{ +0.809017, 0.309017, 0.500000}, + +{ +0.681718, 0.147621, 0.716567}, + +{ +0.587785, 0.425325, 0.688191}, + +{ +0.955423, 0.295242, 0.000000}, + +{ +1.000000, 0.000000, 0.000000}, + +{ +0.951056, 0.162460, 0.262866}, + +{ +0.850651, -0.525731, 0.000000}, + +{ +0.955423, -0.295242, 0.000000}, + +{ +0.864188, -0.442863, 0.238856}, + +{ +0.951056, -0.162460, 0.262866}, + +{ +0.809017, -0.309017, 0.500000}, + +{ +0.681718, -0.147621, 0.716567}, + +{ +0.850651, 0.000000, 0.525731}, + +{ +0.864188, 0.442863, -0.238856}, + +{ +0.809017, 0.309017, -0.500000}, + +{ +0.951056, 0.162460, -0.262866}, + +{ +0.525731, 0.000000, -0.850651}, + +{ +0.681718, 0.147621, -0.716567}, + +{ +0.681718, -0.147621, -0.716567}, + +{ +0.850651, 0.000000, -0.525731}, + +{ +0.809017, -0.309017, -0.500000}, + +{ +0.864188, -0.442863, -0.238856}, + +{ +0.951056, -0.162460, -0.262866}, + +{ +0.147621, 0.716567, -0.681718}, + +{ +0.309017, 0.500000, -0.809017}, + +{ +0.425325, 0.688191, -0.587785}, + +{ +0.442863, 0.238856, -0.864188}, + +{ +0.587785, 0.425325, -0.688191}, + +{ +0.688191, 0.587785, -0.425325}, + +{ +-0.147621, 0.716567, -0.681718}, + +{ +-0.309017, 0.500000, -0.809017}, + +{ +0.000000, 0.525731, -0.850651}, + +{ +-0.525731, 0.000000, -0.850651}, + +{ +-0.442863, 0.238856, -0.864188}, + +{ +-0.295242, 0.000000, -0.955423}, + +{ +-0.162460, 0.262866, -0.951056}, + +{ +0.000000, 0.000000, -1.000000}, + +{ +0.295242, 0.000000, -0.955423}, + +{ +0.162460, 0.262866, -0.951056}, + +{ +-0.442863, -0.238856, -0.864188}, + +{ +-0.309017, -0.500000, -0.809017}, + +{ +-0.162460, -0.262866, -0.951056}, + +{ +0.000000, -0.850651, -0.525731}, + +{ +-0.147621, -0.716567, -0.681718}, + +{ +0.147621, -0.716567, -0.681718}, + +{ +0.000000, -0.525731, -0.850651}, + +{ +0.309017, -0.500000, -0.809017}, + +{ +0.442863, -0.238856, -0.864188}, + +{ +0.162460, -0.262866, -0.951056}, + +{ +0.238856, -0.864188, -0.442863}, + +{ +0.500000, -0.809017, -0.309017}, + +{ +0.425325, -0.688191, -0.587785}, + +{ +0.716567, -0.681718, -0.147621}, + +{ +0.688191, -0.587785, -0.425325}, + +{ +0.587785, -0.425325, -0.688191}, + +{ +0.000000, -0.955423, -0.295242}, + +{ +0.000000, -1.000000, 0.000000}, + +{ +0.262866, -0.951056, -0.162460}, + +{ +0.000000, -0.850651, 0.525731}, + +{ +0.000000, -0.955423, 0.295242}, + +{ +0.238856, -0.864188, 0.442863}, + +{ +0.262866, -0.951056, 0.162460}, + +{ +0.500000, -0.809017, 0.309017}, + +{ +0.716567, -0.681718, 0.147621}, + +{ +0.525731, -0.850651, 0.000000}, + +{ +-0.238856, -0.864188, -0.442863}, + +{ +-0.500000, -0.809017, -0.309017}, + +{ +-0.262866, -0.951056, -0.162460}, + +{ +-0.850651, -0.525731, 0.000000}, + +{ +-0.716567, -0.681718, -0.147621}, + +{ +-0.716567, -0.681718, 0.147621}, + +{ +-0.525731, -0.850651, 0.000000}, + +{ +-0.500000, -0.809017, 0.309017}, + +{ +-0.238856, -0.864188, 0.442863}, + +{ +-0.262866, -0.951056, 0.162460}, + +{ +-0.864188, -0.442863, 0.238856}, + +{ +-0.809017, -0.309017, 0.500000}, + +{ +-0.688191, -0.587785, 0.425325}, + +{ +-0.681718, -0.147621, 0.716567}, + +{ +-0.442863, -0.238856, 0.864188}, + +{ +-0.587785, -0.425325, 0.688191}, + +{ +-0.309017, -0.500000, 0.809017}, + +{ +-0.147621, -0.716567, 0.681718}, + +{ +-0.425325, -0.688191, 0.587785}, + +{ +-0.162460, -0.262866, 0.951056}, + +{ +0.442863, -0.238856, 0.864188}, + +{ +0.162460, -0.262866, 0.951056}, + +{ +0.309017, -0.500000, 0.809017}, + +{ +0.147621, -0.716567, 0.681718}, + +{ +0.000000, -0.525731, 0.850651}, + +{ +0.425325, -0.688191, 0.587785}, + +{ +0.587785, -0.425325, 0.688191}, + +{ +0.688191, -0.587785, 0.425325}, + +{ +-0.955423, 0.295242, 0.000000}, + +{ +-0.951056, 0.162460, 0.262866}, + +{ +-1.000000, 0.000000, 0.000000}, + +{ +-0.850651, 0.000000, 0.525731}, + +{ +-0.955423, -0.295242, 0.000000}, + +{ +-0.951056, -0.162460, 0.262866}, + +{ +-0.864188, 0.442863, -0.238856}, + +{ +-0.951056, 0.162460, -0.262866}, + +{ +-0.809017, 0.309017, -0.500000}, + +{ +-0.864188, -0.442863, -0.238856}, + +{ +-0.951056, -0.162460, -0.262866}, + +{ +-0.809017, -0.309017, -0.500000}, + +{ +-0.681718, 0.147621, -0.716567}, + +{ +-0.681718, -0.147621, -0.716567}, + +{ +-0.850651, 0.000000, -0.525731}, + +{ +-0.688191, 0.587785, -0.425325}, + +{ +-0.587785, 0.425325, -0.688191}, + +{ +-0.425325, 0.688191, -0.587785}, + +{ +-0.425325, -0.688191, -0.587785}, + +{ +-0.587785, -0.425325, -0.688191}, + +{ +-0.688191, -0.587785, -0.425325}, diff --git a/src/gl/renderer/gl_2ddrawer.cpp b/src/gl/renderer/gl_2ddrawer.cpp new file mode 100644 index 000000000..ba78634a3 --- /dev/null +++ b/src/gl/renderer/gl_2ddrawer.cpp @@ -0,0 +1,489 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_2ddrawer.h +** Container class for drawing 2d graphics with a vertex buffer +** +**/ + +#include "gl/system/gl_system.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_2ddrawer.h" +#include "gl/textures/gl_material.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/textures/gl_translate.h" +#include "vectors.h" + +//========================================================================== +// +// +// +//========================================================================== + +int F2DDrawer::AddData(const F2DDrawer::DataGeneric *data) +{ + int addr = mData.Reserve(data->mLen); + memcpy(&mData[addr], data, data->mLen); + mLastLineCmd = -1; + return addr; +} + +//========================================================================== +// +// Draws a texture +// +//========================================================================== + +void F2DDrawer::AddTexture(FTexture *img, DrawParms &parms) +{ + double xscale = parms.destwidth / parms.texwidth; + double yscale = parms.destheight / parms.texheight; + double x = parms.x - parms.left * xscale; + double y = parms.y - parms.top * yscale; + double w = parms.destwidth; + double h = parms.destheight; + float u1, v1, u2, v2; + int light = 255; + + FMaterial * gltex = FMaterial::ValidateTexture(img, false); + if (gltex == nullptr) return; + + DataTexture dg; + + dg.mType = DrawTypeTexture; + dg.mLen = (sizeof(dg) + 7) & ~7; + dg.mVertCount = 4; + dg.mRenderStyle = parms.style; + dg.mMasked = !!parms.masked; + dg.mTexture = gltex; + + if (parms.colorOverlay && (parms.colorOverlay & 0xffffff) == 0) + { + // handle black overlays as reduced light. + light = 255 - APART(parms.colorOverlay); + parms.colorOverlay = 0; + } + dg.mVertIndex = (int)mVertices.Reserve(parms.colorOverlay == 0? 4 : 8); + dg.mColorOverlay = parms.colorOverlay; + dg.mTranslation = 0; + + if (!img->bHasCanvas) + { + if (!parms.alphaChannel) + { + if (parms.remap != NULL && !parms.remap->Inactive) + { + GLTranslationPalette * pal = static_cast(parms.remap->GetNative()); + if (pal) dg.mTranslation = -pal->GetIndex(); + } + } + dg.mAlphaTexture = !!(parms.style.Flags & STYLEF_RedIsAlpha); + u1 = gltex->GetUL(); + v1 = gltex->GetVT(); + u2 = gltex->GetUR(); + v2 = gltex->GetVB(); + + } + else + { + dg.mAlphaTexture = false; + u1 = 0.f; + v1 = 1.f; + u2 = 1.f; + v2 = 0.f; + } + + if (parms.flipX) + std::swap(u1, u2); + + + if (parms.windowleft > 0 || parms.windowright < parms.texwidth) + { + double wi = MIN(parms.windowright, parms.texwidth); + x += parms.windowleft * xscale; + w -= (parms.texwidth - wi + parms.windowleft) * xscale; + + u1 = float(u1 + parms.windowleft / parms.texwidth); + u2 = float(u2 - (parms.texwidth - wi) / parms.texwidth); + } + + PalEntry color; + if (parms.style.Flags & STYLEF_ColorIsFixed) + { + color = parms.fillcolor; + std::swap(color.r, color.b); + } + else + { + color = PalEntry(light, light, light); + } + color.a = (BYTE)(parms.Alpha * 255); + + // scissor test doesn't use the current viewport for the coordinates, so use real screen coordinates + dg.mScissor[0] = GLRenderer->ScreenToWindowX(parms.lclip); + dg.mScissor[1] = GLRenderer->ScreenToWindowY(parms.dclip); + dg.mScissor[2] = GLRenderer->ScreenToWindowX(parms.rclip) - dg.mScissor[0]; + dg.mScissor[3] = GLRenderer->ScreenToWindowY(parms.uclip) - dg.mScissor[1]; + + FSimpleVertex *ptr = &mVertices[dg.mVertIndex]; + ptr->Set(x, y, 0, u1, v1, color); ptr++; + ptr->Set(x, y + h, 0, u1, v2, color); ptr++; + ptr->Set(x + w, y, 0, u2, v1, color); ptr++; + ptr->Set(x + w, y + h, 0, u2, v2, color); ptr++; + if (parms.colorOverlay != 0) + { + color = parms.colorOverlay; + std::swap(color.r, color.b); + ptr->Set(x, y, 0, u1, v1, color); ptr++; + ptr->Set(x, y + h, 0, u1, v2, color); ptr++; + ptr->Set(x + w, y, 0, u2, v1, color); ptr++; + ptr->Set(x + w, y + h, 0, u2, v2, color); ptr++; + dg.mVertCount = 8; + } + AddData(&dg); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::AddPoly(FTexture *texture, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel) +{ + FMaterial *gltexture = FMaterial::ValidateTexture(texture, false); + + if (gltexture == nullptr) + { + return; + } + DataSimplePoly poly; + + poly.mType = DrawTypePoly; + poly.mLen = (sizeof(poly) + 7) & ~7; + poly.mTexture = gltexture; + poly.mColormap = colormap; + poly.mLightLevel = lightlevel; + poly.mVertCount = npoints; + poly.mVertIndex = (int)mVertices.Reserve(npoints); + + bool dorotate = rotation != 0; + + float cosrot = cos(rotation.Radians()); + float sinrot = sin(rotation.Radians()); + + float uscale = float(1.f / (texture->GetScaledWidth() * scalex)); + float vscale = float(1.f / (texture->GetScaledHeight() * scaley)); + if (texture->bHasCanvas) + { + vscale = 0 - vscale; + } + float ox = float(originx); + float oy = float(originy); + + for (int i = 0; i < npoints; ++i) + { + float u = points[i].X - 0.5f - ox; + float v = points[i].Y - 0.5f - oy; + if (dorotate) + { + float t = u; + u = t * cosrot - v * sinrot; + v = v * cosrot + t * sinrot; + } + mVertices[poly.mVertIndex+i].Set(points[i].X, points[i].Y, 0, u*uscale, v*vscale); + } + AddData(&poly); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void F2DDrawer::AddDim(PalEntry color, float damount, int x1, int y1, int w, int h) +{ + color.a = uint8_t(damount * 255); + std::swap(color.r, color.b); + + DataGeneric dg; + + dg.mType = DrawTypeDim; + dg.mLen = (sizeof(dg) + 7) & ~7; + dg.mVertCount = 4; + dg.mVertIndex = (int)mVertices.Reserve(4); + FSimpleVertex *ptr = &mVertices[dg.mVertIndex]; + ptr->Set(x1, y1, 0, 0, 0, color); ptr++; + ptr->Set(x1, y1 + h, 0, 0, 0, color); ptr++; + ptr->Set(x1 + w, y1 + h, 0, 0, 0, color); ptr++; + ptr->Set(x1 + w, y1, 0, 0, 0, color); ptr++; + AddData(&dg); +} + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::AddClear(int left, int top, int right, int bottom, int palcolor, uint32 color) +{ + PalEntry p = palcolor == -1 || color != 0 ? (PalEntry)color : GPalette.BaseColors[palcolor]; + AddDim(p, 1.f, left, top, right - left, bottom - top); +} + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::AddFlatFill(int left, int top, int right, int bottom, FTexture *src, bool local_origin) +{ + float fU1, fU2, fV1, fV2; + + FMaterial *gltexture = FMaterial::ValidateTexture(src, false); + + if (!gltexture) return; + + DataFlatFill dg; + + dg.mType = DrawTypeFlatFill; + dg.mLen = (sizeof(dg) + 7) & ~7; + dg.mVertCount = 4; + dg.mVertIndex = (int)mVertices.Reserve(4); + dg.mTexture = gltexture; + + // scaling is not used here. + if (!local_origin) + { + fU1 = float(left) / src->GetWidth(); + fV1 = float(top) / src->GetHeight(); + fU2 = float(right) / src->GetWidth(); + fV2 = float(bottom) / src->GetHeight(); + } + else + { + fU1 = 0; + fV1 = 0; + fU2 = float(right - left) / src->GetWidth(); + fV2 = float(bottom - top) / src->GetHeight(); + } + FSimpleVertex *ptr = &mVertices[dg.mVertIndex]; + ptr->Set(left, top, 0, fU1, fV1); ptr++; + ptr->Set(left, bottom, 0, fU1, fV2); ptr++; + ptr->Set(right, top, 0, fU2, fV1); ptr++; + ptr->Set(right, bottom, 0, fU2, fV2); ptr++; + AddData(&dg); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::AddLine(int x1, int y1, int x2, int y2, int palcolor, uint32 color) +{ + PalEntry p = color ? (PalEntry)color : GPalette.BaseColors[palcolor]; + p.a = 255; + std::swap(p.r, p.b); + + DataGeneric dg; + + dg.mType = DrawTypeLine; + dg.mLen = (sizeof(dg) + 7) & ~7; + dg.mVertCount = 2; + dg.mVertIndex = (int)mVertices.Reserve(2); + mVertices[dg.mVertIndex].Set(x1, y1, 0, 0, 0, p); + mVertices[dg.mVertIndex+1].Set(x2, y2, 0, 0, 0, p); + + // Test if we can batch multiple line commands + if (mLastLineCmd == -1) + { + mLastLineCmd = AddData(&dg); + } + else + { + DataGeneric *dg = (DataGeneric *)&mData[mLastLineCmd]; + dg->mVertCount += 2; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::AddPixel(int x1, int y1, int palcolor, uint32 color) +{ + PalEntry p = color ? (PalEntry)color : GPalette.BaseColors[palcolor]; + p.a = 255; + std::swap(p.r, p.b); + + DataGeneric dg; + + dg.mType = DrawTypePixel; + dg.mLen = (sizeof(dg) + 7) & ~7; + dg.mVertCount = 2; + dg.mVertIndex = (int)mVertices.Reserve(1); + mVertices[dg.mVertIndex].Set(x1, y1, 0, 0, 0, p); + AddData(&dg); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void F2DDrawer::Draw() +{ + F2DDrawer::EDrawType lasttype = DrawTypeTexture; + + if (mData.Size() == 0) return; + SBYTE savedlightmode = glset.lightmode; + // lightmode is only relevant for automap subsectors, + // but We cannot use the software light mode here because it doesn't properly calculate the light for 2D rendering. + if (glset.lightmode == 8) glset.lightmode = 0; + + set(&mVertices[0], mVertices.Size()); + for (unsigned i = 0; i < mData.Size();) + { + DataGeneric *dg = (DataGeneric *)&mData[i]; + // DrawTypePoly may not use the color part of the vertex buffer because it needs to use gl_SetColor to produce proper output. + if (lasttype == DrawTypePoly && dg->mType != DrawTypePoly) + { + gl_RenderState.ResetColor(); // this is needed to reset the desaturation. + EnableColorArray(true); + } + else if (lasttype != DrawTypePoly && dg->mType == DrawTypePoly) + { + EnableColorArray(false); + } + lasttype = dg->mType; + + switch (dg->mType) + { + default: + break; + + case DrawTypeTexture: + { + DataTexture *dt = static_cast(dg); + + gl_SetRenderStyle(dt->mRenderStyle, !dt->mMasked, false); + gl_RenderState.SetMaterial(dt->mTexture, CLAMP_XY_NOMIP, dt->mTranslation, -1, dt->mAlphaTexture); + if (dt->mTexture->tex->bHasCanvas) gl_RenderState.SetTextureMode(TM_OPAQUE); + + glEnable(GL_SCISSOR_TEST); + glScissor(dt->mScissor[0], dt->mScissor[1], dt->mScissor[2], dt->mScissor[3]); + + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.Apply(); + + glDrawArrays(GL_TRIANGLE_STRIP, dt->mVertIndex, 4); + + gl_RenderState.BlendEquation(GL_FUNC_ADD); + if (dt->mVertCount > 4) + { + gl_RenderState.SetTextureMode(TM_MASK); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, dt->mVertIndex + 4, 4); + } + + const auto &viewport = GLRenderer->mScreenViewport; + glScissor(viewport.left, viewport.top, viewport.width, viewport.height); + glDisable(GL_SCISSOR_TEST); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.SetTextureMode(TM_MODULATE); + break; + } + + case DrawTypePoly: + { + DataSimplePoly *dsp = static_cast(dg); + + FColormap cm; + cm = dsp->mColormap; + gl_SetColor(dsp->mLightLevel, 0, cm, 1.f); + gl_RenderState.SetMaterial(dsp->mTexture, CLAMP_NONE, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_FAN, dsp->mVertIndex, dsp->mVertCount); + break; + } + + case DrawTypeFlatFill: + { + DataFlatFill *dff = static_cast(dg); + gl_RenderState.SetMaterial(dff->mTexture, CLAMP_NONE, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, dg->mVertIndex, dg->mVertCount); + break; + } + + case DrawTypeDim: + gl_RenderState.EnableTexture(false); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.AlphaFunc(GL_GREATER, 0); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_FAN, dg->mVertIndex, dg->mVertCount); + gl_RenderState.EnableTexture(true); + break; + + case DrawTypeLine: + gl_RenderState.EnableTexture(false); + gl_RenderState.Apply(); + glDrawArrays(GL_LINES, dg->mVertIndex, dg->mVertCount); + gl_RenderState.EnableTexture(true); + break; + + case DrawTypePixel: + gl_RenderState.EnableTexture(false); + gl_RenderState.Apply(); + glDrawArrays(GL_POINTS, dg->mVertIndex, dg->mVertCount); + gl_RenderState.EnableTexture(true); + break; + + } + i += dg->mLen; + } + gl_RenderState.SetVertexBuffer(GLRenderer->mVBO); + glset.lightmode = savedlightmode; +} + +void F2DDrawer::Clear() +{ + mVertices.Clear(); + mData.Clear(); +} diff --git a/src/gl/renderer/gl_2ddrawer.h b/src/gl/renderer/gl_2ddrawer.h new file mode 100644 index 000000000..8c27f13d8 --- /dev/null +++ b/src/gl/renderer/gl_2ddrawer.h @@ -0,0 +1,74 @@ +#ifndef __2DDRAWER_H +#define __2DDRAWER_H + +#include "tarray.h" +#include "gl/data/gl_vertexbuffer.h" + +class F2DDrawer : public FSimpleVertexBuffer +{ + enum EDrawType + { + DrawTypeTexture, + DrawTypeDim, + DrawTypeFlatFill, + DrawTypePoly, + DrawTypeLine, + DrawTypePixel + }; + + struct DataGeneric + { + EDrawType mType; + uint32_t mLen; + int mVertIndex; + int mVertCount; + }; + + struct DataTexture : public DataGeneric + { + FMaterial *mTexture; + int mScissor[4]; + uint32_t mColorOverlay; + int mTranslation; + FRenderStyle mRenderStyle; + bool mMasked; + bool mAlphaTexture; + }; + + struct DataFlatFill : public DataGeneric + { + FMaterial *mTexture; + }; + + struct DataSimplePoly : public DataGeneric + { + FMaterial *mTexture; + int mLightLevel; + FDynamicColormap *mColormap; + }; + + TArray mVertices; + TArray mData; + int mLastLineCmd = -1; // consecutive lines can be batched into a single draw call so keep this info around. + + int AddData(const DataGeneric *data); + +public: + void AddTexture(FTexture *img, DrawParms &parms); + void AddDim(PalEntry color, float damount, int x1, int y1, int w, int h); + void AddClear(int left, int top, int right, int bottom, int palcolor, uint32 color); + void AddFlatFill(int left, int top, int right, int bottom, FTexture *src, bool local_origin); + + void AddPoly(FTexture *texture, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel); + + void AddLine(int x1, int y1, int x2, int y2, int palcolor, uint32 color); + void AddPixel(int x1, int y1, int palcolor, uint32 color); + + void Draw(); + void Clear(); +}; + + +#endif diff --git a/src/gl/renderer/gl_colormap.h b/src/gl/renderer/gl_colormap.h new file mode 100644 index 000000000..d66950309 --- /dev/null +++ b/src/gl/renderer/gl_colormap.h @@ -0,0 +1,78 @@ +#ifndef __GL_COLORMAP +#define __GL_COLORMAP + +#include "doomtype.h" +#include "v_palette.h" +#include "r_data/colormaps.h" + +extern DWORD gl_fixedcolormap; + +struct lightlist_t; + +enum EColorManipulation +{ + + CM_INVALID=-1, + CM_DEFAULT=0, // untranslated + CM_FIRSTSPECIALCOLORMAP, // first special fixed colormap + + CM_FOGLAYER = 0x10000000, // Sprite shaped fog layer + + // These are not to be passed to the texture manager + CM_LITE = 0x20000000, // special values to handle these items without excessive hacking + CM_TORCH= 0x20000010, // These are not real color manipulations +}; + +#define CM_MAXCOLORMAP int(CM_FIRSTSPECIALCOLORMAP + SpecialColormaps.Size()) + + // for internal use +struct FColormap +{ + PalEntry LightColor; // a is saturation (0 full, 31=b/w, other=custom colormap) + PalEntry FadeColor; // a is fadedensity>>1 + int desaturation; + int blendfactor; + + void Clear() + { + LightColor=0xffffff; + FadeColor=0; + desaturation = 0; + blendfactor=0; + } + + void ClearColor() + { + LightColor.r=LightColor.g=LightColor.b=0xff; + blendfactor=0; + desaturation = 0; + } + + + FColormap & operator=(FDynamicColormap * from) + { + LightColor = from->Color; + desaturation = from->Desaturate; + FadeColor = from->Fade; + blendfactor = from->Color.a; + return * this; + } + + void CopyLightColor(FDynamicColormap * from) + { + LightColor = from->Color; + desaturation = from->Desaturate; + blendfactor = from->Color.a; + } + + void CopyFrom3DLight(lightlist_t *light); + + void Decolorize() // this for 'nocoloredspritelighting' and not the same as desaturation. The normal formula results in a value that's too dark. + { + int v = (LightColor.r + LightColor.g + LightColor.b) / 3; + LightColor.r = LightColor.g = LightColor.b = (255 + v + v) / 3; + } +}; + + +#endif diff --git a/src/gl/renderer/gl_lightdata.cpp b/src/gl/renderer/gl_lightdata.cpp new file mode 100644 index 000000000..ca2d32c41 --- /dev/null +++ b/src/gl/renderer/gl_lightdata.cpp @@ -0,0 +1,552 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_light.cpp +** Light level / fog management / dynamic lights +** +**/ + +#include "gl/system/gl_system.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/data/gl_data.h" +#include "gl/renderer/gl_colormap.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/shaders/gl_shader.h" +#include "gl/scene/gl_portal.h" +#include "c_dispatch.h" +#include "p_local.h" +#include "g_level.h" +#include "r_sky.h" + +// externally settable lighting properties +static float distfogtable[2][256]; // light to fog conversion table for black fog +static PalEntry outsidefogcolor; +int fogdensity; +int outsidefogdensity; +int skyfog; + +CVAR(Int, gl_weaponlight, 8, CVAR_ARCHIVE); +CUSTOM_CVAR(Bool, gl_enhanced_nightvision, true, CVAR_ARCHIVE|CVAR_NOINITCALL) +{ + // The fixed colormap state needs to be reset because if this happens when + // a shader is set to CM_LITE or CM_TORCH it won't register the change in behavior caused by this CVAR. + if (GLRenderer != nullptr && GLRenderer->mShaderManager != nullptr) + { + GLRenderer->mShaderManager->ResetFixedColormap(); + } +} +CVAR(Bool, gl_brightfog, false, CVAR_ARCHIVE); +CVAR(Bool, gl_lightadditivesurfaces, false, CVAR_ARCHIVE); +CVAR(Bool, gl_attenuate, false, CVAR_ARCHIVE); + + + +//========================================================================== +// +// Sets up the fog tables +// +//========================================================================== + +CUSTOM_CVAR (Int, gl_distfog, 70, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + for (int i=0;i<256;i++) + { + + if (i<164) + { + distfogtable[0][i]= (gl_distfog>>1) + (gl_distfog)*(164-i)/164; + } + else if (i<230) + { + distfogtable[0][i]= (gl_distfog>>1) - (gl_distfog>>1)*(i-164)/(230-164); + } + else distfogtable[0][i]=0; + + if (i<128) + { + distfogtable[1][i]= 6.f + (gl_distfog>>1) + (gl_distfog)*(128-i)/48; + } + else if (i<216) + { + distfogtable[1][i]= (216.f-i) / ((216.f-128.f)) * gl_distfog / 10; + } + else distfogtable[1][i]=0; + } +} + +CUSTOM_CVAR(Int,gl_fogmode,1,CVAR_ARCHIVE|CVAR_NOINITCALL) +{ + if (self>2) self=2; + if (self<0) self=0; +} + +CUSTOM_CVAR(Int, gl_lightmode, 3 ,CVAR_ARCHIVE|CVAR_NOINITCALL) +{ + int newself = self; + if (newself > 4) newself=8; // use 8 for software lighting to avoid conflicts with the bit mask + if (newself < 0) newself=0; + if (self != newself) self = newself; + glset.lightmode = newself; +} + + + + +//========================================================================== +// +// Sets render state to draw the given render style +// includes: Texture mode, blend equation and blend mode +// +//========================================================================== + +void gl_GetRenderStyle(FRenderStyle style, bool drawopaque, bool allowcolorblending, + int *tm, int *sb, int *db, int *be) +{ + static int blendstyles[] = { GL_ZERO, GL_ONE, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }; + static int renderops[] = { 0, GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1 }; + + int srcblend = blendstyles[style.SrcAlpha&3]; + int dstblend = blendstyles[style.DestAlpha&3]; + int blendequation = renderops[style.BlendOp&15]; + int texturemode = drawopaque? TM_OPAQUE : TM_MODULATE; + + if (style.Flags & STYLEF_RedIsAlpha) + { + texturemode = TM_REDTOALPHA; + } + else if (style.Flags & STYLEF_ColorIsFixed) + { + texturemode = TM_MASK; + } + else if (style.Flags & STYLEF_InvertSource) + { + // The only place where InvertSource is used is for inverted sprites with the infrared powerup. + texturemode = TM_INVERSE; + } + + if (blendequation == -1) + { + srcblend = GL_DST_COLOR; + dstblend = GL_ONE_MINUS_SRC_ALPHA; + blendequation = GL_FUNC_ADD; + } + + if (allowcolorblending && srcblend == GL_SRC_ALPHA && dstblend == GL_ONE && blendequation == GL_FUNC_ADD) + { + srcblend = GL_SRC_COLOR; + } + + *tm = texturemode; + *be = blendequation; + *sb = srcblend; + *db = dstblend; +} + + +//========================================================================== +// +// Set fog parameters for the level +// +//========================================================================== +void gl_SetFogParams(int _fogdensity, PalEntry _outsidefogcolor, int _outsidefogdensity, int _skyfog) +{ + fogdensity=_fogdensity; + outsidefogcolor=_outsidefogcolor; + outsidefogdensity=_outsidefogdensity; + skyfog=_skyfog; + + outsidefogdensity>>=1; + fogdensity>>=1; +} + + +//========================================================================== +// +// Get current light level +// +//========================================================================== + +int gl_CalcLightLevel(int lightlevel, int rellight, bool weapon) +{ + int light; + + if (lightlevel == 0) return 0; + + if ((glset.lightmode & 2) && lightlevel < 192 && !weapon) + { + if (lightlevel > 100) + { + light = xs_CRoundToInt(192.f - (192 - lightlevel)* 1.87f); + if (light + rellight < 20) + { + light = 20 + (light + rellight - 20) / 5; + } + else + { + light += rellight; + } + } + else + { + light = (lightlevel + rellight) / 5; + } + + } + else + { + light=lightlevel+rellight; + } + + return clamp(light, 0, 255); +} + +//========================================================================== +// +// Get current light color +// +//========================================================================== + +static PalEntry gl_CalcLightColor(int light, PalEntry pe, int blendfactor) +{ + int r,g,b; + + if (glset.lightmode == 8) + { + return pe; + } + else if (blendfactor == 0) + { + r = pe.r * light / 255; + g = pe.g * light / 255; + b = pe.b * light / 255; + } + else + { + // This is what Legacy does with colored light in 3D volumes. No, it doesn't really make sense... + // It also doesn't translate well to software style lighting. + int mixlight = light * (255 - blendfactor); + + r = (mixlight + pe.r * blendfactor) / 255; + g = (mixlight + pe.g * blendfactor) / 255; + b = (mixlight + pe.b * blendfactor) / 255; + } + return PalEntry(255, BYTE(r), BYTE(g), BYTE(b)); +} + +//========================================================================== +// +// set current light color +// +//========================================================================== +void gl_SetColor(int sectorlightlevel, int rellight, const FColormap &cm, float alpha, bool weapon) +{ + if (gl_fixedcolormap != CM_DEFAULT) + { + gl_RenderState.SetColorAlpha(0xffffff, alpha, 0); + gl_RenderState.SetSoftLightLevel(255); + } + else + { + int hwlightlevel = gl_CalcLightLevel(sectorlightlevel, rellight, weapon); + PalEntry pe = gl_CalcLightColor(hwlightlevel, cm.LightColor, cm.blendfactor); + gl_RenderState.SetColorAlpha(pe, alpha, cm.desaturation); + gl_RenderState.SetSoftLightLevel(gl_ClampLight(sectorlightlevel + rellight)); + } +} + +//========================================================================== +// +// calculates the current fog density +// +// Rules for fog: +// +// 1. If bit 4 of gl_lightmode is set always use the level's fog density. +// This is what Legacy's GL render does. +// 2. black fog means no fog and always uses the distfogtable based on the level's fog density setting +// 3. If outside fog is defined and the current fog color is the same as the outside fog +// the engine always uses the outside fog density to make the fog uniform across the level. +// If the outside fog's density is undefined it uses the level's fog density and if that is +// not defined it uses a default of 70. +// 4. If a global fog density is specified it is being used for all fog on the level +// 5. If none of the above apply fog density is based on the light level as for the software renderer. +// +//========================================================================== + +float gl_GetFogDensity(int lightlevel, PalEntry fogcolor) +{ + float density; + + if (glset.lightmode&4) + { + // uses approximations of Legacy's default settings. + density = fogdensity? fogdensity : 18; + } + else if ((fogcolor.d & 0xffffff) == 0) + { + // case 1: black fog + if (glset.lightmode != 8) + { + density=distfogtable[glset.lightmode!=0][gl_ClampLight(lightlevel)]; + } + else + { + density = 0; + } + } + else if (outsidefogdensity != 0 && outsidefogcolor.a!=0xff && (fogcolor.d & 0xffffff) == (outsidefogcolor.d & 0xffffff)) + { + // case 2. outsidefogdensity has already been set as needed + density=outsidefogdensity; + } + else if (fogdensity!=0) + { + // case 3: level has fog density set + density=fogdensity; + } + else if (lightlevel < 248) + { + // case 4: use light level + density=clamp(255-lightlevel,30,255); + } + else + { + density = 0.f; + } + return density; +} + + +//========================================================================== +// +// Check fog by current lighting info +// +//========================================================================== + +bool gl_CheckFog(FColormap *cm, int lightlevel) +{ + // Check for fog boundaries. This needs a few more checks for the sectors + bool frontfog; + + PalEntry fogcolor = cm->FadeColor; + + if ((fogcolor.d & 0xffffff) == 0) + { + frontfog = false; + } + else if (outsidefogdensity != 0 && outsidefogcolor.a!=0xff && (fogcolor.d & 0xffffff) == (outsidefogcolor.d & 0xffffff)) + { + frontfog = true; + } + else if (fogdensity!=0 || (glset.lightmode & 4)) + { + // case 3: level has fog density set + frontfog = true; + } + else + { + // case 4: use light level + frontfog = lightlevel < 248; + } + return frontfog; +} + +//========================================================================== +// +// Check if the current linedef is a candidate for a fog boundary +// +// Requirements for a fog boundary: +// - front sector has no fog +// - back sector has fog +// - at least one of both does not have a sky ceiling. +// +//========================================================================== + +bool gl_CheckFog(sector_t *frontsector, sector_t *backsector) +{ + if (gl_fixedcolormap) return false; + if (frontsector == backsector) return false; // there can't be a boundary if both sides are in the same sector. + + // Check for fog boundaries. This needs a few more checks for the sectors + + PalEntry fogcolor = frontsector->ColorMap->Fade; + + if ((fogcolor.d & 0xffffff) == 0) + { + return false; + } + else if (outsidefogdensity != 0 && outsidefogcolor.a!=0xff && (fogcolor.d & 0xffffff) == (outsidefogcolor.d & 0xffffff)) + { + } + else if (fogdensity!=0 || (glset.lightmode & 4)) + { + // case 3: level has fog density set + } + else + { + // case 4: use light level + if (frontsector->lightlevel >= 248) return false; + } + + fogcolor = backsector->ColorMap->Fade; + + if ((fogcolor.d & 0xffffff) == 0) + { + } + else if (outsidefogdensity != 0 && outsidefogcolor.a!=0xff && (fogcolor.d & 0xffffff) == (outsidefogcolor.d & 0xffffff)) + { + return false; + } + else if (fogdensity!=0 || (glset.lightmode & 4)) + { + // case 3: level has fog density set + return false; + } + else + { + // case 4: use light level + if (backsector->lightlevel < 248) return false; + } + + // in all other cases this might create more problems than it solves. + return ((frontsector->GetTexture(sector_t::ceiling)!=skyflatnum || + backsector->GetTexture(sector_t::ceiling)!=skyflatnum)); +} + +//========================================================================== +// +// Lighting stuff +// +//========================================================================== + +void gl_SetShaderLight(float level, float olight) +{ + const float MAXDIST = 256.f; + const float THRESHOLD = 96.f; + const float FACTOR = 0.75f; + + if (level > 0) + { + float lightdist, lightfactor; + + if (olight < THRESHOLD) + { + lightdist = (MAXDIST/2) + (olight * MAXDIST / THRESHOLD / 2); + olight = THRESHOLD; + } + else lightdist = MAXDIST; + + lightfactor = 1.f + ((olight/level) - 1.f) * FACTOR; + if (lightfactor == 1.f) lightdist = 0.f; // save some code in the shader + gl_RenderState.SetLightParms(lightfactor, lightdist); + } + else + { + gl_RenderState.SetLightParms(1.f, 0.f); + } +} + + +//========================================================================== +// +// Sets the fog for the current polygon +// +//========================================================================== + +void gl_SetFog(int lightlevel, int rellight, const FColormap *cmap, bool isadditive) +{ + PalEntry fogcolor; + float fogdensity; + + if (level.flags&LEVEL_HASFADETABLE) + { + fogdensity=70; + fogcolor=0x808080; + } + else if (cmap != NULL && gl_fixedcolormap == 0) + { + fogcolor = cmap->FadeColor; + fogdensity = gl_GetFogDensity(lightlevel, fogcolor); + fogcolor.a=0; + } + else + { + fogcolor = 0; + fogdensity = 0; + } + + // Make fog a little denser when inside a skybox + if (GLPortal::inskybox) fogdensity+=fogdensity/2; + + + // no fog in enhanced vision modes! + if (fogdensity==0 || gl_fogmode == 0) + { + gl_RenderState.EnableFog(false); + gl_RenderState.SetFog(0,0); + } + else + { + if (glset.lightmode == 2 && fogcolor == 0) + { + float light = gl_CalcLightLevel(lightlevel, rellight, false); + gl_SetShaderLight(light, lightlevel); + } + else + { + gl_RenderState.SetLightParms(1.f, 0.f); + } + + // For additive rendering using the regular fog color here would mean applying it twice + // so always use black + if (isadditive) + { + fogcolor=0; + } + + gl_RenderState.EnableFog(true); + gl_RenderState.SetFog(fogcolor, fogdensity); + + // Korshun: fullbright fog like in software renderer. + if (glset.lightmode == 8 && glset.brightfog && fogdensity != 0 && fogcolor != 0) + { + gl_RenderState.SetSoftLightLevel(255); + } + } +} + + +//========================================================================== +// +// For testing sky fog sheets +// +//========================================================================== +CCMD(skyfog) +{ + if (argv.argc()>1) + { + skyfog=strtol(argv[1],NULL,0); + } +} + diff --git a/src/gl/renderer/gl_lightdata.h b/src/gl/renderer/gl_lightdata.h new file mode 100644 index 000000000..4cc7a7d04 --- /dev/null +++ b/src/gl/renderer/gl_lightdata.h @@ -0,0 +1,64 @@ +#ifndef __GL_LIGHTDATA +#define __GL_LIGHTDATA + +#include "v_palette.h" +#include "p_3dfloors.h" +#include "r_data/renderstyle.h" +#include "gl/renderer/gl_colormap.h" + +inline int gl_ClampLight(int lightlevel) +{ + return clamp(lightlevel, 0, 255); +} + +void gl_GetRenderStyle(FRenderStyle style, bool drawopaque, bool allowcolorblending, + int *tm, int *sb, int *db, int *be); +void gl_SetFogParams(int _fogdensity, PalEntry _outsidefogcolor, int _outsidefogdensity, int _skyfog); + +int gl_CalcLightLevel(int lightlevel, int rellight, bool weapon); +void gl_SetColor(int light, int rellight, const FColormap &cm, float alpha, bool weapon=false); + +float gl_GetFogDensity(int lightlevel, PalEntry fogcolor); +struct sector_t; +bool gl_CheckFog(FColormap *cm, int lightlevel); +bool gl_CheckFog(sector_t *frontsector, sector_t *backsector); + +void gl_SetFog(int lightlevel, int rellight, const FColormap *cm, bool isadditive); + +inline bool gl_isBlack(PalEntry color) +{ + return color.r + color.g + color.b == 0; +} + +inline bool gl_isWhite(PalEntry color) +{ + return color.r + color.g + color.b == 3*0xff; +} + +extern DWORD gl_fixedcolormap; + +inline bool gl_isFullbright(PalEntry color, int lightlevel) +{ + return gl_fixedcolormap || (gl_isWhite(color) && lightlevel==255); +} + +void gl_DeleteAllAttachedLights(); +void gl_RecreateAllAttachedLights(); + +extern int fogdensity; +extern int outsidefogdensity; +extern int skyfog; + + +inline void FColormap::CopyFrom3DLight(lightlist_t *light) +{ + LightColor = light->extra_colormap->Color; + desaturation = light->extra_colormap->Desaturate; + blendfactor = light->extra_colormap->Color.a; + if (light->caster && (light->caster->flags&FF_FADEWALLS) && (light->extra_colormap->Fade & 0xffffff) != 0) + FadeColor = light->extra_colormap->Fade; +} + + + +#endif \ No newline at end of file diff --git a/src/gl/renderer/gl_postprocess.cpp b/src/gl/renderer/gl_postprocess.cpp new file mode 100644 index 000000000..f35071854 --- /dev/null +++ b/src/gl/renderer/gl_postprocess.cpp @@ -0,0 +1,851 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_postprocess.cpp +** Post processing effects in the render pipeline +** +*/ + +#include "gl/system/gl_system.h" +#include "gi.h" +#include "m_png.h" +#include "m_random.h" +#include "st_stuff.h" +#include "dobject.h" +#include "doomstat.h" +#include "g_level.h" +#include "r_data/r_interpolate.h" +#include "r_utility.h" +#include "d_player.h" +#include "p_effect.h" +#include "sbar.h" +#include "po_man.h" +#include "r_utility.h" +#include "p_local.h" +#include "colormatcher.h" +#include "gl/gl_functions.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_postprocessstate.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/shaders/gl_ambientshader.h" +#include "gl/shaders/gl_bloomshader.h" +#include "gl/shaders/gl_blurshader.h" +#include "gl/shaders/gl_tonemapshader.h" +#include "gl/shaders/gl_colormapshader.h" +#include "gl/shaders/gl_lensshader.h" +#include "gl/shaders/gl_fxaashader.h" +#include "gl/shaders/gl_presentshader.h" +#include "gl/renderer/gl_2ddrawer.h" +#include "gl/stereo3d/gl_stereo3d.h" + +//========================================================================== +// +// CVARs +// +//========================================================================== +CVAR(Bool, gl_bloom, false, CVAR_ARCHIVE); +CUSTOM_CVAR(Float, gl_bloom_amount, 1.4f, CVAR_ARCHIVE) +{ + if (self < 0.1f) self = 0.1f; +} + +CVAR(Float, gl_exposure_scale, 1.3f, CVAR_ARCHIVE) +CVAR(Float, gl_exposure_min, 0.35f, CVAR_ARCHIVE) +CVAR(Float, gl_exposure_base, 0.35f, CVAR_ARCHIVE) +CVAR(Float, gl_exposure_speed, 0.05f, CVAR_ARCHIVE) + +CUSTOM_CVAR(Int, gl_tonemap, 0, CVAR_ARCHIVE) +{ + if (self < 0 || self > 5) + self = 0; +} + +CUSTOM_CVAR(Int, gl_bloom_kernel_size, 7, CVAR_ARCHIVE) +{ + if (self < 3 || self > 15 || self % 2 == 0) + self = 7; +} + +CVAR(Bool, gl_lens, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + +CVAR(Float, gl_lens_k, -0.12f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Float, gl_lens_kcube, 0.1f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Float, gl_lens_chromatic, 1.12f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + +CUSTOM_CVAR(Int, gl_fxaa, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + if (self < 0 || self >= FFXAAShader::Count) + { + self = 0; + } +} + +CUSTOM_CVAR(Int, gl_ssao, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + if (self < 0 || self > 3) + self = 0; +} + +CUSTOM_CVAR(Int, gl_ssao_portals, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + if (self < 0) + self = 0; +} + +CVAR(Float, gl_ssao_strength, 0.7, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Int, gl_ssao_debug, 0, 0) +CVAR(Float, gl_ssao_bias, 0.2f, 0) +CVAR(Float, gl_ssao_radius, 80.0f, 0) +CUSTOM_CVAR(Float, gl_ssao_blur, 16.0f, 0) +{ + if (self < 0.1f) self = 0.1f; +} + +CUSTOM_CVAR(Float, gl_ssao_exponent, 1.8f, 0) +{ + if (self < 0.1f) self = 0.1f; +} + +EXTERN_CVAR(Float, vid_brightness) +EXTERN_CVAR(Float, vid_contrast) + + +void FGLRenderer::RenderScreenQuad() +{ + mVBO->BindVBO(); + gl_RenderState.ResetVertexBuffer(); + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_STRIP, FFlatVertexBuffer::PRESENT_INDEX, 4); +} + +void FGLRenderer::PostProcessScene() +{ + mBuffers->BlitSceneToTexture(); + UpdateCameraExposure(); + BloomScene(); + TonemapScene(); + ColormapScene(); + LensDistortScene(); + ApplyFXAA(); +} + +//----------------------------------------------------------------------------- +// +// Adds ambient occlusion to the scene +// +//----------------------------------------------------------------------------- + +void FGLRenderer::AmbientOccludeScene() +{ + FGLDebug::PushGroup("AmbientOccludeScene"); + + FGLPostProcessState savedState; + savedState.SaveTextureBindings(3); + + float bias = gl_ssao_bias; + float aoRadius = gl_ssao_radius; + const float blurAmount = gl_ssao_blur; + float aoStrength = gl_ssao_strength; + + //float tanHalfFovy = tan(fovy * (M_PI / 360.0f)); + float tanHalfFovy = 1.0f / gl_RenderState.mProjectionMatrix.get()[5]; + float invFocalLenX = tanHalfFovy * (mBuffers->GetSceneWidth() / (float)mBuffers->GetSceneHeight()); + float invFocalLenY = tanHalfFovy; + float nDotVBias = clamp(bias, 0.0f, 1.0f); + float r2 = aoRadius * aoRadius; + + float blurSharpness = 1.0f / blurAmount; + + float sceneScaleX = mSceneViewport.width / (float)mScreenViewport.width; + float sceneScaleY = mSceneViewport.height / (float)mScreenViewport.height; + float sceneOffsetX = mSceneViewport.left / (float)mScreenViewport.width; + float sceneOffsetY = mSceneViewport.top / (float)mScreenViewport.height; + + int randomTexture = clamp(gl_ssao - 1, 0, FGLRenderBuffers::NumAmbientRandomTextures - 1); + + // Calculate linear depth values + glBindFramebuffer(GL_FRAMEBUFFER, mBuffers->LinearDepthFB); + glViewport(0, 0, mBuffers->AmbientWidth, mBuffers->AmbientHeight); + mBuffers->BindSceneDepthTexture(0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + mBuffers->BindSceneColorTexture(1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glActiveTexture(GL_TEXTURE0); + mLinearDepthShader->Bind(); + mLinearDepthShader->DepthTexture.Set(0); + mLinearDepthShader->ColorTexture.Set(1); + if (gl_multisample > 1) mLinearDepthShader->SampleIndex.Set(0); + mLinearDepthShader->LinearizeDepthA.Set(1.0f / GetZFar() - 1.0f / GetZNear()); + mLinearDepthShader->LinearizeDepthB.Set(MAX(1.0f / GetZNear(), 1.e-8f)); + mLinearDepthShader->InverseDepthRangeA.Set(1.0f); + mLinearDepthShader->InverseDepthRangeB.Set(0.0f); + mLinearDepthShader->Scale.Set(sceneScaleX, sceneScaleY); + mLinearDepthShader->Offset.Set(sceneOffsetX, sceneOffsetY); + RenderScreenQuad(); + + // Apply ambient occlusion + glBindFramebuffer(GL_FRAMEBUFFER, mBuffers->AmbientFB1); + glBindTexture(GL_TEXTURE_2D, mBuffers->LinearDepthTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, mBuffers->AmbientRandomTexture[randomTexture]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + mBuffers->BindSceneNormalTexture(2); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glActiveTexture(GL_TEXTURE0); + mSSAOShader->Bind(); + mSSAOShader->DepthTexture.Set(0); + mSSAOShader->RandomTexture.Set(1); + mSSAOShader->NormalTexture.Set(2); + if (gl_multisample > 1) mSSAOShader->SampleIndex.Set(0); + mSSAOShader->UVToViewA.Set(2.0f * invFocalLenX, 2.0f * invFocalLenY); + mSSAOShader->UVToViewB.Set(-invFocalLenX, -invFocalLenY); + mSSAOShader->InvFullResolution.Set(1.0f / mBuffers->AmbientWidth, 1.0f / mBuffers->AmbientHeight); + mSSAOShader->NDotVBias.Set(nDotVBias); + mSSAOShader->NegInvR2.Set(-1.0f / r2); + mSSAOShader->RadiusToScreen.Set(aoRadius * 0.5 / tanHalfFovy * mBuffers->AmbientHeight); + mSSAOShader->AOMultiplier.Set(1.0f / (1.0f - nDotVBias)); + mSSAOShader->AOStrength.Set(aoStrength); + mSSAOShader->Scale.Set(sceneScaleX, sceneScaleY); + mSSAOShader->Offset.Set(sceneOffsetX, sceneOffsetY); + RenderScreenQuad(); + + // Blur SSAO texture + if (gl_ssao_debug < 2) + { + glBindFramebuffer(GL_FRAMEBUFFER, mBuffers->AmbientFB0); + glBindTexture(GL_TEXTURE_2D, mBuffers->AmbientTexture1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + mDepthBlurShader->Bind(false); + mDepthBlurShader->BlurSharpness[false].Set(blurSharpness); + mDepthBlurShader->InvFullResolution[false].Set(1.0f / mBuffers->AmbientWidth, 1.0f / mBuffers->AmbientHeight); + RenderScreenQuad(); + + glBindFramebuffer(GL_FRAMEBUFFER, mBuffers->AmbientFB1); + glBindTexture(GL_TEXTURE_2D, mBuffers->AmbientTexture0); + mDepthBlurShader->Bind(true); + mDepthBlurShader->BlurSharpness[true].Set(blurSharpness); + mDepthBlurShader->InvFullResolution[true].Set(1.0f / mBuffers->AmbientWidth, 1.0f / mBuffers->AmbientHeight); + mDepthBlurShader->PowExponent[true].Set(gl_ssao_exponent); + RenderScreenQuad(); + } + + // Add SSAO back to scene texture: + mBuffers->BindSceneFB(false); + glViewport(mSceneViewport.left, mSceneViewport.top, mSceneViewport.width, mSceneViewport.height); + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (gl_ssao_debug != 0) + { + glClearColor(1.0f, 1.0f, 1.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + } + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, mBuffers->AmbientTexture1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mBuffers->BindSceneFogTexture(1); + mSSAOCombineShader->Bind(); + mSSAOCombineShader->AODepthTexture.Set(0); + mSSAOCombineShader->SceneFogTexture.Set(1); + if (gl_multisample > 1) mSSAOCombineShader->SampleCount.Set(gl_multisample); + mSSAOCombineShader->Scale.Set(sceneScaleX, sceneScaleY); + mSSAOCombineShader->Offset.Set(sceneOffsetX, sceneOffsetY); + RenderScreenQuad(); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Extracts light average from the scene and updates the camera exposure texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::UpdateCameraExposure() +{ + if (!gl_bloom && gl_tonemap == 0) + return; + + FGLDebug::PushGroup("UpdateCameraExposure"); + + FGLPostProcessState savedState; + savedState.SaveTextureBindings(2); + + // Extract light level from scene texture: + const auto &level0 = mBuffers->ExposureLevels[0]; + glBindFramebuffer(GL_FRAMEBUFFER, level0.Framebuffer); + glViewport(0, 0, level0.Width, level0.Height); + mBuffers->BindCurrentTexture(0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mExposureExtractShader->Bind(); + mExposureExtractShader->SceneTexture.Set(0); + mExposureExtractShader->Scale.Set(mSceneViewport.width / (float)mScreenViewport.width, mSceneViewport.height / (float)mScreenViewport.height); + mExposureExtractShader->Offset.Set(mSceneViewport.left / (float)mScreenViewport.width, mSceneViewport.top / (float)mScreenViewport.height); + RenderScreenQuad(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + // Find the average value: + for (int i = 0; i + 1 < mBuffers->ExposureLevels.Size(); i++) + { + const auto &level = mBuffers->ExposureLevels[i]; + const auto &next = mBuffers->ExposureLevels[i + 1]; + + glBindFramebuffer(GL_FRAMEBUFFER, next.Framebuffer); + glViewport(0, 0, next.Width, next.Height); + glBindTexture(GL_TEXTURE_2D, level.Texture); + mExposureAverageShader->Bind(); + mExposureAverageShader->ExposureTexture.Set(0); + RenderScreenQuad(); + } + + // Combine average value with current camera exposure: + glBindFramebuffer(GL_FRAMEBUFFER, mBuffers->ExposureFB); + glViewport(0, 0, 1, 1); + if (!mBuffers->FirstExposureFrame) + { + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + else + { + mBuffers->FirstExposureFrame = false; + } + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, mBuffers->ExposureLevels.Last().Texture); + mExposureCombineShader->Bind(); + mExposureCombineShader->ExposureTexture.Set(0); + mExposureCombineShader->ExposureBase.Set(gl_exposure_base); + mExposureCombineShader->ExposureMin.Set(gl_exposure_min); + mExposureCombineShader->ExposureScale.Set(gl_exposure_scale); + mExposureCombineShader->ExposureSpeed.Set(gl_exposure_speed); + RenderScreenQuad(); + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Adds bloom contribution to scene texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::BloomScene() +{ + // Only bloom things if enabled and no special fixed light mode is active + if (!gl_bloom || gl_fixedcolormap != CM_DEFAULT || gl_ssao_debug) + return; + + FGLDebug::PushGroup("BloomScene"); + + FGLPostProcessState savedState; + savedState.SaveTextureBindings(2); + + const float blurAmount = gl_bloom_amount; + int sampleCount = gl_bloom_kernel_size; + + const auto &level0 = mBuffers->BloomLevels[0]; + + // Extract blooming pixels from scene texture: + glBindFramebuffer(GL_FRAMEBUFFER, level0.VFramebuffer); + glViewport(0, 0, level0.Width, level0.Height); + mBuffers->BindCurrentTexture(0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, mBuffers->ExposureTexture); + glActiveTexture(GL_TEXTURE0); + mBloomExtractShader->Bind(); + mBloomExtractShader->SceneTexture.Set(0); + mBloomExtractShader->ExposureTexture.Set(1); + mBloomExtractShader->Scale.Set(mSceneViewport.width / (float)mScreenViewport.width, mSceneViewport.height / (float)mScreenViewport.height); + mBloomExtractShader->Offset.Set(mSceneViewport.left / (float)mScreenViewport.width, mSceneViewport.top / (float)mScreenViewport.height); + RenderScreenQuad(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + // Blur and downscale: + for (int i = 0; i < FGLRenderBuffers::NumBloomLevels - 1; i++) + { + const auto &level = mBuffers->BloomLevels[i]; + const auto &next = mBuffers->BloomLevels[i + 1]; + mBlurShader->BlurHorizontal(this, blurAmount, sampleCount, level.VTexture, level.HFramebuffer, level.Width, level.Height); + mBlurShader->BlurVertical(this, blurAmount, sampleCount, level.HTexture, next.VFramebuffer, next.Width, next.Height); + } + + // Blur and upscale: + for (int i = FGLRenderBuffers::NumBloomLevels - 1; i > 0; i--) + { + const auto &level = mBuffers->BloomLevels[i]; + const auto &next = mBuffers->BloomLevels[i - 1]; + + mBlurShader->BlurHorizontal(this, blurAmount, sampleCount, level.VTexture, level.HFramebuffer, level.Width, level.Height); + mBlurShader->BlurVertical(this, blurAmount, sampleCount, level.HTexture, level.VFramebuffer, level.Width, level.Height); + + // Linear upscale: + glBindFramebuffer(GL_FRAMEBUFFER, next.VFramebuffer); + glViewport(0, 0, next.Width, next.Height); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, level.VTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mBloomCombineShader->Bind(); + mBloomCombineShader->BloomTexture.Set(0); + RenderScreenQuad(); + } + + mBlurShader->BlurHorizontal(this, blurAmount, sampleCount, level0.VTexture, level0.HFramebuffer, level0.Width, level0.Height); + mBlurShader->BlurVertical(this, blurAmount, sampleCount, level0.HTexture, level0.VFramebuffer, level0.Width, level0.Height); + + // Add bloom back to scene texture: + mBuffers->BindCurrentFB(); + glViewport(mSceneViewport.left, mSceneViewport.top, mSceneViewport.width, mSceneViewport.height); + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_ONE, GL_ONE); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, level0.VTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mBloomCombineShader->Bind(); + mBloomCombineShader->BloomTexture.Set(0); + RenderScreenQuad(); + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Tonemap scene texture and place the result in the HUD/2D texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::TonemapScene() +{ + if (gl_tonemap == 0) + return; + + FGLDebug::PushGroup("TonemapScene"); + + CreateTonemapPalette(); + + FGLPostProcessState savedState; + savedState.SaveTextureBindings(2); + + mBuffers->BindNextFB(); + mBuffers->BindCurrentTexture(0); + mTonemapShader->Bind(); + mTonemapShader->SceneTexture.Set(0); + + if (mTonemapShader->IsPaletteMode()) + { + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, mTonemapPalette->GetTextureHandle(0)); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glActiveTexture(GL_TEXTURE0); + + mTonemapShader->PaletteLUT.Set(1); + } + else + { + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, mBuffers->ExposureTexture); + glActiveTexture(GL_TEXTURE0); + + mTonemapShader->ExposureTexture.Set(1); + } + + RenderScreenQuad(); + mBuffers->NextTexture(); + + FGLDebug::PopGroup(); +} + +void FGLRenderer::CreateTonemapPalette() +{ + if (!mTonemapPalette) + { + TArray lut; + lut.Resize(512 * 512 * 4); + for (int r = 0; r < 64; r++) + { + for (int g = 0; g < 64; g++) + { + for (int b = 0; b < 64; b++) + { + PalEntry color = GPalette.BaseColors[(BYTE)PTM_BestColor((uint32 *)GPalette.BaseColors, (r << 2) | (r >> 4), (g << 2) | (g >> 4), (b << 2) | (b >> 4), 0, 256)]; + int index = ((r * 64 + g) * 64 + b) * 4; + lut[index] = color.r; + lut[index + 1] = color.g; + lut[index + 2] = color.b; + lut[index + 3] = 255; + } + } + } + + mTonemapPalette = new FHardwareTexture(512, 512, true); + mTonemapPalette->CreateTexture(&lut[0], 512, 512, 0, false, 0, "mTonemapPalette"); + } +} + +void FGLRenderer::ClearTonemapPalette() +{ + delete mTonemapPalette; + mTonemapPalette = nullptr; +} + +//----------------------------------------------------------------------------- +// +// Colormap scene texture and place the result in the HUD/2D texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::ColormapScene() +{ + if (gl_fixedcolormap < CM_FIRSTSPECIALCOLORMAP || gl_fixedcolormap >= CM_MAXCOLORMAP) + return; + + FGLDebug::PushGroup("ColormapScene"); + + FGLPostProcessState savedState; + + mBuffers->BindNextFB(); + mBuffers->BindCurrentTexture(0); + mColormapShader->Bind(); + + FSpecialColormap *scm = &SpecialColormaps[gl_fixedcolormap - CM_FIRSTSPECIALCOLORMAP]; + float m[] = { scm->ColorizeEnd[0] - scm->ColorizeStart[0], + scm->ColorizeEnd[1] - scm->ColorizeStart[1], scm->ColorizeEnd[2] - scm->ColorizeStart[2], 0.f }; + + mColormapShader->MapStart.Set(scm->ColorizeStart[0], scm->ColorizeStart[1], scm->ColorizeStart[2], 0.f); + mColormapShader->MapRange.Set(m); + + RenderScreenQuad(); + mBuffers->NextTexture(); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Apply lens distortion and place the result in the HUD/2D texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::LensDistortScene() +{ + if (gl_lens == 0) + return; + + FGLDebug::PushGroup("LensDistortScene"); + + float k[4] = + { + gl_lens_k, + gl_lens_k * gl_lens_chromatic, + gl_lens_k * gl_lens_chromatic * gl_lens_chromatic, + 0.0f + }; + float kcube[4] = + { + gl_lens_kcube, + gl_lens_kcube * gl_lens_chromatic, + gl_lens_kcube * gl_lens_chromatic * gl_lens_chromatic, + 0.0f + }; + + float aspect = mSceneViewport.width / (float)mSceneViewport.height; + + // Scale factor to keep sampling within the input texture + float r2 = aspect * aspect * 0.25 + 0.25f; + float sqrt_r2 = sqrt(r2); + float f0 = 1.0f + MAX(r2 * (k[0] + kcube[0] * sqrt_r2), 0.0f); + float f2 = 1.0f + MAX(r2 * (k[2] + kcube[2] * sqrt_r2), 0.0f); + float f = MAX(f0, f2); + float scale = 1.0f / f; + + FGLPostProcessState savedState; + + mBuffers->BindNextFB(); + mBuffers->BindCurrentTexture(0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mLensShader->Bind(); + mLensShader->InputTexture.Set(0); + mLensShader->AspectRatio.Set(aspect); + mLensShader->Scale.Set(scale); + mLensShader->LensDistortionCoefficient.Set(k); + mLensShader->CubicDistortionValue.Set(kcube); + RenderScreenQuad(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + mBuffers->NextTexture(); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Apply FXAA and place the result in the HUD/2D texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::ApplyFXAA() +{ + if (0 == gl_fxaa) + { + return; + } + + FGLDebug::PushGroup("ApplyFXAA"); + + const GLfloat rpcRes[2] = + { + 1.0f / mBuffers->GetWidth(), + 1.0f / mBuffers->GetHeight() + }; + + FGLPostProcessState savedState; + + mBuffers->BindNextFB(); + mBuffers->BindCurrentTexture(0); + mFXAALumaShader->Bind(); + mFXAALumaShader->InputTexture.Set(0); + RenderScreenQuad(); + mBuffers->NextTexture(); + + mBuffers->BindNextFB(); + mBuffers->BindCurrentTexture(0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + mFXAAShader->Bind(); + mFXAAShader->InputTexture.Set(0); + mFXAAShader->ReciprocalResolution.Set(rpcRes); + RenderScreenQuad(); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + mBuffers->NextTexture(); + + FGLDebug::PopGroup(); +} + +//----------------------------------------------------------------------------- +// +// Copies the rendered screen to its final destination +// +//----------------------------------------------------------------------------- + +void FGLRenderer::Flush() +{ + const s3d::Stereo3DMode& stereo3dMode = s3d::Stereo3DMode::getCurrentMode(); + + if (stereo3dMode.IsMono() || !FGLRenderBuffers::IsEnabled()) + { + CopyToBackbuffer(nullptr, true); + } + else + { + // Render 2D to eye textures + for (int eye_ix = 0; eye_ix < stereo3dMode.eye_count(); ++eye_ix) + { + FGLDebug::PushGroup("Eye2D"); + mBuffers->BindEyeFB(eye_ix); + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + glScissor(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + m2DDrawer->Draw(); + FGLDebug::PopGroup(); + } + m2DDrawer->Clear(); + + FGLPostProcessState savedState; + FGLDebug::PushGroup("PresentEyes"); + stereo3dMode.Present(); + FGLDebug::PopGroup(); + } +} + +//----------------------------------------------------------------------------- +// +// Gamma correct while copying to frame buffer +// +//----------------------------------------------------------------------------- + +void FGLRenderer::CopyToBackbuffer(const GL_IRECT *bounds, bool applyGamma) +{ + m2DDrawer->Draw(); // draw all pending 2D stuff before copying the buffer + m2DDrawer->Clear(); + + FGLDebug::PushGroup("CopyToBackbuffer"); + if (FGLRenderBuffers::IsEnabled()) + { + FGLPostProcessState savedState; + mBuffers->BindOutputFB(); + + GL_IRECT box; + if (bounds) + { + box = *bounds; + } + else + { + ClearBorders(); + box = mOutputLetterbox; + } + + mBuffers->BindCurrentTexture(0); + DrawPresentTexture(box, applyGamma); + } + else if (!bounds) + { + FGLPostProcessState savedState; + ClearBorders(); + } + FGLDebug::PopGroup(); +} + +void FGLRenderer::DrawPresentTexture(const GL_IRECT &box, bool applyGamma) +{ + glViewport(box.left, box.top, box.width, box.height); + + glActiveTexture(GL_TEXTURE0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + mPresentShader->Bind(); + mPresentShader->InputTexture.Set(0); + if (!applyGamma || framebuffer->IsHWGammaActive()) + { + mPresentShader->InvGamma.Set(1.0f); + mPresentShader->Contrast.Set(1.0f); + mPresentShader->Brightness.Set(0.0f); + } + else + { + mPresentShader->InvGamma.Set(1.0f / clamp(Gamma, 0.1f, 4.f)); + mPresentShader->Contrast.Set(clamp(vid_contrast, 0.1f, 3.f)); + mPresentShader->Brightness.Set(clamp(vid_brightness, -0.8f, 0.8f)); + } + mPresentShader->Scale.Set(mScreenViewport.width / (float)mBuffers->GetWidth(), mScreenViewport.height / (float)mBuffers->GetHeight()); + RenderScreenQuad(); +} + +//----------------------------------------------------------------------------- +// +// Fills the black bars around the screen letterbox +// +//----------------------------------------------------------------------------- + +void FGLRenderer::ClearBorders() +{ + const auto &box = mOutputLetterbox; + + int clientWidth = framebuffer->GetClientWidth(); + int clientHeight = framebuffer->GetClientHeight(); + if (clientWidth == 0 || clientHeight == 0) + return; + + glViewport(0, 0, clientWidth, clientHeight); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glEnable(GL_SCISSOR_TEST); + if (box.top > 0) + { + glScissor(0, 0, clientWidth, box.top); + glClear(GL_COLOR_BUFFER_BIT); + } + if (clientHeight - box.top - box.height > 0) + { + glScissor(0, box.top + box.height, clientWidth, clientHeight - box.top - box.height); + glClear(GL_COLOR_BUFFER_BIT); + } + if (box.left > 0) + { + glScissor(0, box.top, box.left, box.height); + glClear(GL_COLOR_BUFFER_BIT); + } + if (clientWidth - box.left - box.width > 0) + { + glScissor(box.left + box.width, box.top, clientWidth - box.left - box.width, box.height); + glClear(GL_COLOR_BUFFER_BIT); + } + glDisable(GL_SCISSOR_TEST); +} + + +// [SP] Re-implemented BestColor for more precision rather than speed. This function is only ever called once until the game palette is changed. + +int FGLRenderer::PTM_BestColor (const uint32 *pal_in, int r, int g, int b, int first, int num) +{ + const PalEntry *pal = (const PalEntry *)pal_in; + static double powtable[256]; + static bool firstTime = true; + + double fbestdist, fdist; + int bestcolor; + + if (firstTime) + { + firstTime = false; + for (int x = 0; x < 256; x++) powtable[x] = pow((double)x/255,1.2); + } + + for (int color = first; color < num; color++) + { + double x = powtable[abs(r-pal[color].r)]; + double y = powtable[abs(g-pal[color].g)]; + double z = powtable[abs(b-pal[color].b)]; + fdist = x + y + z; + if (color == first || fdist < fbestdist) + { + if (fdist == 0) + return color; + + fbestdist = fdist; + bestcolor = color; + } + } + return bestcolor; +} + diff --git a/src/gl/renderer/gl_postprocessstate.cpp b/src/gl/renderer/gl_postprocessstate.cpp new file mode 100644 index 000000000..fead1435a --- /dev/null +++ b/src/gl/renderer/gl_postprocessstate.cpp @@ -0,0 +1,143 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_postprocessstate.cpp +** Render state maintenance +** +**/ + +#include "templates.h" +#include "gl/system/gl_system.h" +#include "gl/system/gl_interface.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_shader.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_postprocessstate.h" + +//----------------------------------------------------------------------------- +// +// Saves state modified by post processing shaders +// +//----------------------------------------------------------------------------- + +FGLPostProcessState::FGLPostProcessState() +{ + glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); + glActiveTexture(GL_TEXTURE0); + SaveTextureBindings(1); + + glGetBooleanv(GL_BLEND, &blendEnabled); + glGetBooleanv(GL_SCISSOR_TEST, &scissorEnabled); + glGetBooleanv(GL_DEPTH_TEST, &depthEnabled); + glGetBooleanv(GL_MULTISAMPLE, &multisampleEnabled); + glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProgram); + glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRgb); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha); + glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRgb); + glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha); + glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRgb); + glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha); + + glDisable(GL_MULTISAMPLE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); +} + +void FGLPostProcessState::SaveTextureBindings(unsigned int numUnits) +{ + while (textureBinding.Size() < numUnits) + { + unsigned int i = textureBinding.Size(); + + GLint texture; + glActiveTexture(GL_TEXTURE0 + i); + glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture); + glBindTexture(GL_TEXTURE_2D, 0); + textureBinding.Push(texture); + + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + GLint sampler; + glGetIntegerv(GL_SAMPLER_BINDING, &sampler); + glBindSampler(i, 0); + samplerBinding.Push(sampler); + } + } + glActiveTexture(GL_TEXTURE0); +} + +//----------------------------------------------------------------------------- +// +// Restores state at the end of post processing +// +//----------------------------------------------------------------------------- + +FGLPostProcessState::~FGLPostProcessState() +{ + if (blendEnabled) + glEnable(GL_BLEND); + else + glDisable(GL_BLEND); + + if (scissorEnabled) + glEnable(GL_SCISSOR_TEST); + else + glDisable(GL_SCISSOR_TEST); + + if (depthEnabled) + glEnable(GL_DEPTH_TEST); + else + glDisable(GL_DEPTH_TEST); + + if (multisampleEnabled) + glEnable(GL_MULTISAMPLE); + else + glDisable(GL_MULTISAMPLE); + + glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha); + glBlendFuncSeparate(blendSrcRgb, blendDestRgb, blendSrcAlpha, blendDestAlpha); + + glUseProgram(currentProgram); + + // Fully unbind to avoid incomplete texture warnings from Nvidia's driver when gl_debug_level 4 is active + for (unsigned int i = 0; i < textureBinding.Size(); i++) + { + glActiveTexture(GL_TEXTURE0 + i); + glBindTexture(GL_TEXTURE_2D, 0); + } + + for (unsigned int i = 0; i < samplerBinding.Size(); i++) + { + glBindSampler(i, samplerBinding[i]); + } + + for (unsigned int i = 0; i < textureBinding.Size(); i++) + { + glActiveTexture(GL_TEXTURE0 + i); + glBindTexture(GL_TEXTURE_2D, textureBinding[i]); + } + + glActiveTexture(activeTex); +} diff --git a/src/gl/renderer/gl_postprocessstate.h b/src/gl/renderer/gl_postprocessstate.h new file mode 100644 index 000000000..795a7d4ba --- /dev/null +++ b/src/gl/renderer/gl_postprocessstate.h @@ -0,0 +1,39 @@ +#ifndef __GL_POSTPROCESSSTATE_H +#define __GL_POSTPROCESSSTATE_H + +#include +#include "gl/system/gl_interface.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_matrix.h" +#include "c_cvars.h" +#include "r_defs.h" + +class FGLPostProcessState +{ +public: + FGLPostProcessState(); + ~FGLPostProcessState(); + + void SaveTextureBindings(unsigned int numUnits); + +private: + FGLPostProcessState(const FGLPostProcessState &) = delete; + FGLPostProcessState &operator=(const FGLPostProcessState &) = delete; + + GLint activeTex; + TArray textureBinding; + TArray samplerBinding; + GLboolean blendEnabled; + GLboolean scissorEnabled; + GLboolean depthEnabled; + GLboolean multisampleEnabled; + GLint currentProgram; + GLint blendEquationRgb; + GLint blendEquationAlpha; + GLint blendSrcRgb; + GLint blendSrcAlpha; + GLint blendDestRgb; + GLint blendDestAlpha; +}; + +#endif diff --git a/src/gl/renderer/gl_quaddrawer.cpp b/src/gl/renderer/gl_quaddrawer.cpp new file mode 100644 index 000000000..d6a4f98a8 --- /dev/null +++ b/src/gl/renderer/gl_quaddrawer.cpp @@ -0,0 +1,69 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "gl/shaders/gl_shader.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_quaddrawer.h" +#include "gl/data/gl_matrix.h" + +/* +** For handling of dynamically created quads when no persistently mapped +** buffer or client array is available (i.e. GL 3.x core profiles) +** +** In this situation the 4 vertices of a quad primitive are being passed +** as a matrix uniform because that is a lot faster than any kind of +** temporary buffer change. +*/ + +FFlatVertex FQuadDrawer::buffer[4]; + +//========================================================================== +// +// +// +//========================================================================== + +void FQuadDrawer::DoRender(int type) +{ + // When this gets called, the render state must already be applied so we can just + // send our vertices to the current shader. + float matV[16], matT[16]; + + for(int i=0;i<4;i++) + { + matV[i*4+0] = buffer[i].x; + matV[i*4+1] = buffer[i].z; + matV[i*4+2] = buffer[i].y; + matV[i*4+3] = 1; + matT[i*4+0] = buffer[i].u; + matT[i*4+1] = buffer[i].v; + matT[i*4+2] = matT[i*4+3] = 0; + } + FShader *shader = GLRenderer->mShaderManager->GetActiveShader(); + glUniformMatrix4fv(shader->vertexmatrix_index, 1, false, matV); + glUniformMatrix4fv(shader->texcoordmatrix_index, 1, false, matT); + glUniform1i(shader->quadmode_index, 1); + GLRenderer->mVBO->RenderArray(type, FFlatVertexBuffer::QUAD_INDEX, 4); + glUniform1i(shader->quadmode_index, 0); +} diff --git a/src/gl/renderer/gl_quaddrawer.h b/src/gl/renderer/gl_quaddrawer.h new file mode 100644 index 000000000..b9db60684 --- /dev/null +++ b/src/gl/renderer/gl_quaddrawer.h @@ -0,0 +1,44 @@ +#ifndef __QDRAWER_H +#define __QDRAWER_H + +#include "gl/data/gl_vertexbuffer.h" + +class FQuadDrawer +{ + FFlatVertex *p; + int ndx; + static FFlatVertex buffer[4]; + + void DoRender(int type); +public: + + FQuadDrawer() + { + if (gl.buffermethod == BM_DEFERRED) + { + p = buffer; + } + else + { + p = GLRenderer->mVBO->Alloc(4, &ndx); + } + } + void Set(int ndx, float x, float y, float z, float s, float t) + { + p[ndx].Set(x, y, z, s, t); + } + void Render(int type) + { + if (gl.buffermethod == BM_DEFERRED) + { + DoRender(type); + } + else + { + GLRenderer->mVBO->RenderArray(type, ndx, 4); + } + } +}; + + +#endif diff --git a/src/gl/renderer/gl_renderbuffers.cpp b/src/gl/renderer/gl_renderbuffers.cpp new file mode 100644 index 000000000..b14ee9852 --- /dev/null +++ b/src/gl/renderer/gl_renderbuffers.cpp @@ -0,0 +1,884 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_renderbuffers.cpp +** Render buffers used during rendering +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "w_wad.h" +#include "i_system.h" +#include "doomerrors.h" +#include + +CVAR(Int, gl_multisample, 1, CVAR_ARCHIVE|CVAR_GLOBALCONFIG); +CVAR(Bool, gl_renderbuffers, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) + +//========================================================================== +// +// Initialize render buffers and textures used in rendering passes +// +//========================================================================== + +FGLRenderBuffers::FGLRenderBuffers() +{ + for (int i = 0; i < NumPipelineTextures; i++) + { + mPipelineTexture[i] = 0; + mPipelineFB[i] = 0; + } + + for (int i = 0; i < NumAmbientRandomTextures; i++) + { + AmbientRandomTexture[i] = 0; + } + + glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&mOutputFB); + glGetIntegerv(GL_MAX_SAMPLES, &mMaxSamples); +} + +//========================================================================== +// +// Free render buffer resources +// +//========================================================================== + +FGLRenderBuffers::~FGLRenderBuffers() +{ + ClearScene(); + ClearPipeline(); + ClearEyeBuffers(); + ClearBloom(); + ClearExposureLevels(); + ClearAmbientOcclusion(); +} + +void FGLRenderBuffers::ClearScene() +{ + DeleteFrameBuffer(mSceneFB); + DeleteFrameBuffer(mSceneDataFB); + if (mSceneUsesTextures) + { + DeleteTexture(mSceneMultisample); + DeleteTexture(mSceneFog); + DeleteTexture(mSceneNormal); + DeleteTexture(mSceneDepthStencil); + } + else + { + DeleteRenderBuffer(mSceneMultisample); + DeleteRenderBuffer(mSceneFog); + DeleteRenderBuffer(mSceneNormal); + DeleteRenderBuffer(mSceneDepthStencil); + } +} + +void FGLRenderBuffers::ClearPipeline() +{ + for (int i = 0; i < NumPipelineTextures; i++) + { + DeleteFrameBuffer(mPipelineFB[i]); + DeleteTexture(mPipelineTexture[i]); + } +} + +void FGLRenderBuffers::ClearBloom() +{ + for (int i = 0; i < NumBloomLevels; i++) + { + auto &level = BloomLevels[i]; + DeleteFrameBuffer(level.HFramebuffer); + DeleteFrameBuffer(level.VFramebuffer); + DeleteTexture(level.HTexture); + DeleteTexture(level.VTexture); + level = FGLBloomTextureLevel(); + } +} + +void FGLRenderBuffers::ClearExposureLevels() +{ + for (auto &level : ExposureLevels) + { + DeleteTexture(level.Texture); + DeleteFrameBuffer(level.Framebuffer); + } + ExposureLevels.Clear(); + DeleteTexture(ExposureTexture); + DeleteFrameBuffer(ExposureFB); +} + +void FGLRenderBuffers::ClearEyeBuffers() +{ + for (auto handle : mEyeFBs) + DeleteFrameBuffer(handle); + + for (auto handle : mEyeTextures) + DeleteTexture(handle); + + mEyeTextures.Clear(); + mEyeFBs.Clear(); +} + +void FGLRenderBuffers::ClearAmbientOcclusion() +{ + DeleteFrameBuffer(LinearDepthFB); + DeleteFrameBuffer(AmbientFB0); + DeleteFrameBuffer(AmbientFB1); + DeleteTexture(LinearDepthTexture); + DeleteTexture(AmbientTexture0); + DeleteTexture(AmbientTexture1); + for (int i = 0; i < NumAmbientRandomTextures; i++) + DeleteTexture(AmbientRandomTexture[i]); +} + +void FGLRenderBuffers::DeleteTexture(GLuint &handle) +{ + if (handle != 0) + glDeleteTextures(1, &handle); + handle = 0; +} + +void FGLRenderBuffers::DeleteRenderBuffer(GLuint &handle) +{ + if (handle != 0) + glDeleteRenderbuffers(1, &handle); + handle = 0; +} + +void FGLRenderBuffers::DeleteFrameBuffer(GLuint &handle) +{ + if (handle != 0) + glDeleteFramebuffers(1, &handle); + handle = 0; +} + +//========================================================================== +// +// Makes sure all render buffers have sizes suitable for rending at the +// specified resolution +// +//========================================================================== + +bool FGLRenderBuffers::Setup(int width, int height, int sceneWidth, int sceneHeight) +{ + if (gl_renderbuffers != BuffersActive) + { + if (BuffersActive) + glBindFramebuffer(GL_FRAMEBUFFER, mOutputFB); + BuffersActive = gl_renderbuffers; + GLRenderer->mShaderManager->ResetFixedColormap(); + } + + if (!IsEnabled()) + return false; + + if (width <= 0 || height <= 0) + I_FatalError("Requested invalid render buffer sizes: screen = %dx%d", width, height); + + int samples = clamp((int)gl_multisample, 0, mMaxSamples); + bool needsSceneTextures = (gl_ssao != 0); + + GLint activeTex; + GLint textureBinding; + glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); + glActiveTexture(GL_TEXTURE0); + glGetIntegerv(GL_TEXTURE_BINDING_2D, &textureBinding); + + if (width != mWidth || height != mHeight) + CreatePipeline(width, height); + + if (width != mWidth || height != mHeight || mSamples != samples || mSceneUsesTextures != needsSceneTextures) + CreateScene(width, height, samples, needsSceneTextures); + + mWidth = width; + mHeight = height; + mSamples = samples; + mSceneUsesTextures = needsSceneTextures; + + // Bloom bluring buffers need to match the scene to avoid bloom bleeding artifacts + if (mSceneWidth != sceneWidth || mSceneHeight != sceneHeight) + { + CreateBloom(sceneWidth, sceneHeight); + CreateExposureLevels(sceneWidth, sceneHeight); + CreateAmbientOcclusion(sceneWidth, sceneHeight); + mSceneWidth = sceneWidth; + mSceneHeight = sceneHeight; + } + + glBindTexture(GL_TEXTURE_2D, textureBinding); + glActiveTexture(activeTex); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + if (FailedCreate) + { + ClearScene(); + ClearPipeline(); + ClearEyeBuffers(); + ClearBloom(); + ClearExposureLevels(); + mWidth = 0; + mHeight = 0; + mSamples = 0; + mSceneWidth = 0; + mSceneHeight = 0; + } + + return !FailedCreate; +} + +//========================================================================== +// +// Creates the scene buffers +// +//========================================================================== + +void FGLRenderBuffers::CreateScene(int width, int height, int samples, bool needsSceneTextures) +{ + ClearScene(); + + if (samples > 1) + { + if (needsSceneTextures) + { + mSceneMultisample = Create2DMultisampleTexture("SceneMultisample", GL_RGBA16F, width, height, samples, false); + mSceneDepthStencil = Create2DMultisampleTexture("SceneDepthStencil", GL_DEPTH24_STENCIL8, width, height, samples, false); + mSceneFog = Create2DMultisampleTexture("SceneFog", GL_RGBA8, width, height, samples, false); + mSceneNormal = Create2DMultisampleTexture("SceneNormal", GL_RGB10_A2, width, height, samples, false); + mSceneFB = CreateFrameBuffer("SceneFB", mSceneMultisample, 0, 0, mSceneDepthStencil, true); + mSceneDataFB = CreateFrameBuffer("SceneGBufferFB", mSceneMultisample, mSceneFog, mSceneNormal, mSceneDepthStencil, true); + } + else + { + mSceneMultisample = CreateRenderBuffer("SceneMultisample", GL_RGBA16F, width, height, samples); + mSceneDepthStencil = CreateRenderBuffer("SceneDepthStencil", GL_DEPTH24_STENCIL8, width, height, samples); + mSceneFB = CreateFrameBuffer("SceneFB", mSceneMultisample, mSceneDepthStencil, true); + mSceneDataFB = CreateFrameBuffer("SceneGBufferFB", mSceneMultisample, mSceneDepthStencil, true); + } + } + else + { + if (needsSceneTextures) + { + mSceneDepthStencil = Create2DTexture("SceneDepthStencil", GL_DEPTH24_STENCIL8, width, height); + mSceneFog = Create2DTexture("SceneFog", GL_RGBA8, width, height); + mSceneNormal = Create2DTexture("SceneNormal", GL_RGB10_A2, width, height); + mSceneFB = CreateFrameBuffer("SceneFB", mPipelineTexture[0], 0, 0, mSceneDepthStencil, false); + mSceneDataFB = CreateFrameBuffer("SceneGBufferFB", mPipelineTexture[0], mSceneFog, mSceneNormal, mSceneDepthStencil, false); + } + else + { + mSceneDepthStencil = CreateRenderBuffer("SceneDepthStencil", GL_DEPTH24_STENCIL8, width, height); + mSceneFB = CreateFrameBuffer("SceneFB", mPipelineTexture[0], mSceneDepthStencil, false); + mSceneDataFB = CreateFrameBuffer("SceneGBufferFB", mPipelineTexture[0], mSceneDepthStencil, false); + } + } +} + +//========================================================================== +// +// Creates the buffers needed for post processing steps +// +//========================================================================== + +void FGLRenderBuffers::CreatePipeline(int width, int height) +{ + ClearPipeline(); + ClearEyeBuffers(); + + for (int i = 0; i < NumPipelineTextures; i++) + { + mPipelineTexture[i] = Create2DTexture("PipelineTexture", GL_RGBA16F, width, height); + mPipelineFB[i] = CreateFrameBuffer("PipelineFB", mPipelineTexture[i]); + } +} + +//========================================================================== +// +// Creates bloom pass working buffers +// +//========================================================================== + +void FGLRenderBuffers::CreateBloom(int width, int height) +{ + ClearBloom(); + + // No scene, no bloom! + if (width <= 0 || height <= 0) + return; + + int bloomWidth = (width + 1) / 2; + int bloomHeight = (height + 1) / 2; + for (int i = 0; i < NumBloomLevels; i++) + { + auto &level = BloomLevels[i]; + level.Width = (bloomWidth + 1) / 2; + level.Height = (bloomHeight + 1) / 2; + + level.VTexture = Create2DTexture("Bloom.VTexture", GL_RGBA16F, level.Width, level.Height); + level.HTexture = Create2DTexture("Bloom.HTexture", GL_RGBA16F, level.Width, level.Height); + level.VFramebuffer = CreateFrameBuffer("Bloom.VFramebuffer", level.VTexture); + level.HFramebuffer = CreateFrameBuffer("Bloom.HFramebuffer", level.HTexture); + + bloomWidth = level.Width; + bloomHeight = level.Height; + } +} + +//========================================================================== +// +// Creates ambient occlusion working buffers +// +//========================================================================== + +void FGLRenderBuffers::CreateAmbientOcclusion(int width, int height) +{ + ClearAmbientOcclusion(); + + if (width <= 0 || height <= 0) + return; + + AmbientWidth = (width + 1) / 2; + AmbientHeight = (height + 1) / 2; + LinearDepthTexture = Create2DTexture("LinearDepthTexture", GL_R32F, AmbientWidth, AmbientHeight); + AmbientTexture0 = Create2DTexture("AmbientTexture0", GL_RG16F, AmbientWidth, AmbientHeight); + AmbientTexture1 = Create2DTexture("AmbientTexture1", GL_RG16F, AmbientWidth, AmbientHeight); + LinearDepthFB = CreateFrameBuffer("LinearDepthFB", LinearDepthTexture); + AmbientFB0 = CreateFrameBuffer("AmbientFB0", AmbientTexture0); + AmbientFB1 = CreateFrameBuffer("AmbientFB1", AmbientTexture1); + + // Must match quality enum in FSSAOShader::GetDefines + double numDirections[NumAmbientRandomTextures] = { 2.0, 4.0, 8.0 }; + + std::mt19937 generator(1337); + std::uniform_real_distribution distribution(0.0, 1.0); + for (int quality = 0; quality < NumAmbientRandomTextures; quality++) + { + int16_t randomValues[16 * 4]; + + for (int i = 0; i < 16; i++) + { + double angle = 2.0 * M_PI * distribution(generator) / numDirections[quality]; + double x = cos(angle); + double y = sin(angle); + double z = distribution(generator); + double w = distribution(generator); + + randomValues[i * 4 + 0] = (int16_t)clamp(x * 32767.0, -32768.0, 32767.0); + randomValues[i * 4 + 1] = (int16_t)clamp(y * 32767.0, -32768.0, 32767.0); + randomValues[i * 4 + 2] = (int16_t)clamp(z * 32767.0, -32768.0, 32767.0); + randomValues[i * 4 + 3] = (int16_t)clamp(w * 32767.0, -32768.0, 32767.0); + } + + AmbientRandomTexture[quality] = Create2DTexture("AmbientRandomTexture", GL_RGBA16_SNORM, 4, 4, randomValues); + } +} + +//========================================================================== +// +// Creates camera exposure level buffers +// +//========================================================================== + +void FGLRenderBuffers::CreateExposureLevels(int width, int height) +{ + ClearExposureLevels(); + + int i = 0; + do + { + width = MAX(width / 2, 1); + height = MAX(height / 2, 1); + + FString textureName, fbName; + textureName.Format("Exposure.Texture%d", i); + fbName.Format("Exposure.Framebuffer%d", i); + i++; + + FGLExposureTextureLevel level; + level.Width = width; + level.Height = height; + level.Texture = Create2DTexture(textureName, GL_R32F, level.Width, level.Height); + level.Framebuffer = CreateFrameBuffer(fbName, level.Texture); + ExposureLevels.Push(level); + } while (width > 1 || height > 1); + + ExposureTexture = Create2DTexture("Exposure.CameraTexture", GL_R32F, 1, 1); + ExposureFB = CreateFrameBuffer("Exposure.CameraFB", ExposureTexture); + + FirstExposureFrame = true; +} + +//========================================================================== +// +// Creates eye buffers if needed +// +//========================================================================== + +void FGLRenderBuffers::CreateEyeBuffers(int eye) +{ + if (mEyeFBs.Size() > eye) + return; + + GLint activeTex, textureBinding, frameBufferBinding; + glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); + glActiveTexture(GL_TEXTURE0); + glGetIntegerv(GL_TEXTURE_BINDING_2D, &textureBinding); + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &frameBufferBinding); + + while (mEyeFBs.Size() <= eye) + { + GLuint texture = Create2DTexture("EyeTexture", GL_RGBA16F, mWidth, mHeight); + mEyeTextures.Push(texture); + mEyeFBs.Push(CreateFrameBuffer("EyeFB", texture)); + } + + glBindTexture(GL_TEXTURE_2D, textureBinding); + glActiveTexture(activeTex); + glBindFramebuffer(GL_FRAMEBUFFER, frameBufferBinding); +} + +//========================================================================== +// +// Creates a 2D texture defaulting to linear filtering and clamp to edge +// +//========================================================================== + +GLuint FGLRenderBuffers::Create2DTexture(const FString &name, GLuint format, int width, int height, const void *data) +{ + GLuint handle = 0; + glGenTextures(1, &handle); + glBindTexture(GL_TEXTURE_2D, handle); + FGLDebug::LabelObject(GL_TEXTURE, handle, name); + + GLenum dataformat, datatype; + switch (format) + { + case GL_RGBA8: dataformat = GL_RGBA; datatype = GL_UNSIGNED_BYTE; break; + case GL_RGBA16: dataformat = GL_RGBA; datatype = GL_UNSIGNED_SHORT; break; + case GL_RGBA16F: dataformat = GL_RGBA; datatype = GL_FLOAT; break; + case GL_RGBA32F: dataformat = GL_RGBA; datatype = GL_FLOAT; break; + case GL_RGBA16_SNORM: dataformat = GL_RGBA; datatype = GL_SHORT; break; + case GL_R32F: dataformat = GL_RED; datatype = GL_FLOAT; break; + case GL_R16F: dataformat = GL_RED; datatype = GL_FLOAT; break; + case GL_RG32F: dataformat = GL_RG; datatype = GL_FLOAT; break; + case GL_RG16F: dataformat = GL_RG; datatype = GL_FLOAT; break; + case GL_RGB10_A2: dataformat = GL_RGBA; datatype = GL_UNSIGNED_INT_10_10_10_2; break; + case GL_DEPTH_COMPONENT24: dataformat = GL_DEPTH_COMPONENT; datatype = GL_FLOAT; break; + case GL_STENCIL_INDEX8: dataformat = GL_STENCIL_INDEX; datatype = GL_INT; break; + case GL_DEPTH24_STENCIL8: dataformat = GL_DEPTH_STENCIL; datatype = GL_UNSIGNED_INT_24_8; break; + default: I_FatalError("Unknown format passed to FGLRenderBuffers.Create2DTexture"); + } + + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, dataformat, datatype, data); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + return handle; +} + +GLuint FGLRenderBuffers::Create2DMultisampleTexture(const FString &name, GLuint format, int width, int height, int samples, bool fixedSampleLocations) +{ + GLuint handle = 0; + glGenTextures(1, &handle); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, handle); + FGLDebug::LabelObject(GL_TEXTURE, handle, name); + glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, format, width, height, fixedSampleLocations); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); + return handle; +} + +//========================================================================== +// +// Creates a render buffer +// +//========================================================================== + +GLuint FGLRenderBuffers::CreateRenderBuffer(const FString &name, GLuint format, int width, int height) +{ + GLuint handle = 0; + glGenRenderbuffers(1, &handle); + glBindRenderbuffer(GL_RENDERBUFFER, handle); + FGLDebug::LabelObject(GL_RENDERBUFFER, handle, name); + glRenderbufferStorage(GL_RENDERBUFFER, format, width, height); + return handle; +} + +GLuint FGLRenderBuffers::CreateRenderBuffer(const FString &name, GLuint format, int width, int height, int samples) +{ + if (samples <= 1) + return CreateRenderBuffer(name, format, width, height); + + GLuint handle = 0; + glGenRenderbuffers(1, &handle); + glBindRenderbuffer(GL_RENDERBUFFER, handle); + FGLDebug::LabelObject(GL_RENDERBUFFER, handle, name); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, format, width, height); + return handle; +} + +//========================================================================== +// +// Creates a frame buffer +// +//========================================================================== + +GLuint FGLRenderBuffers::CreateFrameBuffer(const FString &name, GLuint colorbuffer) +{ + GLuint handle = 0; + glGenFramebuffers(1, &handle); + glBindFramebuffer(GL_FRAMEBUFFER, handle); + FGLDebug::LabelObject(GL_FRAMEBUFFER, handle, name); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorbuffer, 0); + if (CheckFrameBufferCompleteness()) + ClearFrameBuffer(false, false); + return handle; +} + +GLuint FGLRenderBuffers::CreateFrameBuffer(const FString &name, GLuint colorbuffer, GLuint depthstencil, bool colorIsARenderBuffer) +{ + GLuint handle = 0; + glGenFramebuffers(1, &handle); + glBindFramebuffer(GL_FRAMEBUFFER, handle); + FGLDebug::LabelObject(GL_FRAMEBUFFER, handle, name); + if (colorIsARenderBuffer) + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorbuffer); + else + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorbuffer, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthstencil); + if (CheckFrameBufferCompleteness()) + ClearFrameBuffer(true, true); + return handle; +} + +GLuint FGLRenderBuffers::CreateFrameBuffer(const FString &name, GLuint colorbuffer0, GLuint colorbuffer1, GLuint colorbuffer2, GLuint depthstencil, bool multisample) +{ + GLuint handle = 0; + glGenFramebuffers(1, &handle); + glBindFramebuffer(GL_FRAMEBUFFER, handle); + FGLDebug::LabelObject(GL_FRAMEBUFFER, handle, name); + if (multisample) + { + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, colorbuffer0, 0); + if (colorbuffer1 != 0) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, colorbuffer1, 0); + if (colorbuffer2 != 0) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, colorbuffer2, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, depthstencil, 0); + } + else + { + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorbuffer0, 0); + if (colorbuffer1 != 0) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, colorbuffer1, 0); + if (colorbuffer2 != 0) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, colorbuffer2, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthstencil, 0); + } + if (CheckFrameBufferCompleteness()) + ClearFrameBuffer(true, true); + return handle; +} + +//========================================================================== +// +// Verifies that the frame buffer setup is valid +// +//========================================================================== + +bool FGLRenderBuffers::CheckFrameBufferCompleteness() +{ + GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (result == GL_FRAMEBUFFER_COMPLETE) + return true; + + FailedCreate = true; + + if (gl_debug_level > 0) + { + FString error = "glCheckFramebufferStatus failed: "; + switch (result) + { + default: error.AppendFormat("error code %d", (int)result); break; + case GL_FRAMEBUFFER_UNDEFINED: error << "GL_FRAMEBUFFER_UNDEFINED"; break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: error << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: error << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: error << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: error << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; + case GL_FRAMEBUFFER_UNSUPPORTED: error << "GL_FRAMEBUFFER_UNSUPPORTED"; break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: error << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: error << "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; break; + } + Printf("%s\n", error.GetChars()); + } + + return false; +} + +//========================================================================== +// +// Clear frame buffer to make sure it never contains uninitialized data +// +//========================================================================== + +void FGLRenderBuffers::ClearFrameBuffer(bool stencil, bool depth) +{ + GLboolean scissorEnabled; + GLint stencilValue; + GLdouble depthValue; + glGetBooleanv(GL_SCISSOR_TEST, &scissorEnabled); + glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &stencilValue); + glGetDoublev(GL_DEPTH_CLEAR_VALUE, &depthValue); + glDisable(GL_SCISSOR_TEST); + glClearColor(0.0, 0.0, 0.0, 0.0); + glClearDepth(0.0); + glClearStencil(0); + GLenum flags = GL_COLOR_BUFFER_BIT; + if (stencil) + flags |= GL_STENCIL_BUFFER_BIT; + if (depth) + flags |= GL_DEPTH_BUFFER_BIT; + glClear(flags); + glClearStencil(stencilValue); + glClearDepth(depthValue); + if (scissorEnabled) + glEnable(GL_SCISSOR_TEST); +} + +//========================================================================== +// +// Resolves the multisample frame buffer by copying it to the scene texture +// +//========================================================================== + +void FGLRenderBuffers::BlitSceneToTexture() +{ + mCurrentPipelineTexture = 0; + + if (mSamples <= 1) + return; + + glBindFramebuffer(GL_READ_FRAMEBUFFER, mSceneFB); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mPipelineFB[mCurrentPipelineTexture]); + glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); + + if ((gl.flags & RFL_INVALIDATE_BUFFER) != 0) + { + GLenum attachments[2] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, 2, attachments); + } + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +} + +//========================================================================== +// +// Eye textures and their frame buffers +// +//========================================================================== + +void FGLRenderBuffers::BlitToEyeTexture(int eye) +{ + CreateEyeBuffers(eye); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, mPipelineFB[mCurrentPipelineTexture]); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mEyeFBs[eye]); + glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); + + if ((gl.flags & RFL_INVALIDATE_BUFFER) != 0) + { + GLenum attachments[2] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_STENCIL_ATTACHMENT }; + glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, 2, attachments); + } + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +} + +void FGLRenderBuffers::BindEyeTexture(int eye, int texunit) +{ + CreateEyeBuffers(eye); + glActiveTexture(GL_TEXTURE0 + texunit); + glBindTexture(GL_TEXTURE_2D, mEyeTextures[eye]); +} + +void FGLRenderBuffers::BindEyeFB(int eye, bool readBuffer) +{ + CreateEyeBuffers(eye); + glBindFramebuffer(readBuffer ? GL_READ_FRAMEBUFFER : GL_FRAMEBUFFER, mEyeFBs[eye]); +} + +//========================================================================== +// +// Makes the scene frame buffer active (multisample, depth, stecil, etc.) +// +//========================================================================== + +void FGLRenderBuffers::BindSceneFB(bool sceneData) +{ + glBindFramebuffer(GL_FRAMEBUFFER, sceneData ? mSceneDataFB : mSceneFB); +} + +//========================================================================== +// +// Binds the scene color texture to the specified texture unit +// +//========================================================================== + +void FGLRenderBuffers::BindSceneColorTexture(int index) +{ + glActiveTexture(GL_TEXTURE0 + index); + if (mSamples > 1) + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mSceneMultisample); + else + glBindTexture(GL_TEXTURE_2D, mPipelineTexture[0]); +} + +//========================================================================== +// +// Binds the scene fog data texture to the specified texture unit +// +//========================================================================== + +void FGLRenderBuffers::BindSceneFogTexture(int index) +{ + glActiveTexture(GL_TEXTURE0 + index); + if (mSamples > 1) + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mSceneFog); + else + glBindTexture(GL_TEXTURE_2D, mSceneFog); +} + +//========================================================================== +// +// Binds the scene normal data texture to the specified texture unit +// +//========================================================================== + +void FGLRenderBuffers::BindSceneNormalTexture(int index) +{ + glActiveTexture(GL_TEXTURE0 + index); + if (mSamples > 1) + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mSceneNormal); + else + glBindTexture(GL_TEXTURE_2D, mSceneNormal); +} + +//========================================================================== +// +// Binds the depth texture to the specified texture unit +// +//========================================================================== + +void FGLRenderBuffers::BindSceneDepthTexture(int index) +{ + glActiveTexture(GL_TEXTURE0 + index); + if (mSamples > 1) + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mSceneDepthStencil); + else + glBindTexture(GL_TEXTURE_2D, mSceneDepthStencil); +} + +//========================================================================== +// +// Binds the current scene/effect/hud texture to the specified texture unit +// +//========================================================================== + +void FGLRenderBuffers::BindCurrentTexture(int index) +{ + glActiveTexture(GL_TEXTURE0 + index); + glBindTexture(GL_TEXTURE_2D, mPipelineTexture[mCurrentPipelineTexture]); +} + +//========================================================================== +// +// Makes the frame buffer for the current texture active +// +//========================================================================== + +void FGLRenderBuffers::BindCurrentFB() +{ + glBindFramebuffer(GL_FRAMEBUFFER, mPipelineFB[mCurrentPipelineTexture]); +} + +//========================================================================== +// +// Makes the frame buffer for the next texture active +// +//========================================================================== + +void FGLRenderBuffers::BindNextFB() +{ + int out = (mCurrentPipelineTexture + 1) % NumPipelineTextures; + glBindFramebuffer(GL_FRAMEBUFFER, mPipelineFB[out]); +} + +//========================================================================== +// +// Next pipeline texture now contains the output +// +//========================================================================== + +void FGLRenderBuffers::NextTexture() +{ + mCurrentPipelineTexture = (mCurrentPipelineTexture + 1) % NumPipelineTextures; +} + +//========================================================================== +// +// Makes the screen frame buffer active +// +//========================================================================== + +void FGLRenderBuffers::BindOutputFB() +{ + glBindFramebuffer(GL_FRAMEBUFFER, mOutputFB); +} + +//========================================================================== +// +// Returns true if render buffers are supported and should be used +// +//========================================================================== + +bool FGLRenderBuffers::IsEnabled() +{ + return BuffersActive && !gl.legacyMode && !FailedCreate; +} + +bool FGLRenderBuffers::FailedCreate = false; +bool FGLRenderBuffers::BuffersActive = false; diff --git a/src/gl/renderer/gl_renderbuffers.h b/src/gl/renderer/gl_renderbuffers.h new file mode 100644 index 000000000..f2f7b7cb9 --- /dev/null +++ b/src/gl/renderer/gl_renderbuffers.h @@ -0,0 +1,140 @@ +#ifndef __GL_RENDERBUFFERS_H +#define __GL_RENDERBUFFERS_H + +#include "gl/shaders/gl_shader.h" + +class FGLBloomTextureLevel +{ +public: + GLuint VTexture = 0; + GLuint VFramebuffer = 0; + GLuint HTexture = 0; + GLuint HFramebuffer = 0; + GLuint Width = 0; + GLuint Height = 0; +}; + +class FGLExposureTextureLevel +{ +public: + GLuint Texture = 0; + GLuint Framebuffer = 0; + GLuint Width = 0; + GLuint Height = 0; +}; + +class FGLRenderBuffers +{ +public: + FGLRenderBuffers(); + ~FGLRenderBuffers(); + + bool Setup(int width, int height, int sceneWidth, int sceneHeight); + + void BindSceneFB(bool sceneData); + void BindSceneColorTexture(int index); + void BindSceneFogTexture(int index); + void BindSceneNormalTexture(int index); + void BindSceneDepthTexture(int index); + void BlitSceneToTexture(); + + void BindCurrentTexture(int index); + void BindCurrentFB(); + void BindNextFB(); + void NextTexture(); + + void BindOutputFB(); + + void BlitToEyeTexture(int eye); + void BindEyeTexture(int eye, int texunit); + void BindEyeFB(int eye, bool readBuffer = false); + + enum { NumBloomLevels = 4 }; + FGLBloomTextureLevel BloomLevels[NumBloomLevels]; + + TArray ExposureLevels; + GLuint ExposureTexture = 0; + GLuint ExposureFB = 0; + bool FirstExposureFrame = true; + + // Ambient occlusion buffers + GLuint LinearDepthTexture = 0; + GLuint LinearDepthFB = 0; + GLuint AmbientTexture0 = 0; + GLuint AmbientTexture1 = 0; + GLuint AmbientFB0 = 0; + GLuint AmbientFB1 = 0; + int AmbientWidth = 0; + int AmbientHeight = 0; + enum { NumAmbientRandomTextures = 3 }; + GLuint AmbientRandomTexture[NumAmbientRandomTextures]; + + static bool IsEnabled(); + + int GetWidth() const { return mWidth; } + int GetHeight() const { return mHeight; } + + int GetSceneWidth() const { return mSceneWidth; } + int GetSceneHeight() const { return mSceneHeight; } + +private: + void ClearScene(); + void ClearPipeline(); + void ClearEyeBuffers(); + void ClearBloom(); + void ClearExposureLevels(); + void ClearAmbientOcclusion(); + void CreateScene(int width, int height, int samples, bool needsSceneTextures); + void CreatePipeline(int width, int height); + void CreateBloom(int width, int height); + void CreateExposureLevels(int width, int height); + void CreateEyeBuffers(int eye); + void CreateAmbientOcclusion(int width, int height); + GLuint Create2DTexture(const FString &name, GLuint format, int width, int height, const void *data = nullptr); + GLuint Create2DMultisampleTexture(const FString &name, GLuint format, int width, int height, int samples, bool fixedSampleLocations); + GLuint CreateRenderBuffer(const FString &name, GLuint format, int width, int height); + GLuint CreateRenderBuffer(const FString &name, GLuint format, int width, int height, int samples); + GLuint CreateFrameBuffer(const FString &name, GLuint colorbuffer); + GLuint CreateFrameBuffer(const FString &name, GLuint colorbuffer, GLuint depthstencil, bool colorIsARenderBuffer); + GLuint CreateFrameBuffer(const FString &name, GLuint colorbuffer0, GLuint colorbuffer1, GLuint colorbuffer2, GLuint depthstencil, bool multisample); + bool CheckFrameBufferCompleteness(); + void ClearFrameBuffer(bool stencil, bool depth); + void DeleteTexture(GLuint &handle); + void DeleteRenderBuffer(GLuint &handle); + void DeleteFrameBuffer(GLuint &handle); + + int mWidth = 0; + int mHeight = 0; + int mSamples = 0; + int mMaxSamples = 0; + int mSceneWidth = 0; + int mSceneHeight = 0; + + static const int NumPipelineTextures = 2; + int mCurrentPipelineTexture = 0; + + // Buffers for the scene + GLuint mSceneMultisample = 0; + GLuint mSceneDepthStencil = 0; + GLuint mSceneFog = 0; + GLuint mSceneNormal = 0; + GLuint mSceneFB = 0; + GLuint mSceneDataFB = 0; + bool mSceneUsesTextures = false; + + // Effect/HUD buffers + GLuint mPipelineTexture[NumPipelineTextures]; + GLuint mPipelineFB[NumPipelineTextures]; + + // Back buffer frame buffer + GLuint mOutputFB = 0; + + // Eye buffers + TArray mEyeTextures; + TArray mEyeFBs; + + static bool FailedCreate; + static bool BuffersActive; +}; + +#endif \ No newline at end of file diff --git a/src/gl/renderer/gl_renderer.cpp b/src/gl/renderer/gl_renderer.cpp new file mode 100644 index 000000000..90687bcb7 --- /dev/null +++ b/src/gl/renderer/gl_renderer.cpp @@ -0,0 +1,456 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl1_renderer.cpp +** Renderer interface +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "r_data/r_translate.h" +#include "m_png.h" +#include "m_crc32.h" +#include "w_wad.h" +//#include "gl/gl_intern.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "doomstat.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "gl/renderer/gl_2ddrawer.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/shaders/gl_shader.h" +#include "gl/shaders/gl_ambientshader.h" +#include "gl/shaders/gl_bloomshader.h" +#include "gl/shaders/gl_blurshader.h" +#include "gl/shaders/gl_tonemapshader.h" +#include "gl/shaders/gl_colormapshader.h" +#include "gl/shaders/gl_lensshader.h" +#include "gl/shaders/gl_fxaashader.h" +#include "gl/shaders/gl_presentshader.h" +#include "gl/shaders/gl_present3dRowshader.h" +#include "gl/stereo3d/gl_stereo3d.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_material.h" +#include "gl/textures/gl_samplers.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/models/gl_models.h" +#include "gl/dynlights/gl_lightbuffer.h" + +EXTERN_CVAR(Int, screenblocks) + +CVAR(Bool, gl_scale_viewport, true, 0); + +//=========================================================================== +// +// Renderer interface +// +//=========================================================================== + +//----------------------------------------------------------------------------- +// +// Initialize +// +//----------------------------------------------------------------------------- + +FGLRenderer::FGLRenderer(OpenGLFrameBuffer *fb) +{ + framebuffer = fb; + mClipPortal = nullptr; + mCurrentPortal = nullptr; + mMirrorCount = 0; + mPlaneMirrorCount = 0; + mLightCount = 0; + mAngles = FRotator(0.f, 0.f, 0.f); + mViewVector = FVector2(0,0); + mVBO = nullptr; + mSkyVBO = nullptr; + gl_spriteindex = 0; + mShaderManager = nullptr; + gllight = glpart2 = glpart = mirrortexture = nullptr; + mLights = nullptr; + m2DDrawer = nullptr; + mTonemapPalette = nullptr; + mBuffers = nullptr; + mPresentShader = nullptr; + mPresent3dCheckerShader = nullptr; + mPresent3dColumnShader = nullptr; + mPresent3dRowShader = nullptr; + mBloomExtractShader = nullptr; + mBloomCombineShader = nullptr; + mExposureExtractShader = nullptr; + mExposureAverageShader = nullptr; + mExposureCombineShader = nullptr; + mBlurShader = nullptr; + mTonemapShader = nullptr; + mTonemapPalette = nullptr; + mColormapShader = nullptr; + mLensShader = nullptr; + mLinearDepthShader = nullptr; + mDepthBlurShader = nullptr; + mSSAOShader = nullptr; + mSSAOCombineShader = nullptr; + mFXAAShader = nullptr; + mFXAALumaShader = nullptr; +} + +void gl_LoadModels(); +void gl_FlushModels(); + +void FGLRenderer::Initialize(int width, int height) +{ + mBuffers = new FGLRenderBuffers(); + mLinearDepthShader = new FLinearDepthShader(); + mDepthBlurShader = new FDepthBlurShader(); + mSSAOShader = new FSSAOShader(); + mSSAOCombineShader = new FSSAOCombineShader(); + mBloomExtractShader = new FBloomExtractShader(); + mBloomCombineShader = new FBloomCombineShader(); + mExposureExtractShader = new FExposureExtractShader(); + mExposureAverageShader = new FExposureAverageShader(); + mExposureCombineShader = new FExposureCombineShader(); + mBlurShader = new FBlurShader(); + mTonemapShader = new FTonemapShader(); + mColormapShader = new FColormapShader(); + mTonemapPalette = nullptr; + mLensShader = new FLensShader(); + mFXAAShader = new FFXAAShader; + mFXAALumaShader = new FFXAALumaShader; + mPresentShader = new FPresentShader(); + mPresent3dCheckerShader = new FPresent3DCheckerShader(); + mPresent3dColumnShader = new FPresent3DColumnShader(); + mPresent3dRowShader = new FPresent3DRowShader(); + m2DDrawer = new F2DDrawer; + + // needed for the core profile, because someone decided it was a good idea to remove the default VAO. + if (!gl.legacyMode) + { + glGenVertexArrays(1, &mVAOID); + glBindVertexArray(mVAOID); + FGLDebug::LabelObject(GL_VERTEX_ARRAY, mVAOID, "FGLRenderer.mVAOID"); + } + else mVAOID = 0; + + gllight = FTexture::CreateTexture(Wads.GetNumForFullName("glstuff/gllight.png"), FTexture::TEX_MiscPatch); + glpart2 = FTexture::CreateTexture(Wads.GetNumForFullName("glstuff/glpart2.png"), FTexture::TEX_MiscPatch); + glpart = FTexture::CreateTexture(Wads.GetNumForFullName("glstuff/glpart.png"), FTexture::TEX_MiscPatch); + mirrortexture = FTexture::CreateTexture(Wads.GetNumForFullName("glstuff/mirror.png"), FTexture::TEX_MiscPatch); + + mVBO = new FFlatVertexBuffer(width, height); + mSkyVBO = new FSkyVertexBuffer; + if (!gl.legacyMode) mLights = new FLightBuffer(); + else mLights = NULL; + gl_RenderState.SetVertexBuffer(mVBO); + mFBID = 0; + mOldFBID = 0; + + SetupLevel(); + mShaderManager = new FShaderManager; + mSamplerManager = new FSamplerManager; + gl_LoadModels(); +} + +FGLRenderer::~FGLRenderer() +{ + gl_FlushModels(); + gl_DeleteAllAttachedLights(); + FMaterial::FlushAll(); + if (m2DDrawer != nullptr) delete m2DDrawer; + if (mShaderManager != NULL) delete mShaderManager; + if (mSamplerManager != NULL) delete mSamplerManager; + if (mVBO != NULL) delete mVBO; + if (mSkyVBO != NULL) delete mSkyVBO; + if (mLights != NULL) delete mLights; + if (glpart2) delete glpart2; + if (glpart) delete glpart; + if (mirrortexture) delete mirrortexture; + if (mFBID != 0) glDeleteFramebuffers(1, &mFBID); + if (mVAOID != 0) + { + glBindVertexArray(0); + glDeleteVertexArrays(1, &mVAOID); + } + if (mBuffers) delete mBuffers; + if (mPresentShader) delete mPresentShader; + if (mLinearDepthShader) delete mLinearDepthShader; + if (mDepthBlurShader) delete mDepthBlurShader; + if (mSSAOShader) delete mSSAOShader; + if (mSSAOCombineShader) delete mSSAOCombineShader; + if (mPresent3dCheckerShader) delete mPresent3dCheckerShader; + if (mPresent3dColumnShader) delete mPresent3dColumnShader; + if (mPresent3dRowShader) delete mPresent3dRowShader; + if (mBloomExtractShader) delete mBloomExtractShader; + if (mBloomCombineShader) delete mBloomCombineShader; + if (mExposureExtractShader) delete mExposureExtractShader; + if (mExposureAverageShader) delete mExposureAverageShader; + if (mExposureCombineShader) delete mExposureCombineShader; + if (mBlurShader) delete mBlurShader; + if (mTonemapShader) delete mTonemapShader; + if (mTonemapPalette) delete mTonemapPalette; + if (mColormapShader) delete mColormapShader; + if (mLensShader) delete mLensShader; + delete mFXAAShader; + delete mFXAALumaShader; +} + +//========================================================================== +// +// Calculates the viewport values needed for 2D and 3D operations +// +//========================================================================== + +void FGLRenderer::SetOutputViewport(GL_IRECT *bounds) +{ + if (bounds) + { + mSceneViewport = *bounds; + mScreenViewport = *bounds; + mOutputLetterbox = *bounds; + return; + } + + // Special handling so the view with a visible status bar displays properly + int height, width; + if (screenblocks >= 10) + { + height = framebuffer->GetHeight(); + width = framebuffer->GetWidth(); + } + else + { + height = (screenblocks*framebuffer->GetHeight() / 10) & ~7; + width = (screenblocks*framebuffer->GetWidth() / 10); + } + + // Back buffer letterbox for the final output + int clientWidth = framebuffer->GetClientWidth(); + int clientHeight = framebuffer->GetClientHeight(); + if (clientWidth == 0 || clientHeight == 0) + { + // When window is minimized there may not be any client area. + // Pretend to the rest of the render code that we just have a very small window. + clientWidth = 160; + clientHeight = 120; + } + int screenWidth = framebuffer->GetWidth(); + int screenHeight = framebuffer->GetHeight(); + float scale = MIN(clientWidth / (float)screenWidth, clientHeight / (float)screenHeight); + mOutputLetterbox.width = (int)round(screenWidth * scale); + mOutputLetterbox.height = (int)round(screenHeight * scale); + mOutputLetterbox.left = (clientWidth - mOutputLetterbox.width) / 2; + mOutputLetterbox.top = (clientHeight - mOutputLetterbox.height) / 2; + + // The entire renderable area, including the 2D HUD + mScreenViewport.left = 0; + mScreenViewport.top = 0; + mScreenViewport.width = screenWidth; + mScreenViewport.height = screenHeight; + + // Viewport for the 3D scene + mSceneViewport.left = viewwindowx; + mSceneViewport.top = screenHeight - (height + viewwindowy - ((height - viewheight) / 2)); + mSceneViewport.width = viewwidth; + mSceneViewport.height = height; + + // Scale viewports to fit letterbox + if (gl_scale_viewport || !FGLRenderBuffers::IsEnabled()) + { + mScreenViewport.width = mOutputLetterbox.width; + mScreenViewport.height = mOutputLetterbox.height; + mSceneViewport.left = (int)round(mSceneViewport.left * scale); + mSceneViewport.top = (int)round(mSceneViewport.top * scale); + mSceneViewport.width = (int)round(mSceneViewport.width * scale); + mSceneViewport.height = (int)round(mSceneViewport.height * scale); + + // Without render buffers we have to render directly to the letterbox + if (!FGLRenderBuffers::IsEnabled()) + { + mScreenViewport.left += mOutputLetterbox.left; + mScreenViewport.top += mOutputLetterbox.top; + mSceneViewport.left += mOutputLetterbox.left; + mSceneViewport.top += mOutputLetterbox.top; + } + } + + s3d::Stereo3DMode::getCurrentMode().AdjustViewports(); +} + +//=========================================================================== +// +// Calculates the OpenGL window coordinates for a zdoom screen position +// +//=========================================================================== + +int FGLRenderer::ScreenToWindowX(int x) +{ + return mScreenViewport.left + (int)round(x * mScreenViewport.width / (float)framebuffer->GetWidth()); +} + +int FGLRenderer::ScreenToWindowY(int y) +{ + return mScreenViewport.top + mScreenViewport.height - (int)round(y * mScreenViewport.height / (float)framebuffer->GetHeight()); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::SetupLevel() +{ + mVBO->CreateVBO(); +} + +void FGLRenderer::Begin2D() +{ + if (mBuffers->Setup(mScreenViewport.width, mScreenViewport.height, mSceneViewport.width, mSceneViewport.height)) + { + if (mDrawingScene2D) + mBuffers->BindSceneFB(false); + else + mBuffers->BindCurrentFB(); + } + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + glScissor(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + + gl_RenderState.EnableFog(false); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::ProcessLowerMiniseg(seg_t *seg, sector_t * frontsector, sector_t * backsector) +{ + GLWall wall; + wall.ProcessLowerMiniseg(seg, frontsector, backsector); + rendered_lines++; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::ProcessSprite(AActor *thing, sector_t *sector, bool thruportal) +{ + GLSprite glsprite; + glsprite.Process(thing, sector, thruportal); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::ProcessParticle(particle_t *part, sector_t *sector) +{ + GLSprite glsprite; + glsprite.ProcessParticle(part, sector);//, 0, 0); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::ProcessSector(sector_t *fakesector) +{ + GLFlat glflat; + glflat.ProcessSector(fakesector); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::FlushTextures() +{ + FMaterial::FlushAll(); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +bool FGLRenderer::StartOffscreen() +{ + bool firstBind = (mFBID == 0); + if (mFBID == 0) + glGenFramebuffers(1, &mFBID); + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &mOldFBID); + glBindFramebuffer(GL_FRAMEBUFFER, mFBID); + if (firstBind) + FGLDebug::LabelObject(GL_FRAMEBUFFER, mFBID, "OffscreenFB"); + return true; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLRenderer::EndOffscreen() +{ + glBindFramebuffer(GL_FRAMEBUFFER, mOldFBID); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +unsigned char *FGLRenderer::GetTextureBuffer(FTexture *tex, int &w, int &h) +{ + FMaterial * gltex = FMaterial::ValidateTexture(tex, false); + if (gltex) + { + return gltex->CreateTexBuffer(0, w, h); + } + return NULL; +} diff --git a/src/gl/renderer/gl_renderer.h b/src/gl/renderer/gl_renderer.h new file mode 100644 index 000000000..f31736777 --- /dev/null +++ b/src/gl/renderer/gl_renderer.h @@ -0,0 +1,259 @@ +#ifndef __GL_RENDERER_H +#define __GL_RENDERER_H + +#include "r_defs.h" +#include "v_video.h" +#include "vectors.h" +#include "r_renderer.h" +#include "gl/data/gl_matrix.h" + +struct particle_t; +class FCanvasTexture; +class FFlatVertexBuffer; +class FSkyVertexBuffer; +class OpenGLFrameBuffer; +struct FDrawInfo; +class FShaderManager; +class GLPortal; +class FLightBuffer; +class FSamplerManager; +class DPSprite; +class FGLRenderBuffers; +class FLinearDepthShader; +class FDepthBlurShader; +class FSSAOShader; +class FSSAOCombineShader; +class FBloomExtractShader; +class FBloomCombineShader; +class FExposureExtractShader; +class FExposureAverageShader; +class FExposureCombineShader; +class FBlurShader; +class FTonemapShader; +class FColormapShader; +class FLensShader; +class FFXAALumaShader; +class FFXAAShader; +class FPresentShader; +class FPresent3DCheckerShader; +class FPresent3DColumnShader; +class FPresent3DRowShader; +class F2DDrawer; +class FHardwareTexture; + +inline float DEG2RAD(float deg) +{ + return deg * float(M_PI / 180.0); +} + +inline float RAD2DEG(float deg) +{ + return deg * float(180. / M_PI); +} + +enum SectorRenderFlags +{ + // This is used to avoid creating too many drawinfos + SSRF_RENDERFLOOR = 1, + SSRF_RENDERCEILING = 2, + SSRF_RENDER3DPLANES = 4, + SSRF_RENDERALL = 7, + SSRF_PROCESSED = 8, + SSRF_SEEN = 16, +}; + +struct GL_IRECT +{ + int left,top; + int width,height; + + + void Offset(int xofs,int yofs) + { + left+=xofs; + top+=yofs; + } +}; + +enum +{ + DM_MAINVIEW, + DM_OFFSCREEN, + DM_PORTAL +}; + +class FGLRenderer +{ +public: + + OpenGLFrameBuffer *framebuffer; + GLPortal *mClipPortal; + GLPortal *mCurrentPortal; + int mMirrorCount; + int mPlaneMirrorCount; + int mLightCount; + float mCurrentFoV; + AActor *mViewActor; + FShaderManager *mShaderManager; + FSamplerManager *mSamplerManager; + int gl_spriteindex; + unsigned int mFBID; + unsigned int mVAOID; + int mOldFBID; + + FGLRenderBuffers *mBuffers; + FLinearDepthShader *mLinearDepthShader; + FSSAOShader *mSSAOShader; + FDepthBlurShader *mDepthBlurShader; + FSSAOCombineShader *mSSAOCombineShader; + FBloomExtractShader *mBloomExtractShader; + FBloomCombineShader *mBloomCombineShader; + FExposureExtractShader *mExposureExtractShader; + FExposureAverageShader *mExposureAverageShader; + FExposureCombineShader *mExposureCombineShader; + FBlurShader *mBlurShader; + FTonemapShader *mTonemapShader; + FColormapShader *mColormapShader; + FHardwareTexture *mTonemapPalette; + FLensShader *mLensShader; + FFXAALumaShader *mFXAALumaShader; + FFXAAShader *mFXAAShader; + FPresentShader *mPresentShader; + FPresent3DCheckerShader *mPresent3dCheckerShader; + FPresent3DColumnShader *mPresent3dColumnShader; + FPresent3DRowShader *mPresent3dRowShader; + + FTexture *gllight; + FTexture *glpart2; + FTexture *glpart; + FTexture *mirrortexture; + + float mSky1Pos, mSky2Pos; + + FRotator mAngles; + FVector2 mViewVector; + + FFlatVertexBuffer *mVBO; + FSkyVertexBuffer *mSkyVBO; + FLightBuffer *mLights; + F2DDrawer *m2DDrawer; + + GL_IRECT mScreenViewport; + GL_IRECT mSceneViewport; + GL_IRECT mOutputLetterbox; + bool mDrawingScene2D = false; + + float mSceneClearColor[3]; + + FGLRenderer(OpenGLFrameBuffer *fb); + ~FGLRenderer() ; + + void SetOutputViewport(GL_IRECT *bounds); + int ScreenToWindowX(int x); + int ScreenToWindowY(int y); + + angle_t FrustumAngle(); + void SetViewArea(); + void Set3DViewport(bool mainview); + void Reset3DViewport(); + sector_t *RenderViewpoint (AActor * camera, GL_IRECT * bounds, float fov, float ratio, float fovratio, bool mainview, bool toscreen); + void RenderView(player_t *player); + void SetViewAngle(DAngle viewangle); + void SetupView(float viewx, float viewy, float viewz, DAngle viewangle, bool mirror, bool planemirror); + + void Initialize(int width, int height); + + void CreateScene(); + void RenderMultipassStuff(); + void RenderScene(int recursion); + void RenderTranslucent(); + void DrawScene(int drawmode); + void DrawBlend(sector_t * viewsector); + + void DrawPSprite (player_t * player,DPSprite *psp,float sx, float sy, bool hudModelStep, int OverrideShader, bool alphatexture); + void DrawPlayerSprites(sector_t * viewsector, bool hudModelStep); + void DrawTargeterSprites(); + + void Begin2D(); + void ClearBorders(); + + void ProcessLowerMiniseg(seg_t *seg, sector_t * frontsector, sector_t * backsector); + void ProcessSprite(AActor *thing, sector_t *sector, bool thruportal); + void ProcessParticle(particle_t *part, sector_t *sector); + void ProcessSector(sector_t *fakesector); + void FlushTextures(); + unsigned char *GetTextureBuffer(FTexture *tex, int &w, int &h); + void SetupLevel(); + + void RenderScreenQuad(); + void SetFixedColormap (player_t *player); + void WriteSavePic (player_t *player, FileWriter *file, int width, int height); + void EndDrawScene(sector_t * viewsector); + void PostProcessScene(); + void AmbientOccludeScene(); + void UpdateCameraExposure(); + void BloomScene(); + void TonemapScene(); + void ColormapScene(); + void CreateTonemapPalette(); + void ClearTonemapPalette(); + void LensDistortScene(); + void ApplyFXAA(); + void CopyToBackbuffer(const GL_IRECT *bounds, bool applyGamma); + void DrawPresentTexture(const GL_IRECT &box, bool applyGamma); + void Flush(); + + void SetProjection(float fov, float ratio, float fovratio); + void SetProjection(VSMatrix matrix); // raw matrix input from stereo 3d modes + void SetViewMatrix(float vx, float vy, float vz, bool mirror, bool planemirror); + void ProcessScene(bool toscreen = false); + + bool StartOffscreen(); + void EndOffscreen(); + + void StartSimplePolys(); + void FinishSimplePolys(); + + void FillSimplePoly(FTexture *texture, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel, int bottomclip); + + int PTM_BestColor (const uint32 *pal_in, int r, int g, int b, int first, int num); + + static float GetZNear() { return 5.f; } + static float GetZFar() { return 65536.f; } +}; + +// Global functions. Make them members of GLRenderer later? +void gl_RenderBSPNode (void *node); +bool gl_CheckClip(side_t * sidedef, sector_t * frontsector, sector_t * backsector); +void gl_CheckViewArea(vertex_t *v1, vertex_t *v2, sector_t *frontsector, sector_t *backsector); + +typedef enum +{ + area_normal, + area_below, + area_above, + area_default +} area_t; + +extern area_t in_area; + + +sector_t * gl_FakeFlat(sector_t * sec, sector_t * dest, area_t in_area, bool back); +inline sector_t * gl_FakeFlat(sector_t * sec, sector_t * dest, bool back) +{ + return gl_FakeFlat(sec, dest, in_area, back); +} + +struct TexFilter_s +{ + int minfilter; + int magfilter; + bool mipmapping; +} ; + + +extern FGLRenderer *GLRenderer; + +#endif \ No newline at end of file diff --git a/src/gl/renderer/gl_renderstate.cpp b/src/gl/renderer/gl_renderstate.cpp new file mode 100644 index 000000000..fa8237cca --- /dev/null +++ b/src/gl/renderer/gl_renderstate.cpp @@ -0,0 +1,395 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2009-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_renderstate.cpp +** Render state maintenance +** +*/ + +#include "templates.h" +#include "gl/system/gl_system.h" +#include "gl/system/gl_interface.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_shader.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_colormap.h" +#include "gl/dynlights//gl_lightbuffer.h" +#include "gl/renderer/gl_renderbuffers.h" + +void gl_SetTextureMode(int type); + +FRenderState gl_RenderState; + +CVAR(Bool, gl_direct_state_change, true, 0) + + +static VSMatrix identityMatrix(1); +TArray gl_MatrixStack; + +//========================================================================== +// +// +// +//========================================================================== + +void FRenderState::Reset() +{ + mTextureEnabled = true; + mClipLineEnabled = mSplitEnabled = mBrightmapEnabled = mFogEnabled = mGlowEnabled = false; + mColorMask[0] = mColorMask[1] = mColorMask[2] = mColorMask[3] = true; + currentColorMask[0] = currentColorMask[1] = currentColorMask[2] = currentColorMask[3] = true; + mFogColor.d = -1; + mTextureMode = -1; + mLightIndex = -1; + mDesaturation = 0; + mSrcBlend = GL_SRC_ALPHA; + mDstBlend = GL_ONE_MINUS_SRC_ALPHA; + mAlphaThreshold = 0.5f; + mBlendEquation = GL_FUNC_ADD; + mModelMatrixEnabled = false; + mTextureMatrixEnabled = false; + mObjectColor = 0xffffffff; + mVertexBuffer = mCurrentVertexBuffer = NULL; + mColormapState = CM_DEFAULT; + mSoftLight = 0; + mLightParms[0] = mLightParms[1] = mLightParms[2] = 0.0f; + mLightParms[3] = -1.f; + mSpecialEffect = EFF_NONE; + mClipHeight = 0.f; + mClipHeightDirection = 0.f; + mShaderTimer = 0.0f; + ClearClipSplit(); + + stSrcBlend = stDstBlend = -1; + stBlendEquation = -1; + stAlphaThreshold = -1.f; + stAlphaTest = 0; + mLastDepthClamp = true; + mInterpolationFactor = 0.0f; + + mColor.Set(1.0f, 1.0f, 1.0f, 1.0f); + mCameraPos.Set(0.0f, 0.0f, 0.0f, 0.0f); + mGlowTop.Set(0.0f, 0.0f, 0.0f, 0.0f); + mGlowBottom.Set(0.0f, 0.0f, 0.0f, 0.0f); + mGlowTopPlane.Set(0.0f, 0.0f, 0.0f, 0.0f); + mGlowBottomPlane.Set(0.0f, 0.0f, 0.0f, 0.0f); + mSplitTopPlane.Set(0.0f, 0.0f, 0.0f, 0.0f); + mSplitBottomPlane.Set(0.0f, 0.0f, 0.0f, 0.0f); + mClipLine.Set(0.0f, 0.0f, 0.0f, 0.0f); + mDynColor.Set(0.0f, 0.0f, 0.0f, 0.0f); + mEffectState = 0; + activeShader = nullptr; + mProjectionMatrix.loadIdentity(); + mViewMatrix.loadIdentity(); + mModelMatrix.loadIdentity(); + mTextureMatrix.loadIdentity(); + mPassType = NORMAL_PASS; +} + +//========================================================================== +// +// Apply shader settings +// +//========================================================================== + +bool FRenderState::ApplyShader() +{ + static const float nulvec[] = { 0.f, 0.f, 0.f, 0.f }; + if (mSpecialEffect > EFF_NONE) + { + activeShader = GLRenderer->mShaderManager->BindEffect(mSpecialEffect, mPassType); + } + else + { + activeShader = GLRenderer->mShaderManager->Get(mTextureEnabled ? mEffectState : 4, mAlphaThreshold >= 0.f, mPassType); + activeShader->Bind(); + } + + int fogset = 0; + + if (mFogEnabled) + { + if ((mFogColor & 0xffffff) == 0) + { + fogset = gl_fogmode; + } + else + { + fogset = -gl_fogmode; + } + } + + glVertexAttrib4fv(VATTR_COLOR, mColor.vec); + glVertexAttrib4fv(VATTR_NORMAL, mNormal.vec); + + activeShader->muDesaturation.Set(mDesaturation / 255.f); + activeShader->muFogEnabled.Set(fogset); + activeShader->muTextureMode.Set(mTextureMode); + activeShader->muCameraPos.Set(mCameraPos.vec); + activeShader->muLightParms.Set(mLightParms); + activeShader->muFogColor.Set(mFogColor); + activeShader->muObjectColor.Set(mObjectColor); + activeShader->muDynLightColor.Set(mDynColor.vec); + activeShader->muInterpolationFactor.Set(mInterpolationFactor); + activeShader->muClipHeight.Set(mClipHeight); + activeShader->muClipHeightDirection.Set(mClipHeightDirection); + activeShader->muTimer.Set(gl_frameMS * mShaderTimer / 1000.f); + activeShader->muAlphaThreshold.Set(mAlphaThreshold); + activeShader->muLightIndex.Set(mLightIndex); // will always be -1 for now + activeShader->muClipSplit.Set(mClipSplit); + + if (mGlowEnabled) + { + activeShader->muGlowTopColor.Set(mGlowTop.vec); + activeShader->muGlowBottomColor.Set(mGlowBottom.vec); + activeShader->muGlowTopPlane.Set(mGlowTopPlane.vec); + activeShader->muGlowBottomPlane.Set(mGlowBottomPlane.vec); + activeShader->currentglowstate = 1; + } + else if (activeShader->currentglowstate) + { + // if glowing is on, disable it. + activeShader->muGlowTopColor.Set(nulvec); + activeShader->muGlowBottomColor.Set(nulvec); + activeShader->muGlowTopPlane.Set(nulvec); + activeShader->muGlowBottomPlane.Set(nulvec); + activeShader->currentglowstate = 0; + } + + if (mSplitEnabled) + { + activeShader->muSplitTopPlane.Set(mSplitTopPlane.vec); + activeShader->muSplitBottomPlane.Set(mSplitBottomPlane.vec); + activeShader->currentsplitstate = 1; + } + else if (activeShader->currentsplitstate) + { + activeShader->muSplitTopPlane.Set(nulvec); + activeShader->muSplitBottomPlane.Set(nulvec); + activeShader->currentsplitstate = 0; + } + + if (mClipLineEnabled) + { + activeShader->muClipLine.Set(mClipLine.vec); + activeShader->currentcliplinestate = 1; + } + else if (activeShader->currentcliplinestate) + { + activeShader->muClipLine.Set(-10000000.0, 0, 0, 0); + activeShader->currentcliplinestate = 0; + } + + if (mColormapState != activeShader->currentfixedcolormap) + { + float r, g, b; + activeShader->currentfixedcolormap = mColormapState; + if (mColormapState == CM_DEFAULT) + { + activeShader->muFixedColormap.Set(0); + } + else if (mColormapState > CM_DEFAULT && mColormapState < CM_MAXCOLORMAP) + { + if (FGLRenderBuffers::IsEnabled()) + { + // When using postprocessing to apply the colormap, we must render the image fullbright here. + activeShader->muFixedColormap.Set(2); + activeShader->muColormapStart.Set(1, 1, 1, 1.f); + } + else + { + FSpecialColormap *scm = &SpecialColormaps[gl_fixedcolormap - CM_FIRSTSPECIALCOLORMAP]; + float m[] = { scm->ColorizeEnd[0] - scm->ColorizeStart[0], + scm->ColorizeEnd[1] - scm->ColorizeStart[1], scm->ColorizeEnd[2] - scm->ColorizeStart[2], 0.f }; + + activeShader->muFixedColormap.Set(1); + activeShader->muColormapStart.Set(scm->ColorizeStart[0], scm->ColorizeStart[1], scm->ColorizeStart[2], 0.f); + activeShader->muColormapRange.Set(m); + } + } + else if (mColormapState == CM_FOGLAYER) + { + activeShader->muFixedColormap.Set(3); + } + else if (mColormapState == CM_LITE) + { + if (gl_enhanced_nightvision) + { + r = 0.375f, g = 1.0f, b = 0.375f; + } + else + { + r = g = b = 1.f; + } + activeShader->muFixedColormap.Set(2); + activeShader->muColormapStart.Set(r, g, b, 1.f); + } + else if (mColormapState >= CM_TORCH) + { + int flicker = mColormapState - CM_TORCH; + r = (0.8f + (7 - flicker) / 70.0f); + if (r > 1.0f) r = 1.0f; + b = g = r; + if (gl_enhanced_nightvision) b = g * 0.75f; + activeShader->muFixedColormap.Set(2); + activeShader->muColormapStart.Set(r, g, b, 1.f); + } + } + if (mTextureMatrixEnabled) + { + mTextureMatrix.matrixToGL(activeShader->texturematrix_index); + activeShader->currentTextureMatrixState = true; + } + else if (activeShader->currentTextureMatrixState) + { + activeShader->currentTextureMatrixState = false; + identityMatrix.matrixToGL(activeShader->texturematrix_index); + } + + if (mModelMatrixEnabled) + { + mModelMatrix.matrixToGL(activeShader->modelmatrix_index); + VSMatrix norm; + norm.computeNormalMatrix(mModelMatrix); + mNormalModelMatrix.matrixToGL(activeShader->normalmodelmatrix_index); + activeShader->currentModelMatrixState = true; + } + else if (activeShader->currentModelMatrixState) + { + activeShader->currentModelMatrixState = false; + identityMatrix.matrixToGL(activeShader->modelmatrix_index); + identityMatrix.matrixToGL(activeShader->normalmodelmatrix_index); + } + return true; +} + + +//========================================================================== +// +// Apply State +// +//========================================================================== + +void FRenderState::Apply() +{ + if (!gl_direct_state_change) + { + if (mSrcBlend != stSrcBlend || mDstBlend != stDstBlend) + { + stSrcBlend = mSrcBlend; + stDstBlend = mDstBlend; + glBlendFunc(mSrcBlend, mDstBlend); + } + if (mBlendEquation != stBlendEquation) + { + stBlendEquation = mBlendEquation; + glBlendEquation(mBlendEquation); + } + } + + //ApplyColorMask(); I don't think this is needed. + + if (mVertexBuffer != mCurrentVertexBuffer) + { + if (mVertexBuffer == NULL) glBindBuffer(GL_ARRAY_BUFFER, 0); + else mVertexBuffer->BindVBO(); + mCurrentVertexBuffer = mVertexBuffer; + } + if (!gl.legacyMode) + { + ApplyShader(); + } + else + { + ApplyFixedFunction(); + } +} + + + +void FRenderState::ApplyColorMask() +{ + if ((mColorMask[0] != currentColorMask[0]) || + (mColorMask[1] != currentColorMask[1]) || + (mColorMask[2] != currentColorMask[2]) || + (mColorMask[3] != currentColorMask[3])) + { + glColorMask(mColorMask[0], mColorMask[1], mColorMask[2], mColorMask[3]); + currentColorMask[0] = mColorMask[0]; + currentColorMask[1] = mColorMask[1]; + currentColorMask[2] = mColorMask[2]; + currentColorMask[3] = mColorMask[3]; + } +} + +void FRenderState::ApplyMatrices() +{ + if (GLRenderer->mShaderManager != NULL) + { + GLRenderer->mShaderManager->ApplyMatrices(&mProjectionMatrix, &mViewMatrix, mPassType); + } +} + +void FRenderState::ApplyLightIndex(int index) +{ + if (!gl.legacyMode) + { + if (index > -1 && GLRenderer->mLights->GetBufferType() == GL_UNIFORM_BUFFER) + { + index = GLRenderer->mLights->BindUBO(index); + } + activeShader->muLightIndex.Set(index); + } +} + +void FRenderState::SetClipHeight(float height, float direction) +{ + mClipHeight = height; + mClipHeightDirection = direction; +#if 1 + // This still doesn't work... :( + if (gl.flags & RFL_NO_CLIP_PLANES) return; +#endif + if (direction != 0.f) + { + /* + if (gl.flags & RFL_NO_CLIP_PLANES) + { + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadMatrixf(mViewMatrix.get()); + // Plane mirrors never are slopes. + double d[4] = { 0, direction, 0, -direction * height }; + glClipPlane(GL_CLIP_PLANE0, d); + glPopMatrix(); + } + */ + glEnable(GL_CLIP_DISTANCE0); + } + else + { + glDisable(GL_CLIP_DISTANCE0); // GL_CLIP_PLANE0 is the same value so no need to make a distinction + } +} diff --git a/src/gl/renderer/gl_renderstate.h b/src/gl/renderer/gl_renderstate.h new file mode 100644 index 000000000..76e2c791c --- /dev/null +++ b/src/gl/renderer/gl_renderstate.h @@ -0,0 +1,518 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2009-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#ifndef __GL_RENDERSTATE_H +#define __GL_RENDERSTATE_H + +#include +#include "gl/system/gl_interface.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_matrix.h" +#include "gl/textures/gl_material.h" +#include "c_cvars.h" +#include "r_defs.h" +#include "r_data/r_translate.h" + +class FVertexBuffer; +class FShader; +extern TArray gl_MatrixStack; + +EXTERN_CVAR(Bool, gl_direct_state_change) + +struct FStateVec4 +{ + float vec[4]; + + void Set(float r, float g, float b, float a) + { + vec[0] = r; + vec[1] = g; + vec[2] = b; + vec[3] = a; + } +}; + + +enum EEffect +{ + EFF_NONE=-1, + EFF_FOGBOUNDARY, + EFF_SPHEREMAP, + EFF_BURN, + EFF_STENCIL, + + MAX_EFFECTS +}; + +enum EPassType +{ + NORMAL_PASS, + GBUFFER_PASS, + MAX_PASS_TYPES +}; + +class FRenderState +{ + bool mTextureEnabled; + bool mFogEnabled; + bool mGlowEnabled; + bool mSplitEnabled; + bool mClipLineEnabled; + bool mBrightmapEnabled; + bool mColorMask[4]; + bool currentColorMask[4]; + int mLightIndex; + int mSpecialEffect; + int mTextureMode; + int mDesaturation; + int mSoftLight; + float mLightParms[4]; + int mSrcBlend, mDstBlend; + float mAlphaThreshold; + int mBlendEquation; + bool mModelMatrixEnabled; + bool mTextureMatrixEnabled; + bool mLastDepthClamp; + float mInterpolationFactor; + float mClipHeight, mClipHeightDirection; + float mShaderTimer; + + FVertexBuffer *mVertexBuffer, *mCurrentVertexBuffer; + FStateVec4 mNormal; + FStateVec4 mColor; + FStateVec4 mCameraPos; + FStateVec4 mGlowTop, mGlowBottom; + FStateVec4 mGlowTopPlane, mGlowBottomPlane; + FStateVec4 mSplitTopPlane, mSplitBottomPlane; + FStateVec4 mClipLine; + PalEntry mFogColor; + PalEntry mObjectColor; + FStateVec4 mDynColor; + float mClipSplit[2]; + + int mEffectState; + int mColormapState; + + float stAlphaThreshold; + int stSrcBlend, stDstBlend; + bool stAlphaTest; + int stBlendEquation; + + FShader *activeShader; + + EPassType mPassType = NORMAL_PASS; + int mNumDrawBuffers = 1; + + bool ApplyShader(); + +public: + + VSMatrix mProjectionMatrix; + VSMatrix mViewMatrix; + VSMatrix mModelMatrix; + VSMatrix mTextureMatrix; + VSMatrix mNormalViewMatrix; + VSMatrix mNormalModelMatrix; + + FRenderState() + { + Reset(); + } + + void Reset(); + + void SetMaterial(FMaterial *mat, int clampmode, int translation, int overrideshader, bool alphatexture) + { + // textures without their own palette are a special case for use as an alpha texture: + // They use the color index directly as an alpha value instead of using the palette's red. + // To handle this case, we need to set a special translation for such textures. + // Without shaders this translation must be applied to any texture. + if (alphatexture) + { + if (mat->tex->UseBasePalette() || gl.legacyMode) translation = TRANSLATION(TRANSLATION_Standard, 8); + } + mEffectState = overrideshader >= 0? overrideshader : mat->mShaderIndex; + mShaderTimer = mat->tex->gl_info.shaderspeed; + mat->Bind(clampmode, translation); + } + + void Apply(); + void ApplyColorMask(); + void ApplyMatrices(); + void ApplyLightIndex(int index); + + void SetVertexBuffer(FVertexBuffer *vb) + { + mVertexBuffer = vb; + } + + void ResetVertexBuffer() + { + // forces rebinding with the next 'apply' call. + mCurrentVertexBuffer = NULL; + } + + float GetClipHeight() + { + return mClipHeight; + } + + float GetClipHeightDirection() + { + return mClipHeightDirection; + } + + FStateVec4 &GetClipLine() + { + return mClipLine; + } + + bool GetClipLineState() + { + return mClipLineEnabled; + } + + void SetClipHeight(float height, float direction); + + void SetNormal(FVector3 norm) + { + mNormal.Set(norm.X, norm.Y, norm.Z, 0.f); + } + + void SetNormal(float x, float y, float z) + { + mNormal.Set(x, y, z, 0.f); + } + + void SetColor(float r, float g, float b, float a = 1.f, int desat = 0) + { + mColor.Set(r, g, b, a); + mDesaturation = desat; + } + + void SetColor(PalEntry pe, int desat = 0) + { + mColor.Set(pe.r/255.f, pe.g/255.f, pe.b/255.f, pe.a/255.f); + mDesaturation = desat; + } + + void SetColorAlpha(PalEntry pe, float alpha = 1.f, int desat = 0) + { + mColor.Set(pe.r/255.f, pe.g/255.f, pe.b/255.f, alpha); + mDesaturation = desat; + } + + void ResetColor() + { + mColor.Set(1,1,1,1); + mDesaturation = 0; + } + + void GetColorMask(bool& r, bool &g, bool& b, bool& a) const + { + r = mColorMask[0]; + g = mColorMask[1]; + b = mColorMask[2]; + a = mColorMask[3]; + } + + void SetColorMask(bool r, bool g, bool b, bool a) + { + mColorMask[0] = r; + mColorMask[1] = g; + mColorMask[2] = b; + mColorMask[3] = a; + } + + void ResetColorMask() + { + for (int i = 0; i < 4; ++i) + mColorMask[i] = true; + } + + void SetTextureMode(int mode) + { + mTextureMode = mode; + } + + int GetTextureMode() + { + return mTextureMode; + } + + void EnableTexture(bool on) + { + mTextureEnabled = on; + } + + void EnableFog(bool on) + { + mFogEnabled = on; + } + + void SetEffect(int eff) + { + mSpecialEffect = eff; + } + + void EnableGlow(bool on) + { + mGlowEnabled = on; + } + + void EnableSplit(bool on) + { + if (!(gl.flags & RFL_NO_CLIP_PLANES)) + { + mSplitEnabled = on; + if (on) + { + glEnable(GL_CLIP_DISTANCE3); + glEnable(GL_CLIP_DISTANCE4); + } + else + { + glDisable(GL_CLIP_DISTANCE3); + glDisable(GL_CLIP_DISTANCE4); + } + } + } + + void SetClipLine(line_t *line) + { + mClipLine.Set(line->v1->fX(), line->v1->fY(), line->Delta().X, line->Delta().Y); + } + + void EnableClipLine(bool on) + { + if (!(gl.flags & RFL_NO_CLIP_PLANES)) + { + mClipLineEnabled = on; + if (on) + { + glEnable(GL_CLIP_DISTANCE0); + } + else + { + glDisable(GL_CLIP_DISTANCE0); + } + } + } + + void SetLightIndex(int n) + { + mLightIndex = n; + } + + void EnableBrightmap(bool on) + { + mBrightmapEnabled = on; + } + + void EnableModelMatrix(bool on) + { + mModelMatrixEnabled = on; + } + + void EnableTextureMatrix(bool on) + { + mTextureMatrixEnabled = on; + } + + void SetCameraPos(float x, float y, float z) + { + mCameraPos.Set(x, z, y, 0); + } + + void SetGlowParams(float *t, float *b) + { + mGlowTop.Set(t[0], t[1], t[2], t[3]); + mGlowBottom.Set(b[0], b[1], b[2], b[3]); + } + + void SetSoftLightLevel(int level) + { + if (glset.lightmode == 8) mLightParms[3] = level / 255.f; + else mLightParms[3] = -1.f; + } + + void SetGlowPlanes(const secplane_t &top, const secplane_t &bottom) + { + DVector3 tn = top.Normal(); + DVector3 bn = bottom.Normal(); + mGlowTopPlane.Set(tn.X, tn.Y, 1. / tn.Z, top.fD()); + mGlowBottomPlane.Set(bn.X, bn.Y, 1. / bn.Z, bottom.fD()); + } + + void SetSplitPlanes(const secplane_t &top, const secplane_t &bottom) + { + DVector3 tn = top.Normal(); + DVector3 bn = bottom.Normal(); + mSplitTopPlane.Set(tn.X, tn.Y, 1. / tn.Z, top.fD()); + mSplitBottomPlane.Set(bn.X, bn.Y, 1. / bn.Z, bottom.fD()); + } + + void SetDynLight(float r, float g, float b) + { + mDynColor.Set(r, g, b, 0); + } + + void SetObjectColor(PalEntry pe) + { + mObjectColor = pe; + } + + void SetFog(PalEntry c, float d) + { + const float LOG2E = 1.442692f; // = 1/log(2) + mFogColor = c; + if (d >= 0.0f) mLightParms[2] = d * (-LOG2E / 64000.f); + } + + void SetLightParms(float f, float d) + { + mLightParms[1] = f; + mLightParms[0] = d; + } + + void SetFixedColormap(int cm) + { + mColormapState = cm; + } + + int GetFixedColormap() + { + return mColormapState; + } + + PalEntry GetFogColor() const + { + return mFogColor; + } + + void SetClipSplit(float bottom, float top) + { + mClipSplit[0] = bottom; + mClipSplit[1] = top; + } + + void SetClipSplit(float *vals) + { + memcpy(mClipSplit, vals, 2 * sizeof(float)); + } + + void GetClipSplit(float *out) + { + memcpy(out, mClipSplit, 2 * sizeof(float)); + } + + void ClearClipSplit() + { + mClipSplit[0] = -1000000.f; + mClipSplit[1] = 1000000.f; + } + + void BlendFunc(int src, int dst) + { + if (!gl_direct_state_change) + { + mSrcBlend = src; + mDstBlend = dst; + } + else + { + glBlendFunc(src, dst); + } + } + + void AlphaFunc(int func, float thresh) + { + if (func == GL_GREATER) mAlphaThreshold = thresh; + else mAlphaThreshold = thresh - 0.001f; + } + + void BlendEquation(int eq) + { + if (!gl_direct_state_change) + { + mBlendEquation = eq; + } + else + { + glBlendEquation(eq); + } + } + + // This wraps the depth clamp setting because we frequently need to read it which OpenGL is not particularly performant at... + bool SetDepthClamp(bool on) + { + bool res = mLastDepthClamp; + if (!on) glDisable(GL_DEPTH_CLAMP); + else glEnable(GL_DEPTH_CLAMP); + mLastDepthClamp = on; + return res; + } + + void SetInterpolationFactor(float fac) + { + mInterpolationFactor = fac; + } + + float GetInterpolationFactor() + { + return mInterpolationFactor; + } + + void SetPassType(EPassType passType) + { + mPassType = passType; + } + + EPassType GetPassType() + { + return mPassType; + } + + void EnableDrawBuffers(int count) + { + count = MIN(count, 3); + if (mNumDrawBuffers != count) + { + static GLenum buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; + glDrawBuffers(count, buffers); + mNumDrawBuffers = count; + } + } + + int GetPassDrawBufferCount() + { + return mPassType == GBUFFER_PASS ? 3 : 1; + } + + // Backwards compatibility crap follows + void ApplyFixedFunction(); + void DrawColormapOverlay(); +}; + +extern FRenderState gl_RenderState; + +#endif diff --git a/src/gl/scene/gl_bsp.cpp b/src/gl/scene/gl_bsp.cpp new file mode 100644 index 000000000..9e5ea258d --- /dev/null +++ b/src/gl/scene/gl_bsp.cpp @@ -0,0 +1,592 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_bsp.cpp +** Main rendering loop / BSP traversal / visibility clipping +** +**/ + +#include "p_lnspec.h" +#include "p_local.h" +#include "a_sharedglobal.h" +#include "r_sky.h" +#include "p_effect.h" +#include "po_man.h" +#include "doomdata.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_clipper.h" +#include "gl/scene/gl_portal.h" +#include "gl/scene/gl_wall.h" +#include "gl/utility/gl_clock.h" + +EXTERN_CVAR(Bool, gl_render_segs) + +Clipper clipper; + + +CVAR(Bool, gl_render_things, true, 0) +CVAR(Bool, gl_render_walls, true, 0) +CVAR(Bool, gl_render_flats, true, 0) + +extern fixed_t viewx, viewy; + +static void UnclipSubsector(subsector_t *sub) +{ + int count = sub->numlines; + seg_t * seg = sub->firstline; + + while (count--) + { + angle_t startAngle = seg->v2->GetClipAngle(); + angle_t endAngle = seg->v1->GetClipAngle(); + + // Back side, i.e. backface culling - read: endAngle >= startAngle! + if (startAngle-endAngle >= ANGLE_180) + { + clipper.SafeRemoveClipRange(startAngle, endAngle); + clipper.SetBlocked(false); + } + seg++; + } +} + +//========================================================================== +// +// R_AddLine +// Clips the given segment +// and adds any visible pieces to the line list. +// +//========================================================================== + +// making these 2 variables global instead of passing them as function parameters is faster. +static subsector_t *currentsubsector; +static sector_t *currentsector; + +static void AddLine (seg_t *seg, bool portalclip) +{ +#ifdef _DEBUG + if (seg->linedef - lines == 38) + { + int a = 0; + } +#endif + + angle_t startAngle, endAngle; + sector_t * backsector = NULL; + sector_t bs; + + if (portalclip) + { + int clipres = GLRenderer->mClipPortal->ClipSeg(seg); + if (clipres == GLPortal::PClip_InFront) return; + } + + startAngle = seg->v2->GetClipAngle(); + endAngle = seg->v1->GetClipAngle(); + + // Back side, i.e. backface culling - read: endAngle >= startAngle! + if (startAngle-endAnglesidedef == NULL) + { + if (!(currentsubsector->flags & SSECF_DRAWN)) + { + if (clipper.SafeCheckRange(startAngle, endAngle)) + { + currentsubsector->flags |= SSECF_DRAWN; + } + } + return; + } + + if (!clipper.SafeCheckRange(startAngle, endAngle)) + { + return; + } + currentsubsector->flags |= SSECF_DRAWN; + + BYTE ispoly = BYTE(seg->sidedef->Flags & WALLF_POLYOBJ); + + if (!seg->backsector) + { + clipper.SafeAddClipRange(startAngle, endAngle); + } + else if (!ispoly) // Two-sided polyobjects never obstruct the view + { + if (currentsector->sectornum == seg->backsector->sectornum) + { + if (!seg->linedef->isVisualPortal()) + { + FTexture * tex = TexMan(seg->sidedef->GetTexture(side_t::mid)); + if (!tex || tex->UseType==FTexture::TEX_Null) + { + // nothing to do here! + seg->linedef->validcount=validcount; + return; + } + } + backsector=currentsector; + } + else + { + // clipping checks are only needed when the backsector is not the same as the front sector + gl_CheckViewArea(seg->v1, seg->v2, seg->frontsector, seg->backsector); + + backsector = gl_FakeFlat(seg->backsector, &bs, true); + + if (gl_CheckClip(seg->sidedef, currentsector, backsector)) + { + clipper.SafeAddClipRange(startAngle, endAngle); + } + } + } + else + { + // Backsector for polyobj segs is always the containing sector itself + backsector = currentsector; + } + + seg->linedef->flags |= ML_MAPPED; + + if (ispoly || seg->linedef->validcount!=validcount) + { + if (!ispoly) seg->linedef->validcount=validcount; + + if (gl_render_walls) + { + SetupWall.Clock(); + + GLWall wall; + wall.sub = currentsubsector; + wall.Process(seg, currentsector, backsector); + rendered_lines++; + + SetupWall.Unclock(); + } + } +} + +//========================================================================== +// +// R_Subsector +// Determine floor/ceiling planes. +// Add sprites of things in sector. +// Draw one or more line segments. +// +//========================================================================== + +static void PolySubsector(subsector_t * sub) +{ + int count = sub->numlines; + seg_t * line = sub->firstline; + + while (count--) + { + if (line->linedef) + { + AddLine (line, GLRenderer->mClipPortal != NULL); + } + line++; + } +} + +//========================================================================== +// +// RenderBSPNode +// Renders all subsectors below a given node, +// traversing subtree recursively. +// Just call with BSP root. +// +//========================================================================== + +static void RenderPolyBSPNode (void *node) +{ + while (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + + // Decide which side the view point is on. + int side = R_PointOnSide(viewx, viewy, bsp); + + // Recursively divide front space (toward the viewer). + RenderPolyBSPNode (bsp->children[side]); + + // Possibly divide back space (away from the viewer). + side ^= 1; + + // It is not necessary to use the slower precise version here + if (!clipper.CheckBox(bsp->bbox[side])) + { + return; + } + + node = bsp->children[side]; + } + PolySubsector ((subsector_t *)((BYTE *)node - 1)); +} + +//========================================================================== +// +// Unlilke the software renderer this function will only draw the walls, +// not the flats. Those are handled as a whole by the parent subsector. +// +//========================================================================== + +static void AddPolyobjs(subsector_t *sub) +{ + if (sub->BSP == NULL || sub->BSP->bDirty) + { + sub->BuildPolyBSP(); + for (unsigned i = 0; i < sub->BSP->Segs.Size(); i++) + { + sub->BSP->Segs[i].Subsector = sub; + sub->BSP->Segs[i].PartnerSeg = NULL; + } + } + if (sub->BSP->Nodes.Size() == 0) + { + PolySubsector(&sub->BSP->Subsectors[0]); + } + else + { + RenderPolyBSPNode(&sub->BSP->Nodes.Last()); + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +static inline void AddLines(subsector_t * sub, sector_t * sector) +{ + currentsector = sector; + currentsubsector = sub; + + ClipWall.Clock(); + if (sub->polys != NULL) + { + AddPolyobjs(sub); + } + else + { + int count = sub->numlines; + seg_t * seg = sub->firstline; + + while (count--) + { + if (seg->linedef == NULL) + { + if (!(sub->flags & SSECF_DRAWN)) AddLine (seg, GLRenderer->mClipPortal != NULL); + } + else if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + AddLine (seg, GLRenderer->mClipPortal != NULL); + } + seg++; + } + } + ClipWall.Unclock(); +} + +//========================================================================== +// +// Adds lines that lie directly on the portal boundary. +// Only two-sided lines will be handled here, and no polyobjects +// +//========================================================================== + +inline bool PointOnLine(const DVector2 &pos, const line_t *line) +{ + double v = (pos.Y - line->v1->fY()) * line->Delta().X + (line->v1->fX() - pos.X) * line->Delta().Y; + return fabs(v) <= EQUAL_EPSILON; +} + +static inline void AddSpecialPortalLines(subsector_t * sub, sector_t * sector, line_t *line) +{ + currentsector = sector; + currentsubsector = sub; + + ClipWall.Clock(); + int count = sub->numlines; + seg_t * seg = sub->firstline; + + while (count--) + { + if (seg->linedef != NULL && seg->PartnerSeg != NULL) + { + if (PointOnLine(seg->v1->fPos(), line) && PointOnLine(seg->v2->fPos(), line)) + AddLine(seg, false); + } + seg++; + } + ClipWall.Unclock(); +} + + +//========================================================================== +// +// R_RenderThings +// +//========================================================================== + +static inline void RenderThings(subsector_t * sub, sector_t * sector) +{ + + SetupSprite.Clock(); + sector_t * sec=sub->sector; + // Handle all things in sector. + for (auto p = sec->touching_renderthings; p != nullptr; p = p->m_snext) + { + auto thing = p->m_thing; + if (thing->validcount == validcount) continue; + thing->validcount = validcount; + + FIntCVar *cvar = thing->GetClass()->distancecheck; + if (cvar != NULL && *cvar >= 0) + { + double dist = (thing->Pos() - ViewPos).LengthSquared(); + double check = (double)**cvar; + if (dist >= check * check) + { + continue; + } + } + + GLRenderer->ProcessSprite(thing, sector, false); + } + + for (msecnode_t *node = sec->render_thinglist; node; node = node->m_snext) + { + AActor *thing = node->m_thing; + FIntCVar *cvar = thing->GetClass()->distancecheck; + if (cvar != NULL && *cvar >= 0) + { + double dist = (thing->Pos() - ViewPos).LengthSquared(); + double check = (double)**cvar; + if (dist >= check * check) + { + continue; + } + } + + GLRenderer->ProcessSprite(thing, sector, true); + } + SetupSprite.Unclock(); +} + + +//========================================================================== +// +// R_Subsector +// Determine floor/ceiling planes. +// Add sprites of things in sector. +// Draw one or more line segments. +// +//========================================================================== + +static void DoSubsector(subsector_t * sub) +{ + unsigned int i; + sector_t * sector; + sector_t * fakesector; + sector_t fake; + +#ifdef _DEBUG + if (sub->sector-sectors==931) + { + int a = 0; + } +#endif + + sector=sub->sector; + if (!sector) return; + + // If the mapsections differ this subsector can't possibly be visible from the current view point + if (!(currentmapsection[sub->mapsection>>3] & (1 << (sub->mapsection & 7)))) return; + if (sub->flags & SSECF_POLYORG) return; // never render polyobject origin subsectors because their vertices no longer are where one may expect. + + if (gl_drawinfo->ss_renderflags[sub-subsectors] & SSRF_SEEN) + { + // This means that we have reached a subsector in a portal that has been marked 'seen' + // from the other side of the portal. This means we must clear the clipper for the + // range this subsector spans before going on. + UnclipSubsector(sub); + } + if (clipper.IsBlocked()) return; // if we are inside a stacked sector portal which hasn't unclipped anything yet. + + fakesector=gl_FakeFlat(sector, &fake, false); + + if (GLRenderer->mClipPortal) + { + int clipres = GLRenderer->mClipPortal->ClipSubsector(sub); + if (clipres == GLPortal::PClip_InFront) + { + line_t *line = GLRenderer->mClipPortal->ClipLine(); + // The subsector is out of range, but we still have to check lines that lie directly on the boundary and may expose their upper or lower parts. + if (line) AddSpecialPortalLines(sub, fakesector, line); + return; + } + } + + if (sector->validcount != validcount) + { + GLRenderer->mVBO->CheckUpdate(sector); + } + + // [RH] Add particles + //int shade = LIGHT2SHADE((floorlightlevel + ceilinglightlevel)/2 + r_actualextralight); + if (gl_render_things) + { + SetupSprite.Clock(); + + for (i = ParticlesInSubsec[DWORD(sub-subsectors)]; i != NO_PARTICLE; i = Particles[i].snext) + { + GLRenderer->ProcessParticle(&Particles[i], fakesector); + } + SetupSprite.Unclock(); + } + + AddLines(sub, fakesector); + + // BSP is traversed by subsector. + // A sector might have been split into several + // subsectors during BSP building. + // Thus we check whether it was already added. + if (sector->validcount != validcount) + { + // Well, now it will be done. + sector->validcount = validcount; + + if (gl_render_things) + { + RenderThings(sub, fakesector); + } + sector->MoreFlags |= SECF_DRAWN; + } + + if (gl_render_flats) + { + // Subsectors with only 2 lines cannot have any area + if (sub->numlines>2 || (sub->hacked&1)) + { + // Exclude the case when it tries to render a sector with a heightsec + // but undetermined heightsec state. This can only happen if the + // subsector is obstructed but not excluded due to a large bounding box. + // Due to the way a BSP works such a subsector can never be visible + if (!sector->heightsec || sector->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC || in_area!=area_default) + { + if (sector != sub->render_sector) + { + sector = sub->render_sector; + // the planes of this subsector are faked to belong to another sector + // This means we need the heightsec parts and light info of the render sector, not the actual one. + fakesector = gl_FakeFlat(sector, &fake, false); + } + + BYTE &srf = gl_drawinfo->sectorrenderflags[sub->render_sector->sectornum]; + if (!(srf & SSRF_PROCESSED)) + { + srf |= SSRF_PROCESSED; + + SetupFlat.Clock(); + GLRenderer->ProcessSector(fakesector); + SetupFlat.Unclock(); + } + // mark subsector as processed - but mark for rendering only if it has an actual area. + gl_drawinfo->ss_renderflags[sub-subsectors] = + (sub->numlines > 2) ? SSRF_PROCESSED|SSRF_RENDERALL : SSRF_PROCESSED; + if (sub->hacked & 1) gl_drawinfo->AddHackedSubsector(sub); + + FPortal *portal; + + portal = fakesector->GetGLPortal(sector_t::ceiling); + if (portal != NULL) + { + GLSectorStackPortal *glportal = portal->GetRenderState(); + glportal->AddSubsector(sub); + } + + portal = fakesector->GetGLPortal(sector_t::floor); + if (portal != NULL) + { + GLSectorStackPortal *glportal = portal->GetRenderState(); + glportal->AddSubsector(sub); + } + } + } + } +} + + + + +//========================================================================== +// +// RenderBSPNode +// Renders all subsectors below a given node, +// traversing subtree recursively. +// Just call with BSP root. +// +//========================================================================== + +void gl_RenderBSPNode (void *node) +{ + if (numnodes == 0) + { + DoSubsector (subsectors); + return; + } + while (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + + // Decide which side the view point is on. + int side = R_PointOnSide(viewx, viewy, bsp); + + // Recursively divide front space (toward the viewer). + gl_RenderBSPNode (bsp->children[side]); + + // Possibly divide back space (away from the viewer). + side ^= 1; + + // It is not necessary to use the slower precise version here + if (!clipper.CheckBox(bsp->bbox[side])) + { + if (!(gl_drawinfo->no_renderflags[bsp-nodes] & SSRF_SEEN)) + return; + } + + node = bsp->children[side]; + } + DoSubsector ((subsector_t *)((BYTE *)node - 1)); +} + + diff --git a/src/gl/scene/gl_clipper.cpp b/src/gl/scene/gl_clipper.cpp new file mode 100644 index 000000000..cd076d58a --- /dev/null +++ b/src/gl/scene/gl_clipper.cpp @@ -0,0 +1,465 @@ +/* +* +** gl_clipper.cpp +** +** Handles visibility checks. +** Loosely based on the JDoom clipper. +** +**--------------------------------------------------------------------------- +** Copyright 2003 Tim Stump +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "gl/scene/gl_clipper.h" + + + +ClipNode * ClipNode::freelist; +int Clipper::anglecache; + + +//----------------------------------------------------------------------------- +// +// Destructor +// +//----------------------------------------------------------------------------- + +Clipper::~Clipper() +{ + Clear(); + while (ClipNode::freelist != NULL) + { + ClipNode * node = ClipNode::freelist; + ClipNode::freelist = node->next; + delete node; + } +} + +//----------------------------------------------------------------------------- +// +// RemoveRange +// +//----------------------------------------------------------------------------- + +void Clipper::RemoveRange(ClipNode * range) +{ + if (range == cliphead) + { + cliphead = cliphead->next; + } + else + { + if (range->prev) range->prev->next = range->next; + if (range->next) range->next->prev = range->prev; + } + + range->Free(); +} + +//----------------------------------------------------------------------------- +// +// Clear +// +//----------------------------------------------------------------------------- + +void Clipper::Clear() +{ + ClipNode *node = cliphead; + ClipNode *temp; + + blocked = false; + while (node != NULL) + { + temp = node; + node = node->next; + temp->Free(); + } + node = silhouette; + + while (node != NULL) + { + temp = node; + node = node->next; + temp->Free(); + } + + cliphead = NULL; + silhouette = NULL; + anglecache++; +} + +//----------------------------------------------------------------------------- +// +// SetSilhouette +// +//----------------------------------------------------------------------------- + +void Clipper::SetSilhouette() +{ + ClipNode *node = cliphead; + ClipNode *last = NULL; + + while (node != NULL) + { + ClipNode *snode = ClipNode::NewRange(node->start, node->end); + if (silhouette == NULL) silhouette = snode; + snode->prev = last; + if (last != NULL) last->next = snode; + last = snode; + node = node->next; + } +} + + +//----------------------------------------------------------------------------- +// +// IsRangeVisible +// +//----------------------------------------------------------------------------- + +bool Clipper::IsRangeVisible(angle_t startAngle, angle_t endAngle) +{ + ClipNode *ci; + ci = cliphead; + + if (endAngle==0 && ci && ci->start==0) return false; + + while (ci != NULL && ci->start < endAngle) + { + if (startAngle >= ci->start && endAngle <= ci->end) + { + return false; + } + ci = ci->next; + } + + return true; +} + +//----------------------------------------------------------------------------- +// +// AddClipRange +// +//----------------------------------------------------------------------------- + +void Clipper::AddClipRange(angle_t start, angle_t end) +{ + ClipNode *node, *temp, *prevNode; + + if (cliphead) + { + //check to see if range contains any old ranges + node = cliphead; + while (node != NULL && node->start < end) + { + if (node->start >= start && node->end <= end) + { + temp = node; + node = node->next; + RemoveRange(temp); + } + else if (node->start<=start && node->end>=end) + { + return; + } + else + { + node = node->next; + } + } + + //check to see if range overlaps a range (or possibly 2) + node = cliphead; + while (node != NULL && node->start <= end) + { + if (node->end >= start) + { + // we found the first overlapping node + if (node->start > start) + { + // the new range overlaps with this node's start point + node->start = start; + } + + if (node->end < end) + { + node->end = end; + } + + ClipNode *node2 = node->next; + while (node2 && node2->start <= node->end) + { + if (node2->end > node->end) node->end = node2->end; + ClipNode *delnode = node2; + node2 = node2->next; + RemoveRange(delnode); + } + return; + } + node = node->next; + } + + //just add range + node = cliphead; + prevNode = NULL; + temp = ClipNode::NewRange(start, end); + + while (node != NULL && node->start < end) + { + prevNode = node; + node = node->next; + } + + temp->next = node; + if (node == NULL) + { + temp->prev = prevNode; + if (prevNode) prevNode->next = temp; + if (!cliphead) cliphead = temp; + } + else + { + if (node == cliphead) + { + cliphead->prev = temp; + cliphead = temp; + } + else + { + temp->prev = prevNode; + prevNode->next = temp; + node->prev = temp; + } + } + } + else + { + temp = ClipNode::NewRange(start, end); + cliphead = temp; + return; + } +} + + +//----------------------------------------------------------------------------- +// +// RemoveClipRange +// +//----------------------------------------------------------------------------- + +void Clipper::RemoveClipRange(angle_t start, angle_t end) +{ + ClipNode *node; + + if (silhouette) + { + node = silhouette; + while (node != NULL && node->end <= start) + { + node = node->next; + } + if (node != NULL && node->start <= start) + { + if (node->end >= end) return; + start = node->end; + node = node->next; + } + while (node != NULL && node->start < end) + { + DoRemoveClipRange(start, node->start); + start = node->end; + node = node->next; + } + if (start >= end) return; + } + DoRemoveClipRange(start, end); +} + +//----------------------------------------------------------------------------- +// +// RemoveClipRange worker function +// +//----------------------------------------------------------------------------- + +void Clipper::DoRemoveClipRange(angle_t start, angle_t end) +{ + ClipNode *node, *temp; + + if (cliphead) + { + //check to see if range contains any old ranges + node = cliphead; + while (node != NULL && node->start < end) + { + if (node->start >= start && node->end <= end) + { + temp = node; + node = node->next; + RemoveRange(temp); + } + else + { + node = node->next; + } + } + + //check to see if range overlaps a range (or possibly 2) + node = cliphead; + while (node != NULL) + { + if (node->start >= start && node->start <= end) + { + node->start = end; + break; + } + else if (node->end >= start && node->end <= end) + { + node->end=start; + } + else if (node->start < start && node->end > end) + { + temp=ClipNode::NewRange(end, node->end); + node->end=start; + temp->next=node->next; + temp->prev=node; + node->next=temp; + if (temp->next) temp->next->prev=temp; + break; + } + node = node->next; + } + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +angle_t Clipper::AngleToPseudo(angle_t ang) +{ + double vecx = cos(ang * M_PI / ANGLE_180); + double vecy = sin(ang * M_PI / ANGLE_180); + + double result = vecy / (fabs(vecx) + fabs(vecy)); + if (vecx < 0) + { + result = 2.f - result; + } + return xs_Fix<30>::ToFix(result); +} + +//----------------------------------------------------------------------------- +// +// ! Returns the pseudoangle between the line p1 to (infinity, p1.y) and the +// line from p1 to p2. The pseudoangle has the property that the ordering of +// points by true angle around p1 and ordering of points by pseudoangle are the +// same. +// +// For clipping exact angles are not needed. Only the ordering matters. +// This is about as fast as the fixed point R_PointToAngle2 but without +// the precision issues associated with that function. +// +//----------------------------------------------------------------------------- + +fixed_t viewx, viewy; + +void R_SetView() +{ + viewx = FLOAT2FIXED(ViewPos.X); + viewy = FLOAT2FIXED(ViewPos.Y); +} + +angle_t R_PointToPseudoAngle(double x, double y) +{ + double vecx = x - ViewPos.X; + double vecy = y - ViewPos.Y; + + if (vecx == 0 && vecy == 0) + { + return 0; + } + else + { + double result = vecy / (fabs(vecx) + fabs(vecy)); + if (vecx < 0) + { + result = 2.f - result; + } + return xs_Fix<30>::ToFix(result); + } +} + + + +//----------------------------------------------------------------------------- +// +// R_CheckBBox +// Checks BSP node/subtree bounding box. +// Returns true +// if some part of the bbox might be visible. +// +//----------------------------------------------------------------------------- + static const BYTE checkcoord[12][4] = // killough -- static const + { + {3,0,2,1}, + {3,0,2,0}, + {3,1,2,0}, + {0}, + {2,0,2,1}, + {0,0,0,0}, + {3,1,3,0}, + {0}, + {2,0,3,1}, + {2,1,3,1}, + {2,1,3,0} + }; + +bool Clipper::CheckBox(const float *bspcoord) +{ + angle_t angle1, angle2; + + int boxpos; + const BYTE* check; + + // Find the corners of the box + // that define the edges from current viewpoint. + boxpos = (ViewPos.X <= bspcoord[BOXLEFT] ? 0 : ViewPos.X < bspcoord[BOXRIGHT ] ? 1 : 2) + + (ViewPos.Y >= bspcoord[BOXTOP ] ? 0 : ViewPos.Y > bspcoord[BOXBOTTOM] ? 4 : 8); + + if (boxpos == 5) return true; + + check = checkcoord[boxpos]; + angle1 = R_PointToPseudoAngle (bspcoord[check[0]], bspcoord[check[1]]); + angle2 = R_PointToPseudoAngle (bspcoord[check[2]], bspcoord[check[3]]); + + return SafeCheckRange(angle2, angle1); +} + diff --git a/src/gl/scene/gl_clipper.h b/src/gl/scene/gl_clipper.h new file mode 100644 index 000000000..8da75080e --- /dev/null +++ b/src/gl/scene/gl_clipper.h @@ -0,0 +1,159 @@ +#ifndef __GL_CLIPPER +#define __GL_CLIPPER + +#include "doomtype.h" +#include "xs_Float.h" +#include "r_utility.h" + +class ClipNode +{ + friend class Clipper; + friend class ClipNodesFreer; + + ClipNode *prev, *next; + angle_t start, end; + static ClipNode * freelist; + + bool operator== (const ClipNode &other) + { + return other.start == start && other.end == end; + } + + void Free() + { + next=freelist; + freelist=this; + } + + static ClipNode * GetNew() + { + if (freelist) + { + ClipNode * p=freelist; + freelist=p->next; + return p; + } + else return new ClipNode; + } + + static ClipNode * NewRange(angle_t start, angle_t end) + { + ClipNode * c=GetNew(); + + c->start=start; + c->end=end; + c->next=c->prev=NULL; + return c; + } + +}; + + +class Clipper +{ + ClipNode * clipnodes; + ClipNode * cliphead; + ClipNode * silhouette; // will be preserved even when RemoveClipRange is called + bool blocked; + + static angle_t AngleToPseudo(angle_t ang); + bool IsRangeVisible(angle_t startangle, angle_t endangle); + void RemoveRange(ClipNode * cn); + void AddClipRange(angle_t startangle, angle_t endangle); + void RemoveClipRange(angle_t startangle, angle_t endangle); + void DoRemoveClipRange(angle_t start, angle_t end); + +public: + + static int anglecache; + + Clipper() + { + blocked = false; + clipnodes=cliphead=NULL; + } + + ~Clipper(); + + void Clear(); + + + void SetSilhouette(); + + bool SafeCheckRange(angle_t startAngle, angle_t endAngle) + { + if(startAngle > endAngle) + { + return (IsRangeVisible(startAngle, ANGLE_MAX) || IsRangeVisible(0, endAngle)); + } + + return IsRangeVisible(startAngle, endAngle); + } + + void SafeAddClipRange(angle_t startangle, angle_t endangle) + { + if(startangle > endangle) + { + // The range has to added in two parts. + AddClipRange(startangle, ANGLE_MAX); + AddClipRange(0, endangle); + } + else + { + // Add the range as usual. + AddClipRange(startangle, endangle); + } + } + + void SafeAddClipRangeRealAngles(angle_t startangle, angle_t endangle) + { + SafeAddClipRange(AngleToPseudo(startangle), AngleToPseudo(endangle)); + } + + + void SafeRemoveClipRange(angle_t startangle, angle_t endangle) + { + if(startangle > endangle) + { + // The range has to added in two parts. + RemoveClipRange(startangle, ANGLE_MAX); + RemoveClipRange(0, endangle); + } + else + { + // Add the range as usual. + RemoveClipRange(startangle, endangle); + } + } + + void SafeRemoveClipRangeRealAngles(angle_t startangle, angle_t endangle) + { + SafeRemoveClipRange(AngleToPseudo(startangle), AngleToPseudo(endangle)); + } + + void SetBlocked(bool on) + { + blocked = on; + } + + bool IsBlocked() const + { + return blocked; + } + + bool CheckBox(const float *bspcoord); +}; + + +extern Clipper clipper; + +angle_t R_PointToPseudoAngle(double x, double y); +void R_SetView(); + +// Used to speed up angle calculations during clipping +inline angle_t vertex_t::GetClipAngle() +{ + return angletime == Clipper::anglecache? viewangle : (angletime = Clipper::anglecache, viewangle = R_PointToPseudoAngle(p.X, p.Y)); +} + +#endif \ No newline at end of file diff --git a/src/gl/scene/gl_decal.cpp b/src/gl/scene/gl_decal.cpp new file mode 100644 index 000000000..7fb680f8e --- /dev/null +++ b/src/gl/scene/gl_decal.cpp @@ -0,0 +1,398 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2003-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_decal.cpp +** OpenGL decal rendering code +** +*/ + +#include "doomdata.h" +#include "gl/system/gl_system.h" +#include "a_sharedglobal.h" +#include "r_utility.h" + +#include "gl/system/gl_cvars.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/renderer/gl_quaddrawer.h" + +struct DecalVertex +{ + float x,y,z; + float u,v; +}; + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::DrawDecal(DBaseDecal *decal) +{ + line_t * line=seg->linedef; + side_t * side=seg->sidedef; + int i; + float zpos; + int light; + int rel; + float a; + bool flipx, flipy; + DecalVertex dv[4]; + FTextureID decalTile; + + + if (decal->RenderFlags & RF_INVISIBLE) return; + if (type==RENDERWALL_FFBLOCK && gltexture->isMasked()) return; // No decals on 3D floors with transparent textures. + + //if (decal->sprite != 0xffff) + { + decalTile = decal->PicNum; + flipx = !!(decal->RenderFlags & RF_XFLIP); + flipy = !!(decal->RenderFlags & RF_YFLIP); + } + /* + else + { + decalTile = SpriteFrames[sprites[decal->sprite].spriteframes + decal->frame].lump[0]; + flipx = SpriteFrames[sprites[decal->sprite].spriteframes + decal->frame].flip & 1; + } + */ + + FTexture *texture = TexMan[decalTile]; + if (texture == NULL) return; + + FMaterial *tex; + + + tex = FMaterial::ValidateTexture(texture, true); + + + // the sectors are only used for their texture origin coordinates + // so we don't need the fake sectors for deep water etc. + // As this is a completely split wall fragment no further splits are + // necessary for the decal. + sector_t *frontsector; + + // for 3d-floor segments use the model sector as reference + if ((decal->RenderFlags&RF_CLIPMASK)==RF_CLIPMID) frontsector=decal->Sector; + else frontsector=seg->frontsector; + + switch (decal->RenderFlags & RF_RELMASK) + { + default: + // No valid decal can have this type. If one is encountered anyway + // it is in some way invalid so skip it. + return; + //zpos = decal->z; + //break; + + case RF_RELUPPER: + if (type!=RENDERWALL_TOP) return; + if (line->flags & ML_DONTPEGTOP) + { + zpos = decal->Z + frontsector->GetPlaneTexZ(sector_t::ceiling); + } + else + { + zpos = decal->Z + seg->backsector->GetPlaneTexZ(sector_t::ceiling); + } + break; + case RF_RELLOWER: + if (type!=RENDERWALL_BOTTOM) return; + if (line->flags & ML_DONTPEGBOTTOM) + { + zpos = decal->Z + frontsector->GetPlaneTexZ(sector_t::ceiling); + } + else + { + zpos = decal->Z + seg->backsector->GetPlaneTexZ(sector_t::floor); + } + break; + case RF_RELMID: + if (type==RENDERWALL_TOP || type==RENDERWALL_BOTTOM) return; + if (line->flags & ML_DONTPEGBOTTOM) + { + zpos = decal->Z + frontsector->GetPlaneTexZ(sector_t::floor); + } + else + { + zpos = decal->Z + frontsector->GetPlaneTexZ(sector_t::ceiling); + } + } + + if (decal->RenderFlags & RF_FULLBRIGHT) + { + light = 255; + rel = 0; + } + else + { + light = lightlevel; + rel = rellight + getExtraLight(); + } + + FColormap p = Colormap; + + if (glset.nocoloredspritelighting) + { + p.Decolorize(); + } + + + + a = decal->Alpha; + + // now clip the decal to the actual polygon + float decalwidth = tex->TextureWidth() * decal->ScaleX; + float decalheight= tex->TextureHeight() * decal->ScaleY; + float decallefto = tex->GetLeftOffset() * decal->ScaleX; + float decaltopo = tex->GetTopOffset() * decal->ScaleY; + + + float leftedge = glseg.fracleft * side->TexelLength; + float linelength = glseg.fracright * side->TexelLength - leftedge; + + // texel index of the decal's left edge + float decalpixpos = (float)side->TexelLength * decal->LeftDistance - (flipx? decalwidth-decallefto : decallefto) - leftedge; + + float left,right; + float lefttex,righttex; + + // decal is off the left edge + if (decalpixpos < 0) + { + left = 0; + lefttex = -decalpixpos; + } + else + { + left = decalpixpos; + lefttex = 0; + } + + // decal is off the right edge + if (decalpixpos + decalwidth > linelength) + { + right = linelength; + righttex = right - decalpixpos; + } + else + { + right = decalpixpos + decalwidth; + righttex = decalwidth; + } + if (right<=left) return; // nothing to draw + + // one texture unit on the wall as vector + float vx=(glseg.x2-glseg.x1)/linelength; + float vy=(glseg.y2-glseg.y1)/linelength; + + dv[1].x=dv[0].x=glseg.x1+vx*left; + dv[1].y=dv[0].y=glseg.y1+vy*left; + + dv[3].x=dv[2].x=glseg.x1+vx*right; + dv[3].y=dv[2].y=glseg.y1+vy*right; + + zpos+= (flipy? decalheight-decaltopo : decaltopo); + + dv[1].z=dv[2].z = zpos; + dv[0].z=dv[3].z = dv[1].z - decalheight; + dv[1].v=dv[2].v = tex->GetVT(); + + dv[1].u=dv[0].u = tex->GetU(lefttex / decal->ScaleX); + dv[3].u=dv[2].u = tex->GetU(righttex / decal->ScaleX); + dv[0].v=dv[3].v = tex->GetVB(); + + + // now clip to the top plane + float vzt=(ztop[1]-ztop[0])/linelength; + float topleft=this->ztop[0]+vzt*left; + float topright=this->ztop[0]+vzt*right; + + // completely below the wall + if (topleftzbottom[0]+vzb*left; + float bottomright=this->zbottom[0]+vzb*right; + + // completely above the wall + if (bottomleft>dv[1].z && bottomright>dv[2].z) + return; + + if (bottomleft>dv[0].z || bottomright>dv[3].z) + { + // decal has to be clipped at the bottom + // let texture clamping handle all extreme cases + dv[0].v=(dv[1].z-bottomleft)/(dv[1].z-dv[0].z)*(dv[0].v-dv[1].v) + dv[1].v; + dv[3].v=(dv[2].z-bottomright)/(dv[2].z-dv[3].z)*(dv[3].v-dv[2].v) + dv[2].v; + dv[0].z=bottomleft; + dv[3].z=bottomright; + } + + + if (flipx) + { + float ur = tex->GetUR(); + for(i=0;i<4;i++) dv[i].u=ur-dv[i].u; + } + if (flipy) + { + float vb = tex->GetVB(); + for(i=0;i<4;i++) dv[i].v=vb-dv[i].v; + } + + // calculate dynamic light effect. + if (gl_lights && GLRenderer->mLightCount && !gl_fixedcolormap && gl_light_sprites) + { + // Note: This should be replaced with proper shader based lighting. + double x, y; + decal->GetXY(seg->sidedef, x, y); + gl_SetDynSpriteLight(NULL, x, y, zpos, sub); + } + + // alpha color only has an effect when using an alpha texture. + if (decal->RenderStyle.Flags & STYLEF_RedIsAlpha) + { + gl_RenderState.SetObjectColor(decal->AlphaColor|0xff000000); + } + + + + + gl_SetRenderStyle(decal->RenderStyle, false, false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, decal->Translation, 0, !!(decal->RenderStyle.Flags & STYLEF_RedIsAlpha)); + + + // If srcalpha is one it looks better with a higher alpha threshold + if (decal->RenderStyle.SrcAlpha == STYLEALPHA_One) gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + else gl_RenderState.AlphaFunc(GL_GREATER, 0.f); + + + gl_SetColor(light, rel, p, a); + // for additively drawn decals we must temporarily set the fog color to black. + PalEntry fc = gl_RenderState.GetFogColor(); + if (decal->RenderStyle.BlendOp == STYLEOP_Add && decal->RenderStyle.DestAlpha == STYLEALPHA_One) + { + gl_RenderState.SetFog(0,-1); + } + + gl_RenderState.SetNormal(glseg.Normal()); + + FQuadDrawer qd; + for (i = 0; i < 4; i++) + { + qd.Set(i, dv[i].x, dv[i].z, dv[i].y, dv[i].u, dv[i].v); + } + + if (lightlist == NULL) + { + gl_RenderState.Apply(); + qd.Render(GL_TRIANGLE_FAN); + } + else + { + for (unsigned k = 0; k < lightlist->Size(); k++) + { + secplane_t &lowplane = k == (*lightlist).Size() - 1 ? bottomplane : (*lightlist)[k + 1].plane; + + float low1 = lowplane.ZatPoint(dv[1].x, dv[1].y); + float low2 = lowplane.ZatPoint(dv[2].x, dv[2].y); + + if (low1 < dv[1].z || low2 < dv[2].z) + { + int thisll = (*lightlist)[k].caster != NULL ? gl_ClampLight(*(*lightlist)[k].p_lightlevel) : lightlevel; + FColormap thiscm; + thiscm.FadeColor = Colormap.FadeColor; + thiscm.CopyFrom3DLight(&(*lightlist)[k]); + gl_SetColor(thisll, rel, thiscm, a); + if (glset.nocoloredspritelighting) thiscm.Decolorize(); + gl_SetFog(thisll, rel, &thiscm, RenderStyle == STYLE_Add); + gl_RenderState.SetSplitPlanes((*lightlist)[k].plane, lowplane); + + gl_RenderState.Apply(); + qd.Render(GL_TRIANGLE_FAN); + } + if (low1 <= dv[0].z && low2 <= dv[3].z) break; + } + } + + rendered_decals++; + gl_RenderState.SetTextureMode(TM_MODULATE); + gl_RenderState.SetObjectColor(0xffffffff); + gl_RenderState.SetFog(fc,-1); + gl_RenderState.SetDynLight(0,0,0); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::DoDrawDecals() +{ + if (seg->sidedef && seg->sidedef->AttachedDecals) + { + if (lightlist != NULL) + { + gl_RenderState.EnableSplit(true); + } + else + { + gl_SetFog(lightlevel, rellight + getExtraLight(), &Colormap, false); + } + + DBaseDecal *decal = seg->sidedef->AttachedDecals; + while (decal) + { + DrawDecal(decal); + decal = decal->WallNext; + } + + if (lightlist != NULL) + { + gl_RenderState.EnableSplit(false); + } + + } +} + diff --git a/src/gl/scene/gl_drawinfo.cpp b/src/gl/scene/gl_drawinfo.cpp new file mode 100644 index 000000000..e4722b3db --- /dev/null +++ b/src/gl/scene/gl_drawinfo.cpp @@ -0,0 +1,1323 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_drawinfo.cpp +** Implements the draw info structure which contains most of the +** data in a scene and the draw lists - including a very thorough BSP +** style sorting algorithm for translucent objects. +** +*/ + +#include "gl/system/gl_system.h" +#include "r_sky.h" +#include "r_utility.h" +#include "r_state.h" +#include "doomstat.h" + +#include "gl/system/gl_cvars.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/shaders/gl_shader.h" +#include "gl/stereo3d/scoped_color_mask.h" +#include "gl/renderer/gl_quaddrawer.h" + +FDrawInfo * gl_drawinfo; + +//========================================================================== +// +// +// +//========================================================================== +class StaticSortNodeArray : public TDeletingArray +{ + unsigned usecount; +public: + unsigned Size() { return usecount; } + void Clear() { usecount=0; } + void Release(int start) { usecount=start; } + SortNode * GetNew(); +}; + + +SortNode * StaticSortNodeArray::GetNew() +{ + if (usecount==TArray::Size()) + { + Push(new SortNode); + } + return operator[](usecount++); +} + + +static StaticSortNodeArray SortNodes; + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::Reset() +{ + if (sorted) SortNodes.Release(SortNodeStart); + sorted=NULL; + walls.Clear(); + flats.Clear(); + sprites.Clear(); + drawitems.Clear(); +} + + +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Translucent polygon sorting - uses a BSP algorithm with an additional 'equal' branch + +inline double GLSprite::CalcIntersectionVertex(GLWall * w2) +{ + float ax = x1, ay=y1; + float bx = x2, by=y2; + float cx = w2->glseg.x1, cy=w2->glseg.y1; + float dx = w2->glseg.x2, dy=w2->glseg.y2; + return ((ay-cy)*(dx-cx)-(ax-cx)*(dy-cy)) / ((bx-ax)*(dy-cy)-(by-ay)*(dx-cx)); +} + + + +//========================================================================== +// +// +// +//========================================================================== +inline void SortNode::UnlinkFromChain() +{ + if (parent) parent->next=next; + if (next) next->parent=parent; + parent=next=NULL; +} + +//========================================================================== +// +// +// +//========================================================================== +inline void SortNode::Link(SortNode * hook) +{ + if (hook) + { + parent=hook->parent; + hook->parent=this; + } + next=hook; + if (parent) parent->next=this; +} + +//========================================================================== +// +// +// +//========================================================================== +inline void SortNode::AddToEqual(SortNode *child) +{ + child->UnlinkFromChain(); + child->equal=equal; + equal=child; +} + +//========================================================================== +// +// +// +//========================================================================== +inline void SortNode::AddToLeft(SortNode * child) +{ + child->UnlinkFromChain(); + child->Link(left); + left=child; +} + +//========================================================================== +// +// +// +//========================================================================== +inline void SortNode::AddToRight(SortNode * child) +{ + child->UnlinkFromChain(); + child->Link(right); + right=child; +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::MakeSortList() +{ + SortNode * p, * n, * c; + unsigned i; + + SortNodeStart=SortNodes.Size(); + p=NULL; + n=SortNodes.GetNew(); + for(i=0;iitemindex=(int)i; + n->left=n->equal=n->right=NULL; + n->parent=p; + p=n; + if (i!=drawitems.Size()-1) + { + c=SortNodes.GetNew(); + n->next=c; + n=c; + } + else + { + n->next=NULL; + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== +SortNode * GLDrawList::FindSortPlane(SortNode * head) +{ + while (head->next && drawitems[head->itemindex].rendertype!=GLDIT_FLAT) + head=head->next; + if (drawitems[head->itemindex].rendertype==GLDIT_FLAT) return head; + return NULL; +} + + +//========================================================================== +// +// +// +//========================================================================== +SortNode * GLDrawList::FindSortWall(SortNode * head) +{ + float farthest = -FLT_MAX; + float nearest = FLT_MAX; + SortNode * best = NULL; + SortNode * node = head; + float bestdist = FLT_MAX; + + while (node) + { + GLDrawItem * it = &drawitems[node->itemindex]; + if (it->rendertype == GLDIT_WALL) + { + float d = walls[it->index].ViewDistance; + if (d > farthest) farthest = d; + if (d < nearest) nearest = d; + } + node = node->next; + } + if (farthest == INT_MIN) return NULL; + node = head; + farthest = (farthest + nearest) / 2; + while (node) + { + GLDrawItem * it = &drawitems[node->itemindex]; + if (it->rendertype == GLDIT_WALL) + { + float di = fabsf(walls[it->index].ViewDistance - farthest); + if (!best || di < bestdist) + { + best = node; + bestdist = di; + } + } + node = node->next; + } + return best; +} + +//========================================================================== +// +// Note: sloped planes are a huge problem... +// +//========================================================================== +void GLDrawList::SortPlaneIntoPlane(SortNode * head,SortNode * sort) +{ + GLFlat * fh=&flats[drawitems[head->itemindex].index]; + GLFlat * fs=&flats[drawitems[sort->itemindex].index]; + + if (fh->z==fs->z) + head->AddToEqual(sort); + else if ( (fh->zz && fh->ceiling) || (fh->z>fs->z && !fh->ceiling)) + head->AddToLeft(sort); + else + head->AddToRight(sort); +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::SortWallIntoPlane(SortNode * head,SortNode * sort) +{ + GLFlat * fh=&flats[drawitems[head->itemindex].index]; + GLWall * ws=&walls[drawitems[sort->itemindex].index]; + + bool ceiling = fh->z > ViewPos.Z; + + if ((ws->ztop[0] > fh->z || ws->ztop[1] > fh->z) && (ws->zbottom[0] < fh->z || ws->zbottom[1] < fh->z)) + { + // We have to split this wall! + + // WARNING: NEVER EVER push a member of an array onto the array itself. + // Bad things will happen if the memory must be reallocated! + GLWall w = *ws; + AddWall(&w); + + // Splitting is done in the shader with clip planes, if available + if (gl.flags & RFL_NO_CLIP_PLANES) + { + GLWall * ws1; + ws->vertcount = 0; // invalidate current vertices. + ws1=&walls[walls.Size()-1]; + ws=&walls[drawitems[sort->itemindex].index]; // may have been reallocated! + float newtexv = ws->tcs[GLWall::UPLFT].v + ((ws->tcs[GLWall::LOLFT].v - ws->tcs[GLWall::UPLFT].v) / (ws->zbottom[0] - ws->ztop[0])) * (fh->z - ws->ztop[0]); + + // I make the very big assumption here that translucent walls in sloped sectors + // and 3D-floors never coexist in the same level. If that were the case this + // code would become extremely more complicated. + if (!ceiling) + { + ws->ztop[1] = ws1->zbottom[1] = ws->ztop[0] = ws1->zbottom[0] = fh->z; + ws->tcs[GLWall::UPRGT].v = ws1->tcs[GLWall::LORGT].v = ws->tcs[GLWall::UPLFT].v = ws1->tcs[GLWall::LOLFT].v = newtexv; + } + else + { + ws1->ztop[1] = ws->zbottom[1] = ws1->ztop[0] = ws->zbottom[0] = fh->z; + ws1->tcs[GLWall::UPLFT].v = ws->tcs[GLWall::LOLFT].v = ws1->tcs[GLWall::UPRGT].v = ws->tcs[GLWall::LORGT].v=newtexv; + } + } + + SortNode * sort2 = SortNodes.GetNew(); + memset(sort2, 0, sizeof(SortNode)); + sort2->itemindex = drawitems.Size() - 1; + + head->AddToLeft(sort); + head->AddToRight(sort2); + } + else if ((ws->zbottom[0]z && !ceiling) || (ws->ztop[0]>fh->z && ceiling)) // completely on the left side + { + head->AddToLeft(sort); + } + else + { + head->AddToRight(sort); + } + +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::SortSpriteIntoPlane(SortNode * head,SortNode * sort) +{ + GLFlat * fh=&flats[drawitems[head->itemindex].index]; + GLSprite * ss=&sprites[drawitems[sort->itemindex].index]; + + bool ceiling = fh->z > ViewPos.Z; + + if ((ss->z1>fh->z && ss->z2z) || ss->modelframe) + { + // We have to split this sprite + GLSprite s=*ss; + AddSprite(&s); // add a copy to avoid reallocation issues. + + // Splitting is done in the shader with clip planes, if available + if (gl.flags & RFL_NO_CLIP_PLANES) + { + GLSprite * ss1; + ss1=&sprites[sprites.Size()-1]; + ss=&sprites[drawitems[sort->itemindex].index]; // may have been reallocated! + float newtexv=ss->vt + ((ss->vb-ss->vt)/(ss->z2-ss->z1))*(fh->z-ss->z1); + + if (!ceiling) + { + ss->z1=ss1->z2=fh->z; + ss->vt=ss1->vb=newtexv; + } + else + { + ss1->z1=ss->z2=fh->z; + ss1->vt=ss->vb=newtexv; + } + } + + SortNode * sort2=SortNodes.GetNew(); + memset(sort2,0,sizeof(SortNode)); + sort2->itemindex=drawitems.Size()-1; + + head->AddToLeft(sort); + head->AddToRight(sort2); + } + else if ((ss->z2z && !ceiling) || (ss->z1>fh->z && ceiling)) // completely on the left side + { + head->AddToLeft(sort); + } + else + { + head->AddToRight(sort); + } + +} + + +//========================================================================== +// +// +// +//========================================================================== +#define MIN_EQ (0.0005f) + +void GLDrawList::SortWallIntoWall(SortNode * head,SortNode * sort) +{ + GLWall * wh=&walls[drawitems[head->itemindex].index]; + GLWall * ws=&walls[drawitems[sort->itemindex].index]; + GLWall * ws1; + float v1=wh->PointOnSide(ws->glseg.x1,ws->glseg.y1); + float v2=wh->PointOnSide(ws->glseg.x2,ws->glseg.y2); + + if (fabs(v1)type==RENDERWALL_FOGBOUNDARY && wh->type!=RENDERWALL_FOGBOUNDARY) + { + head->AddToRight(sort); + } + else if (ws->type!=RENDERWALL_FOGBOUNDARY && wh->type==RENDERWALL_FOGBOUNDARY) + { + head->AddToLeft(sort); + } + else + { + head->AddToEqual(sort); + } + } + else if (v1AddToLeft(sort); + } + else if (v1>-MIN_EQ && v2>-MIN_EQ) + { + head->AddToRight(sort); + } + else + { + double r=ws->CalcIntersectionVertex(wh); + + float ix=(float)(ws->glseg.x1+r*(ws->glseg.x2-ws->glseg.x1)); + float iy=(float)(ws->glseg.y1+r*(ws->glseg.y2-ws->glseg.y1)); + float iu=(float)(ws->tcs[GLWall::UPLFT].u + r * (ws->tcs[GLWall::UPRGT].u - ws->tcs[GLWall::UPLFT].u)); + float izt=(float)(ws->ztop[0]+r*(ws->ztop[1]-ws->ztop[0])); + float izb=(float)(ws->zbottom[0]+r*(ws->zbottom[1]-ws->zbottom[0])); + + ws->vertcount = 0; // invalidate current vertices. + GLWall w=*ws; + AddWall(&w); + ws1=&walls[walls.Size()-1]; + ws=&walls[drawitems[sort->itemindex].index]; // may have been reallocated! + + ws1->glseg.x1=ws->glseg.x2=ix; + ws1->glseg.y1=ws->glseg.y2=iy; + ws1->glseg.fracleft = ws->glseg.fracright = ws->glseg.fracleft + r*(ws->glseg.fracright - ws->glseg.fracleft); + ws1->ztop[0]=ws->ztop[1]=izt; + ws1->zbottom[0]=ws->zbottom[1]=izb; + ws1->tcs[GLWall::LOLFT].u = ws1->tcs[GLWall::UPLFT].u = ws->tcs[GLWall::LORGT].u = ws->tcs[GLWall::UPRGT].u = iu; + if (gl.buffermethod == BM_DEFERRED) + { + ws->MakeVertices(false); + ws1->MakeVertices(false); + } + + SortNode * sort2=SortNodes.GetNew(); + memset(sort2,0,sizeof(SortNode)); + sort2->itemindex=drawitems.Size()-1; + + if (v1>0) + { + head->AddToLeft(sort2); + head->AddToRight(sort); + } + else + { + head->AddToLeft(sort); + head->AddToRight(sort2); + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== +EXTERN_CVAR(Int, gl_billboard_mode) +EXTERN_CVAR(Bool, gl_billboard_faces_camera) +EXTERN_CVAR(Bool, gl_billboard_particles) + +void GLDrawList::SortSpriteIntoWall(SortNode * head,SortNode * sort) +{ + GLWall * wh=&walls[drawitems[head->itemindex].index]; + GLSprite * ss=&sprites[drawitems[sort->itemindex].index]; + GLSprite * ss1; + + float v1 = wh->PointOnSide(ss->x1, ss->y1); + float v2 = wh->PointOnSide(ss->x2, ss->y2); + + if (fabs(v1)type==RENDERWALL_FOGBOUNDARY) + { + head->AddToLeft(sort); + } + else + { + head->AddToEqual(sort); + } + } + else if (v1AddToLeft(sort); + } + else if (v1>-MIN_EQ && v2>-MIN_EQ) + { + head->AddToRight(sort); + } + else + { + const bool drawWithXYBillboard = ((ss->particle && gl_billboard_particles) || (!(ss->actor && ss->actor->renderflags & RF_FORCEYBILLBOARD) + && (gl_billboard_mode == 1 || (ss->actor && ss->actor->renderflags & RF_FORCEXYBILLBOARD)))); + + const bool drawBillboardFacingCamera = gl_billboard_faces_camera; + // [Nash] has +ROLLSPRITE + const bool rotated = (ss->actor != nullptr && ss->actor->renderflags & (RF_ROLLSPRITE | RF_WALLSPRITE | RF_FLATSPRITE)); + + // cannot sort them at the moment. This requires more complex splitting. + if (drawWithXYBillboard || drawBillboardFacingCamera || rotated) + { + float v1 = wh->PointOnSide(ss->x, ss->y); + if (v1 < 0) + { + head->AddToLeft(sort); + } + else + { + head->AddToRight(sort); + } + return; + } + double r=ss->CalcIntersectionVertex(wh); + + float ix=(float)(ss->x1 + r * (ss->x2-ss->x1)); + float iy=(float)(ss->y1 + r * (ss->y2-ss->y1)); + float iu=(float)(ss->ul + r * (ss->ur-ss->ul)); + + GLSprite s=*ss; + AddSprite(&s); + ss1=&sprites[sprites.Size()-1]; + ss=&sprites[drawitems[sort->itemindex].index]; // may have been reallocated! + + ss1->x1=ss->x2=ix; + ss1->y1=ss->y2=iy; + ss1->ul=ss->ur=iu; + + SortNode * sort2=SortNodes.GetNew(); + memset(sort2,0,sizeof(SortNode)); + sort2->itemindex=drawitems.Size()-1; + + if (v1>0) + { + head->AddToLeft(sort2); + head->AddToRight(sort); + } + else + { + head->AddToLeft(sort); + head->AddToRight(sort2); + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +inline int GLDrawList::CompareSprites(SortNode * a,SortNode * b) +{ + GLSprite * s1=&sprites[drawitems[a->itemindex].index]; + GLSprite * s2=&sprites[drawitems[b->itemindex].index]; + + int res = s1->depth - s2->depth; + + if (res != 0) return -res; + else return (i_compatflags & COMPATF_SPRITESORT)? s1->index-s2->index : s2->index-s1->index; +} + +//========================================================================== +// +// +// +//========================================================================== +static GLDrawList * gd; +int CompareSprite(const void * a,const void * b) +{ + return gd->CompareSprites(*(SortNode**)a,*(SortNode**)b); +} + +//========================================================================== +// +// +// +//========================================================================== +SortNode * GLDrawList::SortSpriteList(SortNode * head) +{ + SortNode * n; + int count; + unsigned i; + + static TArray sortspritelist; + + SortNode * parent=head->parent; + + sortspritelist.Clear(); + for(count=0,n=head;n;n=n->next) sortspritelist.Push(n); + gd=this; + qsort(&sortspritelist[0],sortspritelist.Size(),sizeof(SortNode *),CompareSprite); + for(i=0;inext=NULL; + if (parent) parent->equal=sortspritelist[i]; + parent=sortspritelist[i]; + } + return sortspritelist[0]; +} + +//========================================================================== +// +// +// +//========================================================================== +SortNode * GLDrawList::DoSort(SortNode * head) +{ + SortNode * node, * sn, * next; + + sn=FindSortPlane(head); + if (sn) + { + if (sn==head) head=head->next; + sn->UnlinkFromChain(); + node=head; + head=sn; + while (node) + { + next=node->next; + switch(drawitems[node->itemindex].rendertype) + { + case GLDIT_FLAT: + SortPlaneIntoPlane(head,node); + break; + + case GLDIT_WALL: + SortWallIntoPlane(head,node); + break; + + case GLDIT_SPRITE: + SortSpriteIntoPlane(head,node); + break; + } + node=next; + } + } + else + { + sn=FindSortWall(head); + if (sn) + { + if (sn==head) head=head->next; + sn->UnlinkFromChain(); + node=head; + head=sn; + while (node) + { + next=node->next; + switch(drawitems[node->itemindex].rendertype) + { + case GLDIT_WALL: + SortWallIntoWall(head,node); + break; + + case GLDIT_SPRITE: + SortSpriteIntoWall(head,node); + break; + + case GLDIT_FLAT: break; + } + node=next; + } + } + else + { + return SortSpriteList(head); + } + } + if (head->left) head->left=DoSort(head->left); + if (head->right) head->right=DoSort(head->right); + return sn; +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::DoDraw(int pass, int i, bool trans) +{ + switch(drawitems[i].rendertype) + { + case GLDIT_FLAT: + { + GLFlat * f=&flats[drawitems[i].index]; + RenderFlat.Clock(); + f->Draw(pass, trans); + RenderFlat.Unclock(); + } + break; + + case GLDIT_WALL: + { + GLWall * w=&walls[drawitems[i].index]; + RenderWall.Clock(); + w->Draw(pass); + RenderWall.Unclock(); + } + break; + + case GLDIT_SPRITE: + { + GLSprite * s=&sprites[drawitems[i].index]; + RenderSprite.Clock(); + s->Draw(pass); + RenderSprite.Unclock(); + } + break; + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::DoDrawSorted(SortNode * head) +{ + float clipsplit[2]; + int relation = 0; + float z = 0.f; + + gl_RenderState.GetClipSplit(clipsplit); + + if (drawitems[head->itemindex].rendertype == GLDIT_FLAT) + { + z = flats[drawitems[head->itemindex].index].z; + relation = z > ViewPos.Z ? 1 : -1; + } + + + // left is further away, i.e. for stuff above viewz its z coordinate higher, for stuff below viewz its z coordinate is lower + if (head->left) + { + if (relation == -1) + { + gl_RenderState.SetClipSplit(clipsplit[0], z); // render below: set flat as top clip plane + } + else if (relation == 1) + { + gl_RenderState.SetClipSplit(z, clipsplit[1]); // render above: set flat as bottom clip plane + } + DoDrawSorted(head->left); + gl_RenderState.SetClipSplit(clipsplit); + } + DoDraw(GLPASS_TRANSLUCENT, head->itemindex, true); + if (head->equal) + { + SortNode * ehead=head->equal; + while (ehead) + { + DoDraw(GLPASS_TRANSLUCENT, ehead->itemindex, true); + ehead=ehead->equal; + } + } + // right is closer, i.e. for stuff above viewz its z coordinate is lower, for stuff below viewz its z coordinate is higher + if (head->right) + { + if (relation == 1) + { + gl_RenderState.SetClipSplit(clipsplit[0], z); // render below: set flat as top clip plane + } + else if (relation == -1) + { + gl_RenderState.SetClipSplit(z, clipsplit[1]); // render above: set flat as bottom clip plane + } + DoDrawSorted(head->right); + gl_RenderState.SetClipSplit(clipsplit); + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::DrawSorted() +{ + if (drawitems.Size()==0) return; + + if (!sorted) + { + GLRenderer->mVBO->Map(); + MakeSortList(); + sorted=DoSort(SortNodes[SortNodeStart]); + GLRenderer->mVBO->Unmap(); + } + gl_RenderState.ClearClipSplit(); + if (!(gl.flags & RFL_NO_CLIP_PLANES)) + { + glEnable(GL_CLIP_DISTANCE1); + glEnable(GL_CLIP_DISTANCE2); + } + DoDrawSorted(sorted); + if (!(gl.flags & RFL_NO_CLIP_PLANES)) + { + glDisable(GL_CLIP_DISTANCE1); + glDisable(GL_CLIP_DISTANCE2); + } + gl_RenderState.ClearClipSplit(); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::Draw(int pass, bool trans) +{ + for(unsigned i=0;iwalls[di1->index]; + + const GLDrawItem * di2 = (const GLDrawItem *)b; + GLWall * w2=&sortinfo->walls[di2->index]; + + if (w1->gltexture != w2->gltexture) return w1->gltexture - w2->gltexture; + return ((w1->flags & 3) - (w2->flags & 3)); +} + +static int difcmp (const void *a, const void *b) +{ + const GLDrawItem * di1 = (const GLDrawItem *)a; + GLFlat * w1=&sortinfo->flats[di1->index]; + + const GLDrawItem * di2 = (const GLDrawItem *)b; + GLFlat* w2=&sortinfo->flats[di2->index]; + + return w1->gltexture - w2->gltexture; +} + + +void GLDrawList::SortWalls() +{ + if (drawitems.Size() > 1) + { + sortinfo=this; + qsort(&drawitems[0], drawitems.Size(), sizeof(drawitems[0]), diwcmp); + } +} + +void GLDrawList::SortFlats() +{ + if (drawitems.Size() > 1) + { + sortinfo=this; + qsort(&drawitems[0], drawitems.Size(), sizeof(drawitems[0]), difcmp); + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::AddWall(GLWall * wall) +{ + drawitems.Push(GLDrawItem(GLDIT_WALL,walls.Push(*wall))); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::AddFlat(GLFlat * flat) +{ + drawitems.Push(GLDrawItem(GLDIT_FLAT,flats.Push(*flat))); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLDrawList::AddSprite(GLSprite * sprite) +{ + drawitems.Push(GLDrawItem(GLDIT_SPRITE,sprites.Push(*sprite))); +} + + +//========================================================================== +// +// Try to reuse the lists as often as possible as they contain resources that +// are expensive to create and delete. +// +//========================================================================== + +FDrawInfo *FDrawInfoList::GetNew() +{ + if (mList.Size() > 0) + { + FDrawInfo *di; + mList.Pop(di); + return di; + } + return new FDrawInfo; +} + +void FDrawInfoList::Release(FDrawInfo * di) +{ + di->ClearBuffers(); + mList.Push(di); +} + +static FDrawInfoList di_list; + +//========================================================================== +// +// +// +//========================================================================== + +FDrawInfo::FDrawInfo() +{ + next = NULL; + if (gl.legacyMode) + { + dldrawlists = new GLDrawList[GLLDL_TYPES]; + } +} + +FDrawInfo::~FDrawInfo() +{ + if (dldrawlists != NULL) delete[] dldrawlists; + ClearBuffers(); +} + + +//========================================================================== +// +// Sets up a new drawinfo struct +// +//========================================================================== +void FDrawInfo::StartDrawInfo() +{ + FDrawInfo *di=di_list.GetNew(); + di->StartScene(); +} + +void FDrawInfo::StartScene() +{ + ClearBuffers(); + + sectorrenderflags.Resize(numsectors); + ss_renderflags.Resize(numsubsectors); + no_renderflags.Resize(numsubsectors); + + memset(§orrenderflags[0], 0, numsectors * sizeof(sectorrenderflags[0])); + memset(&ss_renderflags[0], 0, numsubsectors * sizeof(ss_renderflags[0])); + memset(&no_renderflags[0], 0, numnodes * sizeof(no_renderflags[0])); + + next = gl_drawinfo; + gl_drawinfo = this; + for (int i = 0; i < GLDL_TYPES; i++) drawlists[i].Reset(); + if (dldrawlists != NULL) + { + for (int i = 0; i < GLLDL_TYPES; i++) dldrawlists[i].Reset(); + } +} + +//========================================================================== +// +// +// +//========================================================================== +void FDrawInfo::EndDrawInfo() +{ + FDrawInfo * di = gl_drawinfo; + + for(int i=0;idrawlists[i].Reset(); + if (di->dldrawlists != NULL) + { + for (int i = 0; i < GLLDL_TYPES; i++) di->dldrawlists[i].Reset(); + } + gl_drawinfo=di->next; + di_list.Release(di); +} + + +//========================================================================== +// +// Flood gaps with the back side's ceiling/floor texture +// This requires a stencil because the projected plane interferes with +// the depth buffer +// +//========================================================================== + +void FDrawInfo::SetupFloodStencil(wallseg * ws) +{ + int recursion = GLPortal::GetRecursion(); + + // Create stencil + glStencilFunc(GL_EQUAL, recursion, ~0); // create stencil + glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // increment stencil of valid pixels + { + // Use revertible color mask, to avoid stomping on anaglyph 3D state + ScopedColorMask colorMask(0, 0, 0, 0); // glColorMask(0, 0, 0, 0); // don't write to the graphics buffer + gl_RenderState.EnableTexture(false); + gl_RenderState.ResetColor(); + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + + gl_RenderState.Apply(); + FQuadDrawer qd; + qd.Set(0, ws->x1, ws->z1, ws->y1, 0, 0); + qd.Set(1, ws->x1, ws->z2, ws->y1, 0, 0); + qd.Set(2, ws->x2, ws->z2, ws->y2, 0, 0); + qd.Set(3, ws->x2, ws->z1, ws->y2, 0, 0); + qd.Render(GL_TRIANGLE_FAN); + + glStencilFunc(GL_EQUAL, recursion + 1, ~0); // draw sky into stencil + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // this stage doesn't modify the stencil + + } // glColorMask(1, 1, 1, 1); // don't write to the graphics buffer + gl_RenderState.EnableTexture(true); + glDisable(GL_DEPTH_TEST); + glDepthMask(false); +} + +void FDrawInfo::ClearFloodStencil(wallseg * ws) +{ + int recursion = GLPortal::GetRecursion(); + + glStencilOp(GL_KEEP,GL_KEEP,GL_DECR); + gl_RenderState.EnableTexture(false); + { + // Use revertible color mask, to avoid stomping on anaglyph 3D state + ScopedColorMask colorMask(0, 0, 0, 0); // glColorMask(0,0,0,0); // don't write to the graphics buffer + gl_RenderState.ResetColor(); + + gl_RenderState.Apply(); + FQuadDrawer qd; + qd.Set(0, ws->x1, ws->z1, ws->y1, 0, 0); + qd.Set(1, ws->x1, ws->z2, ws->y1, 0, 0); + qd.Set(2, ws->x2, ws->z2, ws->y2, 0, 0); + qd.Set(3, ws->x2, ws->z1, ws->y2, 0, 0); + qd.Render(GL_TRIANGLE_FAN); + + // restore old stencil op. + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + glStencilFunc(GL_EQUAL, recursion, ~0); + gl_RenderState.EnableTexture(true); + } // glColorMask(1, 1, 1, 1); + glEnable(GL_DEPTH_TEST); + glDepthMask(true); +} + +//========================================================================== +// +// Draw the plane segment into the gap +// +//========================================================================== +void FDrawInfo::DrawFloodedPlane(wallseg * ws, float planez, sector_t * sec, bool ceiling) +{ + GLSectorPlane plane; + int lightlevel; + FColormap Colormap; + FMaterial * gltexture; + + plane.GetFromSector(sec, ceiling); + + gltexture=FMaterial::ValidateTexture(plane.texture, false, true); + if (!gltexture) return; + + if (gl_fixedcolormap) + { + Colormap.Clear(); + lightlevel=255; + } + else + { + Colormap=sec->ColorMap; + if (gltexture->tex->isFullbright()) + { + Colormap.LightColor.r = Colormap.LightColor.g = Colormap.LightColor.b = 0xff; + lightlevel=255; + } + else lightlevel=abs(ceiling? sec->GetCeilingLight() : sec->GetFloorLight()); + } + + int rel = getExtraLight(); + gl_SetColor(lightlevel, rel, Colormap, 1.0f); + gl_SetFog(lightlevel, rel, &Colormap, false); + gl_RenderState.SetMaterial(gltexture, CLAMP_NONE, 0, -1, false); + + float fviewx = ViewPos.X; + float fviewy = ViewPos.Y; + float fviewz = ViewPos.Z; + + gl_SetPlaneTextureRotation(&plane, gltexture); + gl_RenderState.Apply(); + + float prj_fac1 = (planez-fviewz)/(ws->z1-fviewz); + float prj_fac2 = (planez-fviewz)/(ws->z2-fviewz); + + float px1 = fviewx + prj_fac1 * (ws->x1-fviewx); + float py1 = fviewy + prj_fac1 * (ws->y1-fviewy); + + float px2 = fviewx + prj_fac2 * (ws->x1-fviewx); + float py2 = fviewy + prj_fac2 * (ws->y1-fviewy); + + float px3 = fviewx + prj_fac2 * (ws->x2-fviewx); + float py3 = fviewy + prj_fac2 * (ws->y2-fviewy); + + float px4 = fviewx + prj_fac1 * (ws->x2-fviewx); + float py4 = fviewy + prj_fac1 * (ws->y2-fviewy); + + FQuadDrawer qd; + qd.Set(0, px1, planez, py1, px1 / 64, -py1 / 64); + qd.Set(1, px2, planez, py2, px2 / 64, -py2 / 64); + qd.Set(2, px3, planez, py3, px3 / 64, -py3 / 64); + qd.Set(3, px4, planez, py4, px4 / 64, -py4 / 64); + qd.Render(GL_TRIANGLE_FAN); + + gl_RenderState.EnableTextureMatrix(false); +} + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::FloodUpperGap(seg_t * seg) +{ + wallseg ws; + sector_t ffake, bfake; + sector_t * fakefsector = gl_FakeFlat(seg->frontsector, &ffake, true); + sector_t * fakebsector = gl_FakeFlat(seg->backsector, &bfake, false); + + vertex_t * v1, * v2; + + // Although the plane can be sloped this code will only be called + // when the edge itself is not. + double backz = fakebsector->ceilingplane.ZatPoint(seg->v1); + double frontz = fakefsector->ceilingplane.ZatPoint(seg->v1); + + if (fakebsector->GetTexture(sector_t::ceiling)==skyflatnum) return; + if (backz < ViewPos.Z) return; + + if (seg->sidedef == seg->linedef->sidedef[0]) + { + v1=seg->linedef->v1; + v2=seg->linedef->v2; + } + else + { + v1=seg->linedef->v2; + v2=seg->linedef->v1; + } + + ws.x1 = v1->fX(); + ws.y1 = v1->fY(); + ws.x2 = v2->fX(); + ws.y2 = v2->fY(); + + ws.z1= frontz; + ws.z2= backz; + + // Step1: Draw a stencil into the gap + SetupFloodStencil(&ws); + + // Step2: Project the ceiling plane into the gap + DrawFloodedPlane(&ws, ws.z2, fakebsector, true); + + // Step3: Delete the stencil + ClearFloodStencil(&ws); +} + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::FloodLowerGap(seg_t * seg) +{ + wallseg ws; + sector_t ffake, bfake; + sector_t * fakefsector = gl_FakeFlat(seg->frontsector, &ffake, true); + sector_t * fakebsector = gl_FakeFlat(seg->backsector, &bfake, false); + + vertex_t * v1, * v2; + + // Although the plane can be sloped this code will only be called + // when the edge itself is not. + double backz = fakebsector->floorplane.ZatPoint(seg->v1); + double frontz = fakefsector->floorplane.ZatPoint(seg->v1); + + + if (fakebsector->GetTexture(sector_t::floor) == skyflatnum) return; + if (fakebsector->GetPlaneTexZ(sector_t::floor) > ViewPos.Z) return; + + if (seg->sidedef == seg->linedef->sidedef[0]) + { + v1=seg->linedef->v1; + v2=seg->linedef->v2; + } + else + { + v1=seg->linedef->v2; + v2=seg->linedef->v1; + } + + ws.x1 = v1->fX(); + ws.y1 = v1->fY(); + ws.x2 = v2->fX(); + ws.y2 = v2->fY(); + + ws.z2= frontz; + ws.z1= backz; + + // Step1: Draw a stencil into the gap + SetupFloodStencil(&ws); + + // Step2: Project the ceiling plane into the gap + DrawFloodedPlane(&ws, ws.z1, fakebsector, false); + + // Step3: Delete the stencil + ClearFloodStencil(&ws); +} diff --git a/src/gl/scene/gl_drawinfo.h b/src/gl/scene/gl_drawinfo.h new file mode 100644 index 000000000..0e7296ee3 --- /dev/null +++ b/src/gl/scene/gl_drawinfo.h @@ -0,0 +1,301 @@ +#ifndef __GL_DRAWINFO_H +#define __GL_DRAWINFO_H + +#include "gl/scene/gl_wall.h" + +enum GLDrawItemType +{ + GLDIT_WALL, + GLDIT_FLAT, + GLDIT_SPRITE, +}; + +enum DrawListType +{ + GLDL_PLAINWALLS, + GLDL_PLAINFLATS, + GLDL_MASKEDWALLS, + GLDL_MASKEDFLATS, + GLDL_MASKEDWALLSOFS, + GLDL_MODELS, + + GLDL_TRANSLUCENT, + GLDL_TRANSLUCENTBORDER, + + GLDL_TYPES, +}; + +// more lists for handling of dynamic lights +enum DLDrawListType +{ + // These are organized so that the various multipass rendering modes have to be set as few times as possible + GLLDL_WALLS_PLAIN, // dynamic lights on normal walls + GLLDL_WALLS_MASKED, // dynamic lights on masked midtextures + + GLLDL_FLATS_PLAIN, // dynamic lights on normal flats + GLLDL_FLATS_MASKED, // dynamic lights on masked flats + + GLLDL_WALLS_FOG, // lights on fogged walls + GLLDL_WALLS_FOGMASKED, // lights on fogged masked midtextures + + GLLDL_FLATS_FOG, // lights on fogged walls + GLLDL_FLATS_FOGMASKED, // lights on fogged masked midtextures + + GLLDL_TYPES, +}; + + +enum Drawpasses +{ + GLPASS_ALL, // Main pass with dynamic lights + GLPASS_LIGHTSONLY, // only collect dynamic lights + GLPASS_PLAIN, // Main pass without dynamic lights + GLPASS_DECALS, // Draws a decal + GLPASS_TRANSLUCENT, // Draws translucent objects + + // these are only used with texture based dynamic lights + GLPASS_BASE, // untextured base for dynamic lights + GLPASS_BASE_MASKED, // same but with active texture + GLPASS_LIGHTTEX, // lighttexture pass + GLPASS_TEXONLY, // finishing texture pass + GLPASS_LIGHTTEX_ADDITIVE, // lighttexture pass (additive) + GLPASS_LIGHTTEX_FOGGY, // lighttexture pass on foggy surfaces (forces all lights to be additive) + +}; + +//========================================================================== +// +// Intermediate struct to link one draw item into a draw list +// +// unfortunately this struct must not contain pointers because +// the arrays may be reallocated! +// +//========================================================================== + +struct GLDrawItem +{ + GLDrawItemType rendertype; + int index; + + GLDrawItem(GLDrawItemType _rendertype,int _index) : rendertype(_rendertype),index(_index) {} +}; + +struct SortNode +{ + int itemindex; + SortNode * parent; + SortNode * next; // unsorted successor + SortNode * left; // left side of this node + SortNode * equal; // equal to this node + SortNode * right; // right side of this node + + + void UnlinkFromChain(); + void Link(SortNode * hook); + void AddToEqual(SortNode * newnode); + void AddToLeft (SortNode * newnode); + void AddToRight(SortNode * newnode); +}; + +//========================================================================== +// +// One draw list. This contains all info for one type of rendering data +// +//========================================================================== + +struct GLDrawList +{ +//private: + TArray walls; + TArray flats; + TArray sprites; + TArray drawitems; + int SortNodeStart; + SortNode * sorted; + +public: + GLDrawList() + { + next=NULL; + SortNodeStart=-1; + sorted=NULL; + } + + ~GLDrawList() + { + Reset(); + } + + unsigned int Size() + { + return drawitems.Size(); + } + + void AddWall(GLWall * wall); + void AddFlat(GLFlat * flat); + void AddSprite(GLSprite * sprite); + void Reset(); + void SortWalls(); + void SortFlats(); + + + void MakeSortList(); + SortNode * FindSortPlane(SortNode * head); + SortNode * FindSortWall(SortNode * head); + void SortPlaneIntoPlane(SortNode * head,SortNode * sort); + void SortWallIntoPlane(SortNode * head,SortNode * sort); + void SortSpriteIntoPlane(SortNode * head,SortNode * sort); + void SortWallIntoWall(SortNode * head,SortNode * sort); + void SortSpriteIntoWall(SortNode * head,SortNode * sort); + int CompareSprites(SortNode * a,SortNode * b); + SortNode * SortSpriteList(SortNode * head); + SortNode * DoSort(SortNode * head); + + void DoDraw(int pass, int index, bool trans); + void DoDrawSorted(SortNode * node); + void DrawSorted(); + void Draw(int pass, bool trans = false); + void DrawWalls(int pass); + void DrawFlats(int pass); + void DrawDecals(); + + GLDrawList * next; +} ; + + +//========================================================================== +// +// these are used to link faked planes due to missing textures to a sector +// +//========================================================================== +struct gl_subsectorrendernode +{ + gl_subsectorrendernode * next; + subsector_t * sub; +}; + + +struct FDrawInfo +{ + struct wallseg + { + float x1, y1, z1, x2, y2, z2; + }; + + bool temporary; + + + + struct MissingTextureInfo + { + seg_t * seg; + subsector_t * sub; + float Planez; + float Planezfront; + }; + + struct MissingSegInfo + { + seg_t * seg; + int MTI_Index; // tells us which MissingTextureInfo represents this seg. + }; + + struct SubsectorHackInfo + { + subsector_t * sub; + BYTE flags; + }; + + TArray sectorrenderflags; + TArray ss_renderflags; + TArray no_renderflags; + + TArray MissingUpperTextures; + TArray MissingLowerTextures; + + TArray MissingUpperSegs; + TArray MissingLowerSegs; + + TArray SubsectorHacks; + + TArray otherfloorplanes; + TArray otherceilingplanes; + + TArray CeilingStacks; + TArray FloorStacks; + + TArray HandledSubsectors; + + FDrawInfo * next; + GLDrawList drawlists[GLDL_TYPES]; + GLDrawList *dldrawlists = NULL; // only gets allocated when needed. + + FDrawInfo(); + ~FDrawInfo(); + void ClearBuffers(); + + bool DoOneSectorUpper(subsector_t * subsec, float planez); + bool DoOneSectorLower(subsector_t * subsec, float planez); + bool DoFakeBridge(subsector_t * subsec, float planez); + bool DoFakeCeilingBridge(subsector_t * subsec, float planez); + + bool CheckAnchorFloor(subsector_t * sub); + bool CollectSubsectorsFloor(subsector_t * sub, sector_t * anchor); + bool CheckAnchorCeiling(subsector_t * sub); + bool CollectSubsectorsCeiling(subsector_t * sub, sector_t * anchor); + void CollectSectorStacksCeiling(subsector_t * sub, sector_t * anchor); + void CollectSectorStacksFloor(subsector_t * sub, sector_t * anchor); + + void AddUpperMissingTexture(side_t * side, subsector_t *sub, float backheight); + void AddLowerMissingTexture(side_t * side, subsector_t *sub, float backheight); + void HandleMissingTextures(); + void DrawUnhandledMissingTextures(); + void AddHackedSubsector(subsector_t * sub); + void HandleHackedSubsectors(); + void AddFloorStack(sector_t * sec); + void AddCeilingStack(sector_t * sec); + void ProcessSectorStacks(); + + void AddOtherFloorPlane(int sector, gl_subsectorrendernode * node); + void AddOtherCeilingPlane(int sector, gl_subsectorrendernode * node); + + void StartScene(); + void SetupFloodStencil(wallseg * ws); + void ClearFloodStencil(wallseg * ws); + void DrawFloodedPlane(wallseg * ws, float planez, sector_t * sec, bool ceiling); + void FloodUpperGap(seg_t * seg); + void FloodLowerGap(seg_t * seg); + + static void StartDrawInfo(); + static void EndDrawInfo(); + + gl_subsectorrendernode * GetOtherFloorPlanes(unsigned int sector) + { + if (sector mList; + +public: + + FDrawInfo *GetNew(); + void Release(FDrawInfo *); +}; + + +extern FDrawInfo * gl_drawinfo; + +void gl_SetPlaneTextureRotation(const GLSectorPlane * secplane, FMaterial * gltexture); +void gl_SetRenderStyle(FRenderStyle style, bool drawopaque, bool allowcolorblending); + +#endif \ No newline at end of file diff --git a/src/gl/scene/gl_fakeflat.cpp b/src/gl/scene/gl_fakeflat.cpp new file mode 100644 index 000000000..b35b36c0e --- /dev/null +++ b/src/gl/scene/gl_fakeflat.cpp @@ -0,0 +1,391 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2001-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_fakeflat.cpp +** Fake flat functions to render stacked sectors +** +*/ + +#include "p_lnspec.h" +#include "p_local.h" +#include "a_sharedglobal.h" +#include "r_sky.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/scene/gl_clipper.h" +#include "gl/data/gl_data.h" + + +//========================================================================== +// +// Check whether the player can look beyond this line +// +//========================================================================== +CVAR(Bool, gltest_slopeopt, false, 0) + +bool gl_CheckClip(side_t * sidedef, sector_t * frontsector, sector_t * backsector) +{ + line_t *linedef = sidedef->linedef; + double bs_floorheight1; + double bs_floorheight2; + double bs_ceilingheight1; + double bs_ceilingheight2; + double fs_floorheight1; + double fs_floorheight2; + double fs_ceilingheight1; + double fs_ceilingheight2; + + // Mirrors and horizons always block the view + //if (linedef->special==Line_Mirror || linedef->special==Line_Horizon) return true; + + // Lines with portals must never block. + // Portals which require the sky flat are excluded here, because for them the special sky semantics apply. + if (!(frontsector->GetPortal(sector_t::ceiling)->mFlags & PORTSF_SKYFLATONLY) || + !(frontsector->GetPortal(sector_t::floor)->mFlags & PORTSF_SKYFLATONLY) || + !(backsector->GetPortal(sector_t::ceiling)->mFlags & PORTSF_SKYFLATONLY) || + !(backsector->GetPortal(sector_t::floor)->mFlags & PORTSF_SKYFLATONLY)) + { + return false; + } + + // on large levels this distinction can save some time + // That's a lot of avoided multiplications if there's a lot to see! + + if (frontsector->ceilingplane.isSlope()) + { + fs_ceilingheight1 = frontsector->ceilingplane.ZatPoint(linedef->v1); + fs_ceilingheight2 = frontsector->ceilingplane.ZatPoint(linedef->v2); + } + else + { + fs_ceilingheight2 = fs_ceilingheight1 = frontsector->ceilingplane.fD(); + } + + if (frontsector->floorplane.isSlope()) + { + fs_floorheight1 = frontsector->floorplane.ZatPoint(linedef->v1); + fs_floorheight2 = frontsector->floorplane.ZatPoint(linedef->v2); + } + else + { + fs_floorheight2 = fs_floorheight1 = -frontsector->floorplane.fD(); + } + + if (backsector->ceilingplane.isSlope()) + { + bs_ceilingheight1 = backsector->ceilingplane.ZatPoint(linedef->v1); + bs_ceilingheight2 = backsector->ceilingplane.ZatPoint(linedef->v2); + } + else + { + bs_ceilingheight2 = bs_ceilingheight1 = backsector->ceilingplane.fD(); + } + + if (backsector->floorplane.isSlope()) + { + bs_floorheight1 = backsector->floorplane.ZatPoint(linedef->v1); + bs_floorheight2 = backsector->floorplane.ZatPoint(linedef->v2); + } + else + { + bs_floorheight2 = bs_floorheight1 = -backsector->floorplane.fD(); + } + + // now check for closed sectors! + if (bs_ceilingheight1 <= fs_floorheight1 && bs_ceilingheight2 <= fs_floorheight2) + { + FTexture * tex = TexMan(sidedef->GetTexture(side_t::top)); + if (!tex || tex->UseType == FTexture::TEX_Null) return false; + if (backsector->GetTexture(sector_t::ceiling) == skyflatnum && + frontsector->GetTexture(sector_t::ceiling) == skyflatnum) return false; + return true; + } + + if (fs_ceilingheight1 <= bs_floorheight1 && fs_ceilingheight2 <= bs_floorheight2) + { + FTexture * tex = TexMan(sidedef->GetTexture(side_t::bottom)); + if (!tex || tex->UseType == FTexture::TEX_Null) return false; + + // properly render skies (consider door "open" if both floors are sky): + if (backsector->GetTexture(sector_t::ceiling) == skyflatnum && + frontsector->GetTexture(sector_t::ceiling) == skyflatnum) return false; + return true; + } + + if (bs_ceilingheight1 <= bs_floorheight1 && bs_ceilingheight2 <= bs_floorheight2) + { + // preserve a kind of transparent door/lift special effect: + if (bs_ceilingheight1 < fs_ceilingheight1 || bs_ceilingheight2 < fs_ceilingheight2) + { + FTexture * tex = TexMan(sidedef->GetTexture(side_t::top)); + if (!tex || tex->UseType == FTexture::TEX_Null) return false; + } + if (bs_floorheight1 > fs_floorheight1 || bs_floorheight2 > fs_floorheight2) + { + FTexture * tex = TexMan(sidedef->GetTexture(side_t::bottom)); + if (!tex || tex->UseType == FTexture::TEX_Null) return false; + } + if (backsector->GetTexture(sector_t::ceiling) == skyflatnum && + frontsector->GetTexture(sector_t::ceiling) == skyflatnum) return false; + if (backsector->GetTexture(sector_t::floor) == skyflatnum && frontsector->GetTexture(sector_t::floor) + == skyflatnum) return false; + return true; + } + + return false; +} + +//========================================================================== +// +// check for levels with exposed lower areas +// +//========================================================================== + +void gl_CheckViewArea(vertex_t *v1, vertex_t *v2, sector_t *frontsector, sector_t *backsector) +{ + if (in_area == area_default && + (backsector->heightsec && !(backsector->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC)) && + (!frontsector->heightsec || frontsector->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC)) + { + sector_t * s = backsector->heightsec; + + double cz1 = frontsector->ceilingplane.ZatPoint(v1); + double cz2 = frontsector->ceilingplane.ZatPoint(v2); + double fz1 = s->floorplane.ZatPoint(v1); + double fz2 = s->floorplane.ZatPoint(v2); + + // allow some tolerance in case slopes are involved + if (cz1 <= fz1 + 1. / 100 && cz2 <= fz2 + 1. / 100) + in_area = area_below; + else + in_area = area_normal; + } +} + + +//========================================================================== +// +// This is mostly like R_FakeFlat but with a few alterations necessitated +// by hardware rendering +// +//========================================================================== +sector_t * gl_FakeFlat(sector_t * sec, sector_t * dest, area_t in_area, bool back) +{ + if (!sec->heightsec || sec->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC || sec->heightsec==sec) + { + // check for backsectors with the ceiling lower than the floor. These will create + // visual glitches because upper amd lower textures overlap. + if (back && sec->planes[sector_t::floor].TexZ > sec->planes[sector_t::ceiling].TexZ) + { + if (!sec->floorplane.isSlope() && !sec->ceilingplane.isSlope()) + { + *dest = *sec; + dest->ceilingplane=sec->floorplane; + dest->ceilingplane.FlipVert(); + dest->planes[sector_t::ceiling].TexZ = dest->planes[sector_t::floor].TexZ; + dest->ClearPortal(sector_t::ceiling); + dest->ClearPortal(sector_t::floor); + return dest; + } + } + return sec; + } + +#ifdef _DEBUG + if (sec-sectors==560) + { + int a = 0; + } +#endif + + if (in_area==area_above) + { + if (sec->heightsec->MoreFlags&SECF_FAKEFLOORONLY /*|| sec->GetTexture(sector_t::ceiling)==skyflatnum*/) in_area=area_normal; + } + + int diffTex = (sec->heightsec->MoreFlags & SECF_CLIPFAKEPLANES); + sector_t * s = sec->heightsec; + +#if 0 + *dest=*sec; // This will invoke the copy operator which isn't really needed here. Memcpy is faster. +#else + memcpy(dest, sec, sizeof(sector_t)); +#endif + + // Replace floor and ceiling height with control sector's heights. + if (diffTex) + { + if (s->floorplane.CopyPlaneIfValid (&dest->floorplane, &sec->ceilingplane)) + { + dest->SetTexture(sector_t::floor, s->GetTexture(sector_t::floor), false); + dest->SetPlaneTexZ(sector_t::floor, s->GetPlaneTexZ(sector_t::floor)); + dest->vboindex[sector_t::floor] = sec->vboindex[sector_t::vbo_fakefloor]; + dest->vboheight[sector_t::floor] = s->vboheight[sector_t::floor]; + } + else if (s->MoreFlags & SECF_FAKEFLOORONLY) + { + if (in_area==area_below) + { + dest->ColorMap=s->ColorMap; + if (!(s->MoreFlags & SECF_NOFAKELIGHT)) + { + dest->lightlevel = s->lightlevel; + dest->SetPlaneLight(sector_t::floor, s->GetPlaneLight(sector_t::floor)); + dest->SetPlaneLight(sector_t::ceiling, s->GetPlaneLight(sector_t::ceiling)); + dest->ChangeFlags(sector_t::floor, -1, s->GetFlags(sector_t::floor)); + dest->ChangeFlags(sector_t::ceiling, -1, s->GetFlags(sector_t::ceiling)); + } + return dest; + } + return sec; + } + } + else + { + dest->SetPlaneTexZ(sector_t::floor, s->GetPlaneTexZ(sector_t::floor)); + dest->floorplane = s->floorplane; + + dest->vboindex[sector_t::floor] = sec->vboindex[sector_t::vbo_fakefloor]; + dest->vboheight[sector_t::floor] = s->vboheight[sector_t::floor]; + } + + if (!(s->MoreFlags&SECF_FAKEFLOORONLY)) + { + if (diffTex) + { + if (s->ceilingplane.CopyPlaneIfValid (&dest->ceilingplane, &sec->floorplane)) + { + dest->SetTexture(sector_t::ceiling, s->GetTexture(sector_t::ceiling), false); + dest->SetPlaneTexZ(sector_t::ceiling, s->GetPlaneTexZ(sector_t::ceiling)); + dest->vboindex[sector_t::ceiling] = sec->vboindex[sector_t::vbo_fakeceiling]; + dest->vboheight[sector_t::ceiling] = s->vboheight[sector_t::ceiling]; + } + } + else + { + dest->ceilingplane = s->ceilingplane; + dest->SetPlaneTexZ(sector_t::ceiling, s->GetPlaneTexZ(sector_t::ceiling)); + dest->vboindex[sector_t::ceiling] = sec->vboindex[sector_t::vbo_fakeceiling]; + dest->vboheight[sector_t::ceiling] = s->vboheight[sector_t::ceiling]; + } + } + + if (in_area==area_below) + { + dest->ColorMap=s->ColorMap; + dest->SetPlaneTexZ(sector_t::floor, sec->GetPlaneTexZ(sector_t::floor)); + dest->SetPlaneTexZ(sector_t::ceiling, s->GetPlaneTexZ(sector_t::floor)); + dest->floorplane=sec->floorplane; + dest->ceilingplane=s->floorplane; + dest->ceilingplane.FlipVert(); + + dest->vboindex[sector_t::floor] = sec->vboindex[sector_t::floor]; + dest->vboheight[sector_t::floor] = sec->vboheight[sector_t::floor]; + + dest->vboindex[sector_t::ceiling] = sec->vboindex[sector_t::vbo_fakefloor]; + dest->vboheight[sector_t::ceiling] = s->vboheight[sector_t::floor]; + + dest->ClearPortal(sector_t::ceiling); + + if (!(s->MoreFlags & SECF_NOFAKELIGHT)) + { + dest->lightlevel = s->lightlevel; + } + + if (!back) + { + dest->SetTexture(sector_t::floor, diffTex ? sec->GetTexture(sector_t::floor) : s->GetTexture(sector_t::floor), false); + dest->planes[sector_t::floor].xform = s->planes[sector_t::floor].xform; + + //dest->ceilingplane = s->floorplane; + + if (s->GetTexture(sector_t::ceiling) == skyflatnum) + { + dest->SetTexture(sector_t::ceiling, dest->GetTexture(sector_t::floor), false); + //dest->floorplane = dest->ceilingplane; + //dest->floorplane.FlipVert (); + //dest->floorplane.ChangeHeight (+1); + dest->planes[sector_t::ceiling].xform = dest->planes[sector_t::floor].xform; + + } + else + { + dest->SetTexture(sector_t::ceiling, diffTex ? s->GetTexture(sector_t::floor) : s->GetTexture(sector_t::ceiling), false); + dest->planes[sector_t::ceiling].xform = s->planes[sector_t::ceiling].xform; + } + + if (!(s->MoreFlags & SECF_NOFAKELIGHT)) + { + dest->SetPlaneLight(sector_t::floor, s->GetPlaneLight(sector_t::floor)); + dest->SetPlaneLight(sector_t::ceiling, s->GetPlaneLight(sector_t::ceiling)); + dest->ChangeFlags(sector_t::floor, -1, s->GetFlags(sector_t::floor)); + dest->ChangeFlags(sector_t::ceiling, -1, s->GetFlags(sector_t::ceiling)); + } + } + } + else if (in_area == area_above) + { + dest->ColorMap = s->ColorMap; + dest->SetPlaneTexZ(sector_t::ceiling, sec->GetPlaneTexZ(sector_t::ceiling)); + dest->SetPlaneTexZ(sector_t::floor, s->GetPlaneTexZ(sector_t::ceiling)); + dest->ceilingplane = sec->ceilingplane; + dest->floorplane = s->ceilingplane; + dest->floorplane.FlipVert(); + + dest->vboindex[sector_t::floor] = sec->vboindex[sector_t::vbo_fakeceiling]; + dest->vboheight[sector_t::floor] = s->vboheight[sector_t::ceiling]; + + dest->vboindex[sector_t::ceiling] = sec->vboindex[sector_t::ceiling]; + dest->vboheight[sector_t::ceiling] = sec->vboheight[sector_t::ceiling]; + + dest->ClearPortal(sector_t::floor); + + if (!(s->MoreFlags & SECF_NOFAKELIGHT)) + { + dest->lightlevel = s->lightlevel; + } + + if (!back) + { + dest->SetTexture(sector_t::ceiling, diffTex ? sec->GetTexture(sector_t::ceiling) : s->GetTexture(sector_t::ceiling), false); + dest->SetTexture(sector_t::floor, s->GetTexture(sector_t::ceiling), false); + dest->planes[sector_t::ceiling].xform = dest->planes[sector_t::floor].xform = s->planes[sector_t::ceiling].xform; + + if (s->GetTexture(sector_t::floor) != skyflatnum) + { + dest->SetTexture(sector_t::floor, s->GetTexture(sector_t::floor), false); + dest->planes[sector_t::floor].xform = s->planes[sector_t::floor].xform; + } + + if (!(s->MoreFlags & SECF_NOFAKELIGHT)) + { + dest->lightlevel = s->lightlevel; + dest->SetPlaneLight(sector_t::floor, s->GetPlaneLight(sector_t::floor)); + dest->SetPlaneLight(sector_t::ceiling, s->GetPlaneLight(sector_t::ceiling)); + dest->ChangeFlags(sector_t::floor, -1, s->GetFlags(sector_t::floor)); + dest->ChangeFlags(sector_t::ceiling, -1, s->GetFlags(sector_t::ceiling)); + } + } + } + return dest; +} + + diff --git a/src/gl/scene/gl_flats.cpp b/src/gl/scene/gl_flats.cpp new file mode 100644 index 000000000..bc47e448b --- /dev/null +++ b/src/gl/scene/gl_flats.cpp @@ -0,0 +1,822 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_flat.cpp +** Flat rendering +** +*/ + +#include "gl/system/gl_system.h" +#include "a_sharedglobal.h" +#include "r_defs.h" +#include "r_sky.h" +#include "r_utility.h" +#include "g_level.h" +#include "doomstat.h" +#include "d_player.h" +#include "portal.h" +#include "templates.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/dynlights/gl_lightbuffer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_convert.h" +#include "gl/utility/gl_templates.h" +#include "gl/renderer/gl_quaddrawer.h" + +#ifdef _DEBUG +CVAR(Int, gl_breaksec, -1, 0) +#endif +//========================================================================== +// +// Sets the texture matrix according to the plane's texture positioning +// information +// +//========================================================================== +static float tics; +void gl_SetPlaneTextureRotation(const GLSectorPlane * secplane, FMaterial * gltexture) +{ + // only manipulate the texture matrix if needed. + if (!secplane->Offs.isZero() || + secplane->Scale.X != 1. || secplane->Scale.Y != 1 || + secplane->Angle != 0 || + gltexture->TextureWidth() != 64 || + gltexture->TextureHeight() != 64) + { + float uoffs = secplane->Offs.X / gltexture->TextureWidth(); + float voffs = secplane->Offs.Y / gltexture->TextureHeight(); + + float xscale1 = secplane->Scale.X; + float yscale1 = secplane->Scale.Y; + if (gltexture->tex->bHasCanvas) + { + yscale1 = 0 - yscale1; + } + float angle = -secplane->Angle; + + float xscale2 = 64.f / gltexture->TextureWidth(); + float yscale2 = 64.f / gltexture->TextureHeight(); + + gl_RenderState.mTextureMatrix.loadIdentity(); + gl_RenderState.mTextureMatrix.scale(xscale1, yscale1, 1.0f); + gl_RenderState.mTextureMatrix.translate(uoffs, voffs, 0.0f); + gl_RenderState.mTextureMatrix.scale(xscale2, yscale2, 1.0f); + gl_RenderState.mTextureMatrix.rotate(angle, 0.0f, 0.0f, 1.0f); + gl_RenderState.EnableTextureMatrix(true); + } +} + + + +//========================================================================== +// +// Flats +// +//========================================================================== +extern FDynLightData lightdata; + +void GLFlat::SetupSubsectorLights(int pass, subsector_t * sub, int *dli) +{ + Plane p; + + if (renderstyle == STYLE_Add && !glset.lightadditivesurfaces) return; // no lights on additively blended surfaces. + + if (dli != NULL && *dli != -1) + { + gl_RenderState.ApplyLightIndex(GLRenderer->mLights->GetIndex(*dli)); + (*dli)++; + return; + } + + lightdata.Clear(); + FLightNode * node = sub->lighthead; + while (node) + { + ADynamicLight * light = node->lightsource; + + if (light->flags2&MF2_DORMANT) + { + node=node->nextLight; + continue; + } + iter_dlightf++; + + // we must do the side check here because gl_SetupLight needs the correct plane orientation + // which we don't have for Legacy-style 3D-floors + double planeh = plane.plane.ZatPoint(light); + if (gl_lights_checkside && ((planehZ() && ceiling) || (planeh>light->Z() && !ceiling))) + { + node = node->nextLight; + continue; + } + + p.Set(plane.plane); + gl_GetLight(sub->sector->PortalGroup, p, light, false, lightdata); + node = node->nextLight; + } + + int d = GLRenderer->mLights->UploadLights(lightdata); + if (pass == GLPASS_LIGHTSONLY) + { + GLRenderer->mLights->StoreIndex(d); + } + else + { + gl_RenderState.ApplyLightIndex(d); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLFlat::DrawSubsector(subsector_t * sub) +{ + if (gl.buffermethod != BM_DEFERRED) + { + FFlatVertex *ptr = GLRenderer->mVBO->GetBuffer(); + for (unsigned int k = 0; k < sub->numlines; k++) + { + vertex_t *vt = sub->firstline[k].v1; + ptr->x = vt->fX(); + ptr->z = plane.plane.ZatPoint(vt) + dz; + ptr->y = vt->fY(); + ptr->u = vt->fX() / 64.f; + ptr->v = -vt->fY() / 64.f; + ptr++; + } + GLRenderer->mVBO->RenderCurrent(ptr, GL_TRIANGLE_FAN); + } + else + { + // if we cannot access the buffer, use the quad drawer as fallback by splitting the subsector into quads. + // Trying to get this into the vertex buffer in the processing pass is too costly and this is only used for render hacks. + FQuadDrawer qd; + unsigned int vi[4]; + + vi[0] = 0; + for (unsigned int i = 0; i < sub->numlines - 2; i += 2) + { + for (unsigned int j = 1; j < 4; j++) + { + vi[j] = MIN(i + j, sub->numlines - 1); + } + for (unsigned int x = 0; x < 4; x++) + { + vertex_t *vt = sub->firstline[vi[x]].v1; + qd.Set(x, vt->fX(), plane.plane.ZatPoint(vt) + dz, vt->fY(), vt->fX() / 64.f, -vt->fY() / 64.f); + } + qd.Render(GL_TRIANGLE_FAN); + } + } + + flatvertices += sub->numlines; + flatprimitives++; +} + + +//========================================================================== +// +// this is only used by LM_DEFERRED +// +//========================================================================== + +void GLFlat::ProcessLights(bool istrans) +{ + dynlightindex = GLRenderer->mLights->GetIndexPtr(); + + // Draw the subsectors belonging to this sector + for (int i=0; isubsectorcount; i++) + { + subsector_t * sub = sector->subsectors[i]; + if (gl_drawinfo->ss_renderflags[sub-subsectors]&renderflags || istrans) + { + SetupSubsectorLights(GLPASS_LIGHTSONLY, sub); + } + } + + // Draw the subsectors assigned to it due to missing textures + if (!(renderflags&SSRF_RENDER3DPLANES)) + { + gl_subsectorrendernode * node = (renderflags&SSRF_RENDERFLOOR)? + gl_drawinfo->GetOtherFloorPlanes(sector->sectornum) : + gl_drawinfo->GetOtherCeilingPlanes(sector->sectornum); + + while (node) + { + SetupSubsectorLights(GLPASS_LIGHTSONLY, node->sub); + node = node->next; + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== + +void GLFlat::DrawSubsectors(int pass, bool processlights, bool istrans) +{ + int dli = dynlightindex; + + gl_RenderState.Apply(); + if (vboindex >= 0) + { + int index = vboindex; + for (int i=0; isubsectorcount; i++) + { + subsector_t * sub = sector->subsectors[i]; + + if (gl_drawinfo->ss_renderflags[sub-subsectors]&renderflags || istrans) + { + if (processlights) SetupSubsectorLights(GLPASS_ALL, sub, &dli); + drawcalls.Clock(); + glDrawArrays(GL_TRIANGLE_FAN, index, sub->numlines); + drawcalls.Unclock(); + flatvertices += sub->numlines; + flatprimitives++; + } + index += sub->numlines; + } + } + else + { + // Draw the subsectors belonging to this sector + // (can this case even happen?) + for (int i=0; isubsectorcount; i++) + { + subsector_t * sub = sector->subsectors[i]; + if (gl_drawinfo->ss_renderflags[sub-subsectors]&renderflags || istrans) + { + if (processlights) SetupSubsectorLights(GLPASS_ALL, sub, &dli); + DrawSubsector(sub); + } + } + } + + // Draw the subsectors assigned to it due to missing textures + if (!(renderflags&SSRF_RENDER3DPLANES)) + { + gl_subsectorrendernode * node = (renderflags&SSRF_RENDERFLOOR)? + gl_drawinfo->GetOtherFloorPlanes(sector->sectornum) : + gl_drawinfo->GetOtherCeilingPlanes(sector->sectornum); + + while (node) + { + if (processlights) SetupSubsectorLights(GLPASS_ALL, node->sub, &dli); + DrawSubsector(node->sub); + node = node->next; + } + } +} + + +//========================================================================== +// +// special handling for skyboxes which need texture clamping. +// This will find the bounding rectangle of the sector and just +// draw one single polygon filling that rectangle with a clamped +// texture. +// +//========================================================================== + +void GLFlat::DrawSkyboxSector(int pass, bool processlights) +{ + + float minx = FLT_MAX, miny = FLT_MAX; + float maxx = -FLT_MAX, maxy = -FLT_MAX; + + for (int i = 0; i < sector->linecount; i++) + { + line_t *ln = sector->lines[i]; + float x = ln->v1->fX(); + float y = ln->v1->fY(); + if (x < minx) minx = x; + if (y < miny) miny = y; + if (x > maxx) maxx = x; + if (y > maxy) maxy = y; + x = ln->v2->fX(); + y = ln->v2->fY(); + if (x < minx) minx = x; + if (y < miny) miny = y; + if (x > maxx) maxx = x; + if (y > maxy) maxy = y; + } + + float z = plane.plane.ZatPoint(0., 0.) + dz; + static float uvals[] = { 0, 0, 1, 1 }; + static float vvals[] = { 1, 0, 0, 1 }; + int rot = -xs_FloorToInt(plane.Angle / 90.f); + + FQuadDrawer qd; + + qd.Set(0, minx, z, miny, uvals[rot & 3], vvals[rot & 3]); + qd.Set(1, minx, z, maxy, uvals[(rot + 1) & 3], vvals[(rot + 1) & 3]); + qd.Set(2, maxx, z, maxy, uvals[(rot + 2) & 3], vvals[(rot + 2) & 3]); + qd.Set(3, maxx, z, miny, uvals[(rot + 3) & 3], vvals[(rot + 3) & 3]); + qd.Render(GL_TRIANGLE_FAN); + + flatvertices += 4; + flatprimitives++; +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLFlat::Draw(int pass, bool trans) // trans only has meaning for GLPASS_LIGHTSONLY +{ + int rel = getExtraLight(); + +#ifdef _DEBUG + if (sector->sectornum == gl_breaksec) + { + int a = 0; + } +#endif + + gl_RenderState.SetNormal(plane.plane.Normal().X, plane.plane.Normal().Z, plane.plane.Normal().Y); + + switch (pass) + { + case GLPASS_PLAIN: // Single-pass rendering + case GLPASS_ALL: // Same, but also creates the dynlight data. + gl_SetColor(lightlevel, rel, Colormap,1.0f); + gl_SetFog(lightlevel, rel, &Colormap, false); + if (sector->special != GLSector_Skybox) + { + gl_RenderState.SetMaterial(gltexture, CLAMP_NONE, 0, -1, false); + gl_SetPlaneTextureRotation(&plane, gltexture); + DrawSubsectors(pass, (pass == GLPASS_ALL || dynlightindex > -1), false); + gl_RenderState.EnableTextureMatrix(false); + } + else + { + gl_RenderState.SetMaterial(gltexture, CLAMP_XY, 0, -1, false); + DrawSkyboxSector(pass, (pass == GLPASS_ALL || dynlightindex > -1)); + } + break; + + case GLPASS_LIGHTSONLY: + if (!trans || gltexture) + { + ProcessLights(trans); + } + break; + + case GLPASS_TRANSLUCENT: + if (renderstyle==STYLE_Add) gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE); + gl_SetColor(lightlevel, rel, Colormap, alpha); + gl_SetFog(lightlevel, rel, &Colormap, false); + if (!gltexture) + { + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.EnableTexture(false); + DrawSubsectors(pass, false, true); + gl_RenderState.EnableTexture(true); + } + else + { + if (!gltexture->GetTransparent()) gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_threshold); + else gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.SetMaterial(gltexture, CLAMP_NONE, 0, -1, false); + gl_SetPlaneTextureRotation(&plane, gltexture); + DrawSubsectors(pass, !gl.legacyMode, true); + gl_RenderState.EnableTextureMatrix(false); + } + if (renderstyle==STYLE_Add) gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + break; + + case GLPASS_LIGHTTEX: + case GLPASS_LIGHTTEX_ADDITIVE: + case GLPASS_LIGHTTEX_FOGGY: + DrawLightsCompat(pass); + break; + + case GLPASS_TEXONLY: + gl_RenderState.SetMaterial(gltexture, CLAMP_NONE, 0, -1, false); + gl_SetPlaneTextureRotation(&plane, gltexture); + DrawSubsectors(pass, false, false); + gl_RenderState.EnableTextureMatrix(false); + break; + } +} + + +//========================================================================== +// +// GLFlat::PutFlat +// +// Checks texture, lighting and translucency settings and puts this +// plane in the appropriate render list. +// +//========================================================================== +inline void GLFlat::PutFlat(bool fog) +{ + int list; + + if (gl_fixedcolormap) + { + Colormap.Clear(); + } + if (gl.legacyMode) + { + if (PutFlatCompat(fog)) return; + } + if (renderstyle!=STYLE_Translucent || alpha < 1.f - FLT_EPSILON || fog || gltexture == NULL) + { + // translucent 3D floors go into the regular translucent list, translucent portals go into the translucent border list. + list = (renderflags&SSRF_RENDER3DPLANES) ? GLDL_TRANSLUCENT : GLDL_TRANSLUCENTBORDER; + } + else if (gltexture->GetTransparent()) + { + if (stack) + { + list = GLDL_TRANSLUCENTBORDER; + } + else if ((renderflags&SSRF_RENDER3DPLANES) && !plane.plane.isSlope()) + { + list = GLDL_TRANSLUCENT; + } + else + { + list = GLDL_PLAINFLATS; + } + } + else + { + bool masked = gltexture->isMasked() && ((renderflags&SSRF_RENDER3DPLANES) || stack); + list = masked ? GLDL_MASKEDFLATS : GLDL_PLAINFLATS; + } + dynlightindex = -1; // make sure this is always initialized to something proper. + gl_drawinfo->drawlists[list].AddFlat (this); +} + +//========================================================================== +// +// This draws one flat +// The passed sector does not indicate the area which is rendered. +// It is only used as source for the plane data. +// The whichplane boolean indicates if the flat is a floor(false) or a ceiling(true) +// +//========================================================================== + +void GLFlat::Process(sector_t * model, int whichplane, bool fog) +{ + plane.GetFromSector(model, whichplane); + if (whichplane != int(ceiling)) + { + // Flip the normal if the source plane has a different orientation than what we are about to render. + plane.plane.FlipVert(); + } + + if (!fog) + { + gltexture=FMaterial::ValidateTexture(plane.texture, false, true); + if (!gltexture) return; + if (gltexture->tex->isFullbright()) + { + Colormap.LightColor.r = Colormap.LightColor.g = Colormap.LightColor.b = 0xff; + lightlevel=255; + } + } + else + { + gltexture = NULL; + lightlevel = abs(lightlevel); + } + + // get height from vplane + if (whichplane == sector_t::floor && sector->transdoor) dz = -1; + else dz = 0; + + z = plane.plane.ZatPoint(0.f, 0.f); + + PutFlat(fog); + rendered_flats++; +} + +//========================================================================== +// +// Sets 3D floor info. Common code for all 4 cases +// +//========================================================================== + +void GLFlat::SetFrom3DFloor(F3DFloor *rover, bool top, bool underside) +{ + F3DFloor::planeref & plane = top? rover->top : rover->bottom; + + // FF_FOG requires an inverted logic where to get the light from + lightlist_t *light = P_GetPlaneLight(sector, plane.plane, underside); + lightlevel = gl_ClampLight(*light->p_lightlevel); + + if (rover->flags & FF_FOG) Colormap.LightColor = (light->extra_colormap)->Fade; + else Colormap.CopyFrom3DLight(light); + + + alpha = rover->alpha/255.0f; + renderstyle = rover->flags&FF_ADDITIVETRANS? STYLE_Add : STYLE_Translucent; + if (plane.model->VBOHeightcheck(plane.isceiling)) + { + vboindex = plane.vindex; + } + else + { + vboindex = -1; + } +} + +//========================================================================== +// +// Process a sector's flats for rendering +// This function is only called once per sector. +// Subsequent subsectors are just quickly added to the ss_renderflags array +// +//========================================================================== + +void GLFlat::ProcessSector(sector_t * frontsector) +{ + lightlist_t * light; + FSectorPortal *port; + +#ifdef _DEBUG + if (frontsector->sectornum == gl_breaksec) + { + int a = 0; + } +#endif + + // Get the real sector for this one. + sector = §ors[frontsector->sectornum]; + extsector_t::xfloor &x = sector->e->XFloor; + dynlightindex = -1; + + byte &srf = gl_drawinfo->sectorrenderflags[sector->sectornum]; + + // + // + // + // do floors + // + // + // + if (frontsector->floorplane.ZatPoint(ViewPos) <= ViewPos.Z) + { + // process the original floor first. + + srf |= SSRF_RENDERFLOOR; + + lightlevel = gl_ClampLight(frontsector->GetFloorLight()); + Colormap = frontsector->ColorMap; + port = frontsector->ValidatePortal(sector_t::floor); + if ((stack = (port != NULL))) + { + if (port->mType == PORTS_STACKEDSECTORTHING) + { + gl_drawinfo->AddFloorStack(sector); // stacked sector things require visplane merging. + } + alpha = frontsector->GetAlpha(sector_t::floor); + } + else + { + alpha = 1.0f - frontsector->GetReflect(sector_t::floor); + } + + if (alpha != 0.f && frontsector->GetTexture(sector_t::floor) != skyflatnum) + { + if (frontsector->VBOHeightcheck(sector_t::floor)) + { + vboindex = frontsector->vboindex[sector_t::floor]; + } + else + { + vboindex = -1; + } + + ceiling = false; + renderflags = SSRF_RENDERFLOOR; + + if (x.ffloors.Size()) + { + light = P_GetPlaneLight(sector, &frontsector->floorplane, false); + if ((!(sector->GetFlags(sector_t::floor)&PLANEF_ABSLIGHTING) || light->lightsource == NULL) + && (light->p_lightlevel != &frontsector->lightlevel)) + { + lightlevel = gl_ClampLight(*light->p_lightlevel); + } + + Colormap.CopyFrom3DLight(light); + } + renderstyle = STYLE_Translucent; + Process(frontsector, sector_t::floor, false); + } + } + + // + // + // + // do ceilings + // + // + // + if (frontsector->ceilingplane.ZatPoint(ViewPos) >= ViewPos.Z) + { + // process the original ceiling first. + + srf |= SSRF_RENDERCEILING; + + lightlevel = gl_ClampLight(frontsector->GetCeilingLight()); + Colormap = frontsector->ColorMap; + port = frontsector->ValidatePortal(sector_t::ceiling); + if ((stack = (port != NULL))) + { + if (port->mType == PORTS_STACKEDSECTORTHING) + { + gl_drawinfo->AddCeilingStack(sector); + } + alpha = frontsector->GetAlpha(sector_t::ceiling); + } + else + { + alpha = 1.0f - frontsector->GetReflect(sector_t::ceiling); + } + + if (alpha != 0.f && frontsector->GetTexture(sector_t::ceiling) != skyflatnum) + { + if (frontsector->VBOHeightcheck(sector_t::ceiling)) + { + vboindex = frontsector->vboindex[sector_t::ceiling]; + } + else + { + vboindex = -1; + } + + ceiling = true; + renderflags = SSRF_RENDERCEILING; + + if (x.ffloors.Size()) + { + light = P_GetPlaneLight(sector, §or->ceilingplane, true); + + if ((!(sector->GetFlags(sector_t::ceiling)&PLANEF_ABSLIGHTING)) + && (light->p_lightlevel != &frontsector->lightlevel)) + { + lightlevel = gl_ClampLight(*light->p_lightlevel); + } + Colormap.CopyFrom3DLight(light); + } + renderstyle = STYLE_Translucent; + Process(frontsector, sector_t::ceiling, false); + } + } + + // + // + // + // do 3D floors + // + // + // + + stack = false; + if (x.ffloors.Size()) + { + player_t * player = players[consoleplayer].camera->player; + + renderflags = SSRF_RENDER3DPLANES; + srf |= SSRF_RENDER3DPLANES; + // 3d-floors must not overlap! + double lastceilingheight = sector->CenterCeiling(); // render only in the range of the + double lastfloorheight = sector->CenterFloor(); // current sector part (if applicable) + F3DFloor * rover; + int k; + + // floors are ordered now top to bottom so scanning the list for the best match + // is no longer necessary. + + ceiling = true; + for (k = 0; k < (int)x.ffloors.Size(); k++) + { + rover = x.ffloors[k]; + + if ((rover->flags&(FF_EXISTS | FF_RENDERPLANES | FF_THISINSIDE)) == (FF_EXISTS | FF_RENDERPLANES)) + { + if (rover->flags&FF_FOG && gl_fixedcolormap) continue; + if (!rover->top.copied && rover->flags&(FF_INVERTPLANES | FF_BOTHPLANES)) + { + double ff_top = rover->top.plane->ZatPoint(sector->centerspot); + if (ff_top < lastceilingheight) + { + if (ViewPos.Z <= rover->top.plane->ZatPoint(ViewPos)) + { + SetFrom3DFloor(rover, true, !!(rover->flags&FF_FOG)); + Colormap.FadeColor = frontsector->ColorMap->Fade; + Process(rover->top.model, rover->top.isceiling, !!(rover->flags&FF_FOG)); + } + lastceilingheight = ff_top; + } + } + if (!rover->bottom.copied && !(rover->flags&FF_INVERTPLANES)) + { + double ff_bottom = rover->bottom.plane->ZatPoint(sector->centerspot); + if (ff_bottom < lastceilingheight) + { + if (ViewPos.Z <= rover->bottom.plane->ZatPoint(ViewPos)) + { + SetFrom3DFloor(rover, false, !(rover->flags&FF_FOG)); + Colormap.FadeColor = frontsector->ColorMap->Fade; + Process(rover->bottom.model, rover->bottom.isceiling, !!(rover->flags&FF_FOG)); + } + lastceilingheight = ff_bottom; + if (rover->alpha < 255) lastceilingheight += EQUAL_EPSILON; + } + } + } + } + + ceiling = false; + for (k = x.ffloors.Size() - 1; k >= 0; k--) + { + rover = x.ffloors[k]; + + if ((rover->flags&(FF_EXISTS | FF_RENDERPLANES | FF_THISINSIDE)) == (FF_EXISTS | FF_RENDERPLANES)) + { + if (rover->flags&FF_FOG && gl_fixedcolormap) continue; + if (!rover->bottom.copied && rover->flags&(FF_INVERTPLANES | FF_BOTHPLANES)) + { + double ff_bottom = rover->bottom.plane->ZatPoint(sector->centerspot); + if (ff_bottom > lastfloorheight || (rover->flags&FF_FIX)) + { + if (ViewPos.Z >= rover->bottom.plane->ZatPoint(ViewPos)) + { + SetFrom3DFloor(rover, false, !(rover->flags&FF_FOG)); + Colormap.FadeColor = frontsector->ColorMap->Fade; + + if (rover->flags&FF_FIX) + { + lightlevel = gl_ClampLight(rover->model->lightlevel); + Colormap = rover->GetColormap(); + } + + Process(rover->bottom.model, rover->bottom.isceiling, !!(rover->flags&FF_FOG)); + } + lastfloorheight = ff_bottom; + } + } + if (!rover->top.copied && !(rover->flags&FF_INVERTPLANES)) + { + double ff_top = rover->top.plane->ZatPoint(sector->centerspot); + if (ff_top > lastfloorheight) + { + if (ViewPos.Z >= rover->top.plane->ZatPoint(ViewPos)) + { + SetFrom3DFloor(rover, true, !!(rover->flags&FF_FOG)); + Colormap.FadeColor = frontsector->ColorMap->Fade; + Process(rover->top.model, rover->top.isceiling, !!(rover->flags&FF_FOG)); + } + lastfloorheight = ff_top; + if (rover->alpha < 255) lastfloorheight -= EQUAL_EPSILON; + } + } + } + } + } +} + diff --git a/src/gl/scene/gl_portal.cpp b/src/gl/scene/gl_portal.cpp new file mode 100644 index 000000000..02fd9b452 --- /dev/null +++ b/src/gl/scene/gl_portal.cpp @@ -0,0 +1,1258 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_portal.cpp +** Generalized portal maintenance classes for skyboxes, horizons etc. +** +*/ + +#include "gl/system/gl_system.h" +#include "p_local.h" +#include "vectors.h" +#include "c_dispatch.h" +#include "doomstat.h" +#include "a_sharedglobal.h" +#include "r_sky.h" +#include "portal.h" +#include "p_maputl.h" +#include "d_player.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_quaddrawer.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/scene/gl_clipper.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/stereo3d/scoped_color_mask.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/utility/gl_geometric.h" + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// General portal handling code +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +EXTERN_CVAR(Bool, gl_portals) +EXTERN_CVAR(Bool, gl_noquery) +EXTERN_CVAR(Int, r_mirror_recursions) + +extern bool r_showviewer; + +TArray GLPortal::portals; +TArray GLPortal::planestack; +int GLPortal::recursion; +int GLPortal::MirrorFlag; +int GLPortal::PlaneMirrorFlag; +int GLPortal::renderdepth; +int GLPortal::PlaneMirrorMode; +GLuint GLPortal::QueryObject; + +int GLPortal::instack[2]; +bool GLPortal::inskybox; + +UniqueList UniqueSkies; +UniqueList UniqueHorizons; +UniqueList UniquePlaneMirrors; +UniqueList UniqueLineToLines; + +void gl_RenderActorsInPortal(FGLLinePortal *glport); + +//========================================================================== +// +// +// +//========================================================================== + +void GLPortal::BeginScene() +{ + UniqueSkies.Clear(); + UniqueHorizons.Clear(); + UniquePlaneMirrors.Clear(); + UniqueLineToLines.Clear(); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLPortal::ClearScreen() +{ + bool multi = !!glIsEnabled(GL_MULTISAMPLE); + gl_MatrixStack.Push(gl_RenderState.mViewMatrix); + gl_MatrixStack.Push(gl_RenderState.mProjectionMatrix); + + gl_RenderState.mViewMatrix.loadIdentity(); + gl_RenderState.mProjectionMatrix.ortho(0, SCREENWIDTH, SCREENHEIGHT, 0, -1.0f, 1.0f); + gl_RenderState.ApplyMatrices(); + + glDisable(GL_MULTISAMPLE); + glDisable(GL_DEPTH_TEST); + + glDrawArrays(GL_TRIANGLE_STRIP, FFlatVertexBuffer::FULLSCREEN_INDEX, 4); + + glEnable(GL_DEPTH_TEST); + gl_MatrixStack.Pop(gl_RenderState.mProjectionMatrix); + gl_MatrixStack.Pop(gl_RenderState.mViewMatrix); + gl_RenderState.ApplyMatrices(); + if (multi) glEnable(GL_MULTISAMPLE); +} + +//----------------------------------------------------------------------------- +// +// DrawPortalStencil +// +//----------------------------------------------------------------------------- +void GLPortal::DrawPortalStencil() +{ + if (mPrimIndices.Size() == 0) + { + mPrimIndices.Resize(2 * lines.Size()); + + for (unsigned int i = 0; i < lines.Size(); i++) + { + if (gl.buffermethod != BM_DEFERRED) lines[i].MakeVertices(false); + mPrimIndices[i * 2] = lines[i].vertindex; + mPrimIndices[i * 2 + 1] = lines[i].vertcount; + } + } + gl_RenderState.Apply(); + for (unsigned int i = 0; i < mPrimIndices.Size(); i += 2) + { + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_FAN, mPrimIndices[i], mPrimIndices[i + 1]); + } + if (NeedCap() && lines.Size() > 1) + { + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_FAN, FFlatVertexBuffer::STENCILTOP_INDEX, 4); + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_FAN, FFlatVertexBuffer::STENCILBOTTOM_INDEX, 4); + } +} + + + + + + +//----------------------------------------------------------------------------- +// +// Start +// +//----------------------------------------------------------------------------- + +bool GLPortal::Start(bool usestencil, bool doquery) +{ + rendered_portals++; +// PortalAll.Clock(); + if (usestencil) + { + if (!gl_portals) + { +// PortalAll.Unclock(); + return false; + } + + // Create stencil + glStencilFunc(GL_EQUAL,recursion,~0); // create stencil + glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // increment stencil of valid pixels + { + ScopedColorMask colorMask(0, 0, 0, 0); // glColorMask(0,0,0,0); // don't write to the graphics buffer + gl_RenderState.SetEffect(EFF_STENCIL); + gl_RenderState.EnableTexture(false); + gl_RenderState.ResetColor(); + glDepthFunc(GL_LESS); + gl_RenderState.Apply(); + + if (NeedDepthBuffer()) + { + glDepthMask(false); // don't write to Z-buffer! + if (!NeedDepthBuffer()) doquery = false; // too much overhead and nothing to gain. + else if (gl_noquery) doquery = false; + + // If occlusion query is supported let's use it to avoid rendering portals that aren't visible + if (!QueryObject && doquery) glGenQueries(1, &QueryObject); + if (QueryObject) + { + glBeginQuery(GL_SAMPLES_PASSED, QueryObject); + } + else doquery = false; // some kind of error happened + + DrawPortalStencil(); + + glEndQuery(GL_SAMPLES_PASSED); + + // Clear Z-buffer + glStencilFunc(GL_EQUAL, recursion + 1, ~0); // draw sky into stencil + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // this stage doesn't modify the stencil + glDepthMask(true); // enable z-buffer again + glDepthRange(1, 1); + glDepthFunc(GL_ALWAYS); + DrawPortalStencil(); + + // set normal drawing mode + gl_RenderState.EnableTexture(true); + glDepthFunc(GL_LESS); + // glColorMask(1, 1, 1, 1); + gl_RenderState.SetEffect(EFF_NONE); + glDepthRange(0, 1); + + GLuint sampleCount; + + if (QueryObject) + { + glGetQueryObjectuiv(QueryObject, GL_QUERY_RESULT, &sampleCount); + + if (sampleCount == 0) // not visible + { + // restore default stencil op. + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + glStencilFunc(GL_EQUAL, recursion, ~0); // draw sky into stencil + PortalAll.Unclock(); + return false; + } + } + FDrawInfo::StartDrawInfo(); + } + else + { + // No z-buffer is needed therefore we can skip all the complicated stuff that is involved + // No occlusion queries will be done here. For these portals the overhead is far greater + // than the benefit. + // Note: We must draw the stencil with z-write enabled here because there is no second pass! + + glDepthMask(true); + DrawPortalStencil(); + glStencilFunc(GL_EQUAL, recursion + 1, ~0); // draw sky into stencil + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // this stage doesn't modify the stencil + gl_RenderState.EnableTexture(true); + // glColorMask(1,1,1,1); + gl_RenderState.SetEffect(EFF_NONE); + glDisable(GL_DEPTH_TEST); + glDepthMask(false); // don't write to Z-buffer! + } + } + recursion++; + + + } + else + { + if (NeedDepthBuffer()) + { + FDrawInfo::StartDrawInfo(); + } + else + { + glDepthMask(false); + glDisable(GL_DEPTH_TEST); + } + } + + // save viewpoint + savedViewPos = ViewPos; + savedAngle = ViewAngle; + savedviewactor=GLRenderer->mViewActor; + savedviewarea=in_area; + savedviewpath[0] = ViewPath[0]; + savedviewpath[1] = ViewPath[1]; + savedvisibility = camera ? camera->renderflags & RF_INVISIBLE : ActorRenderFlags::FromInt(0); + + + PrevPortal = GLRenderer->mCurrentPortal; + PrevClipPortal = GLRenderer->mClipPortal; + GLRenderer->mClipPortal = NULL; // Portals which need this have to set it themselves + GLRenderer->mCurrentPortal = this; + + if (PrevPortal != NULL) PrevPortal->PushState(); +// PortalAll.Unclock(); + return true; +} + + +inline void GLPortal::ClearClipper() +{ + DAngle angleOffset = deltaangle(savedAngle, ViewAngle); + + clipper.Clear(); + + static int call=0; + + // Set the clipper to the minimal visible area + clipper.SafeAddClipRange(0,0xffffffff); + for (unsigned int i = 0; i < lines.Size(); i++) + { + DAngle startAngle = (DVector2(lines[i].glseg.x2, lines[i].glseg.y2) - savedViewPos).Angle() + angleOffset; + DAngle endAngle = (DVector2(lines[i].glseg.x1, lines[i].glseg.y1) - savedViewPos).Angle() + angleOffset; + + if (deltaangle(endAngle, startAngle) < 0) + { + clipper.SafeRemoveClipRangeRealAngles(startAngle.BAMs(), endAngle.BAMs()); + } + } + + // and finally clip it to the visible area + angle_t a1 = GLRenderer->FrustumAngle(); + if (a1 < ANGLE_180) clipper.SafeAddClipRangeRealAngles(ViewAngle.BAMs() + a1, ViewAngle.BAMs() - a1); + + // lock the parts that have just been clipped out. + clipper.SetSilhouette(); +} + +//----------------------------------------------------------------------------- +// +// End +// +//----------------------------------------------------------------------------- +void GLPortal::End(bool usestencil) +{ + bool needdepth = NeedDepthBuffer(); + + PortalAll.Clock(); + if (PrevPortal != NULL) PrevPortal->PopState(); + GLRenderer->mCurrentPortal = PrevPortal; + GLRenderer->mClipPortal = PrevClipPortal; + + if (usestencil) + { + if (needdepth) FDrawInfo::EndDrawInfo(); + + // Restore the old view + ViewPath[0] = savedviewpath[0]; + ViewPath[1] = savedviewpath[1]; + ViewPos = savedViewPos; + ViewAngle = savedAngle; + GLRenderer->mViewActor=savedviewactor; + in_area=savedviewarea; + if (camera != nullptr) camera->renderflags = (camera->renderflags & ~RF_INVISIBLE) | savedvisibility; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag & 1), !!(PlaneMirrorFlag & 1)); + + { + ScopedColorMask colorMask(0, 0, 0, 0); // glColorMask(0, 0, 0, 0); // no graphics + gl_RenderState.SetEffect(EFF_NONE); + gl_RenderState.ResetColor(); + gl_RenderState.EnableTexture(false); + gl_RenderState.Apply(); + + if (needdepth) + { + // first step: reset the depth buffer to max. depth + glDepthRange(1, 1); // always + glDepthFunc(GL_ALWAYS); // write the farthest depth value + DrawPortalStencil(); + } + else + { + glEnable(GL_DEPTH_TEST); + } + + // second step: restore the depth buffer to the previous values and reset the stencil + glDepthFunc(GL_LEQUAL); + glDepthRange(0, 1); + glStencilOp(GL_KEEP, GL_KEEP, GL_DECR); + glStencilFunc(GL_EQUAL, recursion, ~0); // draw sky into stencil + DrawPortalStencil(); + glDepthFunc(GL_LESS); + + + gl_RenderState.EnableTexture(true); + gl_RenderState.SetEffect(EFF_NONE); + } // glColorMask(1, 1, 1, 1); + recursion--; + + // restore old stencil op. + glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP); + glStencilFunc(GL_EQUAL,recursion,~0); // draw sky into stencil + } + else + { + if (needdepth) + { + FDrawInfo::EndDrawInfo(); + glClear(GL_DEPTH_BUFFER_BIT); + } + else + { + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + } + // Restore the old view + ViewPos = savedViewPos; + ViewAngle = savedAngle; + GLRenderer->mViewActor=savedviewactor; + in_area=savedviewarea; + if (camera != nullptr) camera->renderflags |= savedvisibility; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag&1), !!(PlaneMirrorFlag&1)); + + // This draws a valid z-buffer into the stencil's contents to ensure it + // doesn't get overwritten by the level's geometry. + + gl_RenderState.ResetColor(); + glDepthFunc(GL_LEQUAL); + glDepthRange(0, 1); + { + ScopedColorMask colorMask(0, 0, 0, 1); // mark portal in alpha channel but don't touch color + gl_RenderState.SetEffect(EFF_STENCIL); + gl_RenderState.EnableTexture(false); + gl_RenderState.BlendFunc(GL_ONE, GL_ZERO); + gl_RenderState.BlendEquation(GL_FUNC_ADD); + gl_RenderState.Apply(); + DrawPortalStencil(); + gl_RenderState.SetEffect(EFF_NONE); + gl_RenderState.EnableTexture(true); + } + glDepthFunc(GL_LESS); + } + PortalAll.Unclock(); +} + + +//----------------------------------------------------------------------------- +// +// StartFrame +// +//----------------------------------------------------------------------------- +void GLPortal::StartFrame() +{ + GLPortal * p=NULL; + portals.Push(p); + if (renderdepth==0) + { + inskybox=false; + instack[sector_t::floor]=instack[sector_t::ceiling]=0; + } + renderdepth++; +} + + +//----------------------------------------------------------------------------- +// +// Portal info +// +//----------------------------------------------------------------------------- + +static bool gl_portalinfo; + +CCMD(gl_portalinfo) +{ + gl_portalinfo = true; +} + +FString indent; + +//----------------------------------------------------------------------------- +// +// EndFrame +// +//----------------------------------------------------------------------------- + +void GLPortal::EndFrame() +{ + GLPortal * p; + + if (gl_portalinfo) + { + Printf("%s%d portals, depth = %d\n%s{\n", indent.GetChars(), portals.Size(), renderdepth, indent.GetChars()); + indent += " "; + } + + // Only use occlusion query if there are more than 2 portals. + // Otherwise there's too much overhead. + // (And don't forget to consider the separating NULL pointers!) + bool usequery = portals.Size() > 2 + (unsigned)renderdepth; + + while (portals.Pop(p) && p) + { + if (gl_portalinfo) + { + Printf("%sProcessing %s, depth = %d, query = %d\n", indent.GetChars(), p->GetName(), renderdepth, usequery); + } + if (p->lines.Size() > 0) + { + p->RenderPortal(true, usequery); + } + delete p; + } + renderdepth--; + + if (gl_portalinfo) + { + indent.Truncate(long(indent.Len()-2)); + Printf("%s}\n", indent.GetChars()); + if (portals.Size() == 0) gl_portalinfo = false; + } +} + + +//----------------------------------------------------------------------------- +// +// Renders one sky portal without a stencil. +// In more complex scenes using a stencil for skies can severely stall +// the GPU and there's rarely more than one sky visible at a time. +// +//----------------------------------------------------------------------------- +bool GLPortal::RenderFirstSkyPortal(int recursion) +{ + GLPortal * p; + GLPortal * best = NULL; + unsigned bestindex=0; + + // Find the one with the highest amount of lines. + // Normally this is also the one that saves the largest amount + // of time by drawing it before the scene itself. + for(int i = portals.Size()-1; i >= 0 && portals[i] != NULL; --i) + { + p=portals[i]; + if (p->lines.Size() > 0 && p->IsSky()) + { + // Cannot clear the depth buffer inside a portal recursion + if (recursion && p->NeedDepthBuffer()) continue; + + if (!best || p->lines.Size()>best->lines.Size()) + { + best=p; + bestindex=i; + } + } + } + + if (best) + { + portals.Delete(bestindex); + best->RenderPortal(false, false); + delete best; + return true; + } + return false; +} + + +//----------------------------------------------------------------------------- +// +// FindPortal +// +//----------------------------------------------------------------------------- + +GLPortal * GLPortal::FindPortal(const void * src) +{ + int i=portals.Size()-1; + + while (i>=0 && portals[i] && portals[i]->GetSource()!=src) i--; + return i>=0? portals[i]:NULL; +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void GLPortal::SaveMapSection() +{ + savedmapsection.Resize(currentmapsection.Size()); + memcpy(&savedmapsection[0], ¤tmapsection[0], currentmapsection.Size()); + memset(¤tmapsection[0], 0, currentmapsection.Size()); +} + +void GLPortal::RestoreMapSection() +{ + memcpy(¤tmapsection[0], &savedmapsection[0], currentmapsection.Size()); +} + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Skybox Portal +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// +// GLSkyboxPortal::DrawContents +// +//----------------------------------------------------------------------------- +static int skyboxrecursion=0; +void GLSkyboxPortal::DrawContents() +{ + int old_pm = PlaneMirrorMode; + int saved_extralight = extralight; + + if (skyboxrecursion >= 3) + { + ClearScreen(); + return; + } + + skyboxrecursion++; + AActor *origin = portal->mSkybox; + portal->mFlags |= PORTSF_INSKYBOX; + extralight = 0; + + PlaneMirrorMode = 0; + + bool oldclamp = gl_RenderState.SetDepthClamp(false); + ViewPos = origin->InterpolatedPosition(r_TicFracF); + ViewAngle += (origin->PrevAngles.Yaw + deltaangle(origin->PrevAngles.Yaw, origin->Angles.Yaw) * r_TicFracF); + + // Don't let the viewpoint be too close to a floor or ceiling + double floorh = origin->Sector->floorplane.ZatPoint(origin->Pos()); + double ceilh = origin->Sector->ceilingplane.ZatPoint(origin->Pos()); + if (ViewPos.Z < floorh + 4) ViewPos.Z = floorh + 4; + if (ViewPos.Z > ceilh - 4) ViewPos.Z = ceilh - 4; + + GLRenderer->mViewActor = origin; + + inskybox = true; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag & 1), !!(PlaneMirrorFlag & 1)); + GLRenderer->SetViewArea(); + ClearClipper(); + + int mapsection = R_PointInSubsector(ViewPos)->mapsection; + + SaveMapSection(); + currentmapsection[mapsection >> 3] |= 1 << (mapsection & 7); + + GLRenderer->DrawScene(DM_PORTAL); + portal->mFlags &= ~PORTSF_INSKYBOX; + inskybox = false; + gl_RenderState.SetDepthClamp(oldclamp); + skyboxrecursion--; + + PlaneMirrorMode = old_pm; + extralight = saved_extralight; + + RestoreMapSection(); +} + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Sector stack Portal +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +GLSectorStackPortal::~GLSectorStackPortal() +{ + if (origin != NULL && origin->glportal == this) + { + origin->glportal = NULL; + } +} + +//----------------------------------------------------------------------------- +// +// GLSectorStackPortal::SetupCoverage +// +//----------------------------------------------------------------------------- + +static BYTE SetCoverage(void *node) +{ + if (numnodes == 0) + { + return 0; + } + if (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + BYTE coverage = SetCoverage(bsp->children[0]) | SetCoverage(bsp->children[1]); + gl_drawinfo->no_renderflags[bsp-nodes] = coverage; + return coverage; + } + else + { + subsector_t *sub = (subsector_t *)((BYTE *)node - 1); + return gl_drawinfo->ss_renderflags[sub-subsectors] & SSRF_SEEN; + } +} + +void GLSectorStackPortal::SetupCoverage() +{ + for(unsigned i=0; iplane; + for(int j=0;jportalcoverage[plane].sscount; j++) + { + subsector_t *dsub = &::subsectors[sub->portalcoverage[plane].subsectors[j]]; + currentmapsection[dsub->mapsection>>3] |= 1 << (dsub->mapsection&7); + gl_drawinfo->ss_renderflags[dsub-::subsectors] |= SSRF_SEEN; + } + } + SetCoverage(&nodes[numnodes-1]); +} + +//----------------------------------------------------------------------------- +// +// GLSectorStackPortal::DrawContents +// +//----------------------------------------------------------------------------- +void GLSectorStackPortal::DrawContents() +{ + FPortal *portal = origin; + + ViewPos += origin->mDisplacement; + GLRenderer->mViewActor = NULL; + + // avoid recursions! + if (origin->plane != -1) instack[origin->plane]++; + + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag&1), !!(PlaneMirrorFlag&1)); + SaveMapSection(); + SetupCoverage(); + ClearClipper(); + + // If the viewpoint is not within the portal, we need to invalidate the entire clip area. + // The portal will re-validate the necessary parts when its subsectors get traversed. + subsector_t *sub = R_PointInSubsector(ViewPos); + if (!(gl_drawinfo->ss_renderflags[sub - ::subsectors] & SSRF_SEEN)) + { + clipper.SafeAddClipRange(0, ANGLE_MAX); + clipper.SetBlocked(true); + } + + GLRenderer->DrawScene(DM_PORTAL); + RestoreMapSection(); + + if (origin->plane != -1) instack[origin->plane]--; +} + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Plane Mirror Portal +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// +// GLPlaneMirrorPortal::DrawContents +// +//----------------------------------------------------------------------------- + +void GLPlaneMirrorPortal::DrawContents() +{ + if (renderdepth>r_mirror_recursions) + { + ClearScreen(); + return; + } + + int old_pm=PlaneMirrorMode; + + double planez = origin->ZatPoint(ViewPos); + ViewPos.Z = 2 * planez - ViewPos.Z; + GLRenderer->mViewActor = NULL; + PlaneMirrorMode = origin->fC() < 0 ? -1 : 1; + + PlaneMirrorFlag++; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag&1), !!(PlaneMirrorFlag&1)); + ClearClipper(); + + gl_RenderState.SetClipHeight(planez, PlaneMirrorMode < 0? -1.f : 1.f); + GLRenderer->DrawScene(DM_PORTAL); + gl_RenderState.SetClipHeight(0.f, 0.f); + PlaneMirrorFlag--; + PlaneMirrorMode=old_pm; +} + +void GLPlaneMirrorPortal::PushState() +{ + planestack.Push(gl_RenderState.GetClipHeight()); + planestack.Push(gl_RenderState.GetClipHeightDirection()); + gl_RenderState.SetClipHeight(0.f, 0.f); +} + +void GLPlaneMirrorPortal::PopState() +{ + float d, f; + planestack.Pop(d); + planestack.Pop(f); + gl_RenderState.SetClipHeight(f, d); +} + +//----------------------------------------------------------------------------- +// +// Common code for line to line and mirror portals +// +//----------------------------------------------------------------------------- + +void GLLinePortal::PushState() +{ + FStateVec4 &v = gl_RenderState.GetClipLine(); + planestack.Push(v.vec[0]); + planestack.Push(v.vec[1]); + planestack.Push(v.vec[2]); + planestack.Push(v.vec[3]); + planestack.Push(gl_RenderState.GetClipLineState()); + gl_RenderState.EnableClipLine(false); +} + +void GLLinePortal::PopState() +{ + FStateVec4 &v = gl_RenderState.GetClipLine(); + float e; + planestack.Pop(e); + planestack.Pop(v.vec[3]); + planestack.Pop(v.vec[2]); + planestack.Pop(v.vec[1]); + planestack.Pop(v.vec[0]); + gl_RenderState.EnableClipLine(e != 0); +} + +int GLLinePortal::ClipSeg(seg_t *seg) +{ + line_t *linedef = seg->linedef; + if (!linedef) + { + return PClip_Inside; // should be handled properly. + } + return P_ClipLineToPortal(linedef, line(), ViewPos) ? PClip_InFront : PClip_Inside; +} + +int GLLinePortal::ClipSubsector(subsector_t *sub) +{ + // this seg is completely behind the mirror! + for(unsigned int i=0;inumlines;i++) + { + if (P_PointOnLineSidePrecise(sub->firstline[i].v1->fPos(), line()) == 0) return PClip_Inside; + } + return PClip_InFront; +} + +int GLLinePortal::ClipPoint(const DVector2 &pos) +{ + if (P_PointOnLineSidePrecise(pos, line())) + { + return PClip_InFront; + } + return PClip_Inside; +} + + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Mirror Portal +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// +// R_EnterMirror +// +//----------------------------------------------------------------------------- +void GLMirrorPortal::DrawContents() +{ + if (renderdepth>r_mirror_recursions) + { + ClearScreen(); + return; + } + + GLRenderer->mClipPortal = this; + DAngle StartAngle = ViewAngle; + DVector3 StartPos = ViewPos; + + vertex_t *v1 = linedef->v1; + vertex_t *v2 = linedef->v2; + + // Reflect the current view behind the mirror. + if (linedef->Delta().X == 0) + { + // vertical mirror + ViewPos.X = 2 * v1->fX() - StartPos.X; + + // Compensation for reendering inaccuracies + if (StartPos.X < v1->fX()) ViewPos.X -= 0.1; + else ViewPos.X += 0.1; + } + else if (linedef->Delta().Y == 0) + { + // horizontal mirror + ViewPos.Y = 2*v1->fY() - StartPos.Y; + + // Compensation for reendering inaccuracies + if (StartPos.YfY()) ViewPos.Y -= 0.1; + else ViewPos.Y += 0.1; + } + else + { + // any mirror--use floats to avoid integer overflow. + // Use doubles to avoid losing precision which is very important here. + + double dx = v2->fX() - v1->fX(); + double dy = v2->fY() - v1->fY(); + double x1 = v1->fX(); + double y1 = v1->fY(); + double x = StartPos.X; + double y = StartPos.Y; + + // the above two cases catch len == 0 + double r = ((x - x1)*dx + (y - y1)*dy) / (dx*dx + dy*dy); + + ViewPos.X = (x1 + r * dx)*2 - x; + ViewPos.Y = (y1 + r * dy)*2 - y; + + // Compensation for reendering inaccuracies + FVector2 v(-dx, dy); + v.MakeUnit(); + + ViewPos.X+= v[1] * renderdepth / 2; + ViewPos.Y+= v[0] * renderdepth / 2; + } + ViewAngle = linedef->Delta().Angle() * 2. - StartAngle; + + GLRenderer->mViewActor = NULL; + + MirrorFlag++; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag&1), !!(PlaneMirrorFlag&1)); + + clipper.Clear(); + + angle_t af = GLRenderer->FrustumAngle(); + if (afv1->GetClipAngle(); + angle_t a1 = linedef->v2->GetClipAngle(); + clipper.SafeAddClipRange(a1,a2); + + gl_RenderState.SetClipLine(linedef); + gl_RenderState.EnableClipLine(true); + GLRenderer->DrawScene(DM_PORTAL); + gl_RenderState.EnableClipLine(false); + + MirrorFlag--; +} + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Line to line Portal +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- +void GLLineToLinePortal::DrawContents() +{ + // TODO: Handle recursion more intelligently + if (renderdepth>r_mirror_recursions) + { + ClearScreen(); + return; + } + + GLRenderer->mClipPortal = this; + + line_t *origin = glport->lines[0]->mOrigin; + P_TranslatePortalXY(origin, ViewPos.X, ViewPos.Y); + P_TranslatePortalAngle(origin, ViewAngle); + P_TranslatePortalZ(origin, ViewPos.Z); + P_TranslatePortalXY(origin, ViewPath[0].X, ViewPath[0].Y); + P_TranslatePortalXY(origin, ViewPath[1].X, ViewPath[1].Y); + if (!r_showviewer && camera != nullptr && P_PointOnLineSidePrecise(ViewPath[0], glport->lines[0]->mDestination) != P_PointOnLineSidePrecise(ViewPath[1], glport->lines[0]->mDestination)) + { + double distp = (ViewPath[0] - ViewPath[1]).Length(); + if (distp > EQUAL_EPSILON) + { + double dist1 = (ViewPos - ViewPath[0]).Length(); + double dist2 = (ViewPos - ViewPath[1]).Length(); + + if (dist1 + dist2 < distp + 1) + { + camera->renderflags |= RF_INVISIBLE; + } + } + } + + + SaveMapSection(); + + for (unsigned i = 0; i < lines.Size(); i++) + { + line_t *line = lines[i].seg->linedef->getPortalDestination(); + subsector_t *sub; + if (line->sidedef[0]->Flags & WALLF_POLYOBJ) + sub = R_PointInSubsector(line->v1->fixX(), line->v1->fixY()); + else sub = line->frontsector->subsectors[0]; + int mapsection = sub->mapsection; + currentmapsection[mapsection >> 3] |= 1 << (mapsection & 7); + } + + GLRenderer->mViewActor = nullptr; + GLRenderer->SetupView(ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle, !!(MirrorFlag&1), !!(PlaneMirrorFlag&1)); + + ClearClipper(); + gl_RenderState.SetClipLine(glport->lines[0]->mDestination); + gl_RenderState.EnableClipLine(true); + GLRenderer->DrawScene(DM_PORTAL); + gl_RenderState.EnableClipLine(false); + RestoreMapSection(); +} + +void GLLineToLinePortal::RenderAttached() +{ + gl_RenderActorsInPortal(glport); +} + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Horizon Portal +// +// This simply draws the area in medium sized squares. Drawing it as a whole +// polygon creates visible inaccuracies. +// +// Originally I tried to minimize the amount of data to be drawn but there +// are 2 problems with it: +// +// 1. Setting this up completely negates any performance gains. +// 2. It doesn't work with a 360° field of view (as when you are looking up.) +// +// +// So the brute force mechanism is just as good. +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +GLHorizonPortal::GLHorizonPortal(GLHorizonInfo * pt, bool local) + : GLPortal(local) +{ + origin = pt; + + // create the vertex data for this horizon portal. + GLSectorPlane * sp = &origin->plane; + const float vx = ViewPos.X; + const float vy = ViewPos.Y; + const float vz = ViewPos.Z; + const float z = sp->Texheight; + const float tz = (z - vz); + + // Draw to some far away boundary + // This is not drawn as larger strips because it causes visual glitches. + FFlatVertex *ptr = GLRenderer->mVBO->GetBuffer(); + for (float x = -32768 + vx; x<32768 + vx; x += 4096) + { + for (float y = -32768 + vy; y<32768 + vy; y += 4096) + { + ptr->Set(x, z, y, x / 64, -y / 64); + ptr++; + ptr->Set(x + 4096, z, y, x / 64 + 64, -y / 64); + ptr++; + ptr->Set(x, z, y + 4096, x / 64, -y / 64 - 64); + ptr++; + ptr->Set(x + 4096, z, y + 4096, x / 64 + 64, -y / 64 - 64); + ptr++; + } + } + + // fill the gap between the polygon and the true horizon + // Since I can't draw into infinity there can always be a + // small gap + ptr->Set(-32768 + vx, z, -32768 + vy, 512.f, 0); + ptr++; + ptr->Set(-32768 + vx, vz, -32768 + vy, 512.f, tz); + ptr++; + ptr->Set(-32768 + vx, z, 32768 + vy, -512.f, 0); + ptr++; + ptr->Set(-32768 + vx, vz, 32768 + vy, -512.f, tz); + ptr++; + ptr->Set(32768 + vx, z, 32768 + vy, 512.f, 0); + ptr++; + ptr->Set(32768 + vx, vz, 32768 + vy, 512.f, tz); + ptr++; + ptr->Set(32768 + vx, z, -32768 + vy, -512.f, 0); + ptr++; + ptr->Set(32768 + vx, vz, -32768 + vy, -512.f, tz); + ptr++; + ptr->Set(-32768 + vx, z, -32768 + vy, 512.f, 0); + ptr++; + ptr->Set(-32768 + vx, vz, -32768 + vy, 512.f, tz); + ptr++; + + vcount = GLRenderer->mVBO->GetCount(ptr, &voffset) - 10; + +} + +//----------------------------------------------------------------------------- +// +// GLHorizonPortal::DrawContents +// +//----------------------------------------------------------------------------- +void GLHorizonPortal::DrawContents() +{ + PortalAll.Clock(); + + FMaterial * gltexture; + PalEntry color; + player_t * player=&players[consoleplayer]; + GLSectorPlane * sp = &origin->plane; + + gltexture=FMaterial::ValidateTexture(sp->texture, false, true); + if (!gltexture) + { + ClearScreen(); + PortalAll.Unclock(); + return; + } + gl_RenderState.SetCameraPos(ViewPos.X, ViewPos.Y, ViewPos.Z); + + + if (gltexture && gltexture->tex->isFullbright()) + { + // glowing textures are always drawn full bright without color + gl_SetColor(255, 0, origin->colormap, 1.f); + gl_SetFog(255, 0, &origin->colormap, false); + } + else + { + int rel = getExtraLight(); + gl_SetColor(origin->lightlevel, rel, origin->colormap, 1.0f); + gl_SetFog(origin->lightlevel, rel, &origin->colormap, false); + } + + + gl_RenderState.SetMaterial(gltexture, CLAMP_NONE, 0, -1, false); + + gl_SetPlaneTextureRotation(sp, gltexture); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.BlendFunc(GL_ONE,GL_ZERO); + gl_RenderState.Apply(); + + + for (unsigned i = 0; i < vcount; i += 4) + { + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_STRIP, voffset + i, 4); + } + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_STRIP, voffset + vcount, 10); + + gl_RenderState.EnableTextureMatrix(false); + PortalAll.Unclock(); + +} + + +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// +// +// Eternity-style horizon portal +// +// To the rest of the engine these masquerade as a skybox portal +// Internally they need to draw two horizon or sky portals +// and will use the respective classes to achieve that. +// +// +//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void GLEEHorizonPortal::DrawContents() +{ + PortalAll.Clock(); + sector_t *sector = portal->mOrigin; + if (sector->GetTexture(sector_t::floor) == skyflatnum || + sector->GetTexture(sector_t::ceiling) == skyflatnum) + { + GLSkyInfo skyinfo; + skyinfo.init(sector->sky, 0); + GLSkyPortal sky(&skyinfo, true); + sky.DrawContents(); + } + if (sector->GetTexture(sector_t::ceiling) != skyflatnum) + { + GLHorizonInfo horz; + horz.plane.GetFromSector(sector, sector_t::ceiling); + horz.lightlevel = gl_ClampLight(sector->GetCeilingLight()); + horz.colormap = sector->ColorMap; + if (portal->mType == PORTS_PLANE) + { + horz.plane.Texheight = ViewPos.Z + fabs(horz.plane.Texheight); + } + GLHorizonPortal ceil(&horz, true); + ceil.DrawContents(); + } + if (sector->GetTexture(sector_t::floor) != skyflatnum) + { + GLHorizonInfo horz; + horz.plane.GetFromSector(sector, sector_t::floor); + horz.lightlevel = gl_ClampLight(sector->GetFloorLight()); + horz.colormap = sector->ColorMap; + if (portal->mType == PORTS_PLANE) + { + horz.plane.Texheight = ViewPos.Z - fabs(horz.plane.Texheight); + } + GLHorizonPortal floor(&horz, true); + floor.DrawContents(); + } + + + +} + +const char *GLSkyPortal::GetName() { return "Sky"; } +const char *GLSkyboxPortal::GetName() { return "Skybox"; } +const char *GLSectorStackPortal::GetName() { return "Sectorstack"; } +const char *GLPlaneMirrorPortal::GetName() { return "Planemirror"; } +const char *GLMirrorPortal::GetName() { return "Mirror"; } +const char *GLLineToLinePortal::GetName() { return "LineToLine"; } +const char *GLHorizonPortal::GetName() { return "Horizon"; } +const char *GLEEHorizonPortal::GetName() { return "EEHorizon"; } + diff --git a/src/gl/scene/gl_portal.h b/src/gl/scene/gl_portal.h new file mode 100644 index 000000000..fbd3a0c7f --- /dev/null +++ b/src/gl/scene/gl_portal.h @@ -0,0 +1,404 @@ +/* +** gl_renderstruct.h +** Generalized portal maintenance classes to make rendering special effects easier +** and help add future extensions +** +**--------------------------------------------------------------------------- +** Copyright 2002-2005 Christoph Oelckers +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#ifndef __GL_PORTAL_H +#define __GL_PORTAL_H + +#include "tarray.h" +//#include "gl/gl_intern.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/utility/gl_templates.h" +#include "gl/data/gl_data.h" + +class ASkyViewpoint; + + +struct GLHorizonInfo +{ + GLSectorPlane plane; + int lightlevel; + FColormap colormap; +}; + +struct GLSkyInfo +{ + float x_offset[2]; + float y_offset; // doubleskies don't have a y-offset + FMaterial * texture[2]; + FTextureID skytexno1; + bool mirrored; + bool doublesky; + bool sky2; + PalEntry fadecolor; // if this isn't made part of the dome things will become more complicated when sky fog is used. + + bool operator==(const GLSkyInfo & inf) + { + return !memcmp(this, &inf, sizeof(*this)); + } + bool operator!=(const GLSkyInfo & inf) + { + return !!memcmp(this, &inf, sizeof(*this)); + } + void init(int sky1, PalEntry fadecolor); +}; + +extern UniqueList UniqueSkies; +extern UniqueList UniqueHorizons; +extern UniqueList UniquePlaneMirrors; +extern UniqueList UniqueLineToLines; +struct GLEEHorizonPortal; + +class GLPortal +{ + static TArray portals; + static int recursion; + static unsigned int QueryObject; +protected: + static TArray planestack; + static int MirrorFlag; + static int PlaneMirrorFlag; + static int renderdepth; + +public: + static int PlaneMirrorMode; + static int inupperstack; + static int instack[2]; + static bool inskybox; + +private: + void DrawPortalStencil(); + + DVector3 savedViewPos; + DAngle savedAngle; + AActor * savedviewactor; + area_t savedviewarea; + ActorRenderFlags savedvisibility; + DVector3 savedviewpath[2]; + GLPortal *PrevPortal; + GLPortal *PrevClipPortal; + TArray savedmapsection; + TArray mPrimIndices; + +protected: + TArray lines; + int level; + + GLPortal(bool local = false) { if (!local) portals.Push(this); } + virtual ~GLPortal() { } + + bool Start(bool usestencil, bool doquery); + void End(bool usestencil); + virtual void DrawContents()=0; + virtual void * GetSource() const =0; // GetSource MUST be implemented! + void ClearClipper(); + virtual bool IsSky() { return false; } + virtual bool NeedCap() { return true; } + virtual bool NeedDepthBuffer() { return true; } + void ClearScreen(); + virtual const char *GetName() = 0; + void SaveMapSection(); + void RestoreMapSection(); + virtual void PushState() {} + virtual void PopState() {} + +public: + + enum + { + PClip_InFront, + PClip_Inside, + PClip_Behind, + }; + + void RenderPortal(bool usestencil, bool doquery) + { + // Start may perform an occlusion query. If that returns 0 there + // is no need to draw the stencil's contents and there's also no + // need to restore the affected area becasue there is none! + if (Start(usestencil, doquery)) + { + DrawContents(); + End(usestencil); + } + } + + void AddLine(GLWall * l) + { + lines.Push(*l); + } + + static int GetRecursion() + { + return recursion; + } + + virtual int ClipSeg(seg_t *seg) { return PClip_Inside; } + virtual int ClipSubsector(subsector_t *sub) { return PClip_Inside; } + virtual int ClipPoint(const DVector2 &pos) { return PClip_Inside; } + virtual line_t *ClipLine() { return NULL; } + virtual void RenderAttached() {} + + static void BeginScene(); + static void StartFrame(); + static bool RenderFirstSkyPortal(int recursion); + static void EndFrame(); + static GLPortal * FindPortal(const void * src); +}; + +struct GLLinePortal : public GLPortal +{ + // this must be the same as at the start of line_t, so that we can pass in this structure directly to P_ClipLineToPortal. + vertex_t *v1, *v2; // vertices, from v1 to v2 + DVector2 delta; // precalculated v2 - v1 for side checking + + angle_t angv1, angv2; // for quick comparisons with a line or subsector + + GLLinePortal(line_t *line) + { + v1 = line->v1; + v2 = line->v2; + CalcDelta(); + } + + GLLinePortal(FGLLinePortal *line) + { + if (line->lines[0]->mType != PORTT_LINKED || line->v1 == nullptr) + { + // For non-linked portals we must check the actual linedef. + line_t *lline = line->lines[0]->mDestination; + v1 = lline->v1; + v2 = lline->v2; + } + else + { + // For linked portals we can check the merged span. + v1 = line->v1; + v2 = line->v2; + } + CalcDelta(); + } + + void CalcDelta() + { + delta = v2->fPos() - v1->fPos(); + } + + line_t *line() + { + vertex_t **pv = &v1; + return reinterpret_cast(pv); + } + + virtual int ClipSeg(seg_t *seg); + virtual int ClipSubsector(subsector_t *sub); + virtual int ClipPoint(const DVector2 &pos); + virtual bool NeedCap() { return false; } + virtual void PushState(); + virtual void PopState(); +}; + + +struct GLMirrorPortal : public GLLinePortal +{ + // mirror portals always consist of single linedefs! + line_t * linedef; + +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return linedef; } + virtual const char *GetName(); + +public: + + GLMirrorPortal(line_t * line) + : GLLinePortal(line) + { + linedef=line; + } +}; + + +struct GLLineToLinePortal : public GLLinePortal +{ + FGLLinePortal *glport; +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return glport; } + virtual const char *GetName(); + virtual line_t *ClipLine() { return line(); } + virtual void RenderAttached(); + +public: + + GLLineToLinePortal(FGLLinePortal *ll) + : GLLinePortal(ll) + { + glport = ll; + } +}; + + +struct GLSkyboxPortal : public GLPortal +{ + FSectorPortal * portal; + +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return portal; } + virtual bool IsSky() { return true; } + virtual const char *GetName(); + +public: + + + GLSkyboxPortal(FSectorPortal * pt) + { + portal=pt; + } + +}; + + +struct GLSkyPortal : public GLPortal +{ + GLSkyInfo * origin; + friend struct GLEEHorizonPortal; + +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return origin; } + virtual bool IsSky() { return true; } + virtual bool NeedDepthBuffer() { return false; } + virtual const char *GetName(); + +public: + + + GLSkyPortal(GLSkyInfo * pt, bool local = false) + : GLPortal(local) + { + origin=pt; + } + +}; + + + +struct GLSectorStackPortal : public GLPortal +{ + TArray subsectors; +protected: + virtual ~GLSectorStackPortal(); + virtual void DrawContents(); + virtual void * GetSource() const { return origin; } + virtual bool IsSky() { return true; } // although this isn't a real sky it can be handled as one. + virtual const char *GetName(); + FPortal *origin; + +public: + + GLSectorStackPortal(FPortal *pt) + { + origin=pt; + } + void SetupCoverage(); + void AddSubsector(subsector_t *sub) + { + subsectors.Push(sub); + } + +}; + +struct GLPlaneMirrorPortal : public GLPortal +{ +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return origin; } + virtual const char *GetName(); + virtual void PushState(); + virtual void PopState(); + secplane_t * origin; + +public: + + GLPlaneMirrorPortal(secplane_t * pt) + { + origin=pt; + } + +}; + + +struct GLHorizonPortal : public GLPortal +{ + GLHorizonInfo * origin; + unsigned int voffset; + unsigned int vcount; + friend struct GLEEHorizonPortal; + +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return origin; } + virtual bool NeedDepthBuffer() { return false; } + virtual bool NeedCap() { return false; } + virtual const char *GetName(); + +public: + + GLHorizonPortal(GLHorizonInfo * pt, bool local = false); +}; + +struct GLEEHorizonPortal : public GLPortal +{ + FSectorPortal * portal; + +protected: + virtual void DrawContents(); + virtual void * GetSource() const { return portal; } + virtual bool NeedDepthBuffer() { return false; } + virtual bool NeedCap() { return false; } + virtual const char *GetName(); + +public: + + GLEEHorizonPortal(FSectorPortal *pt) + { + portal=pt; + } + +}; + +#endif diff --git a/src/gl/scene/gl_renderhacks.cpp b/src/gl/scene/gl_renderhacks.cpp new file mode 100644 index 000000000..9242df2a9 --- /dev/null +++ b/src/gl/scene/gl_renderhacks.cpp @@ -0,0 +1,1215 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_renderhacks.cpp +** Handles missing upper and lower textures and self referencing sector hacks +** +*/ + +#include "a_sharedglobal.h" +#include "r_utility.h" +#include "r_defs.h" +#include "r_sky.h" +#include "g_level.h" + + +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" + + +// This is for debugging maps. + +FreeList SSR_List; + +// profiling data +static int totalupper, totallower; +static int lowershcount, uppershcount; +static glcycle_t totalms, showtotalms; +static glcycle_t totalssms; +static sector_t fakesec; + +void FDrawInfo::ClearBuffers() +{ + for(unsigned int i=0;i< otherfloorplanes.Size();i++) + { + gl_subsectorrendernode * node = otherfloorplanes[i]; + while (node) + { + gl_subsectorrendernode * n = node; + node = node->next; + SSR_List.Release(n); + } + } + otherfloorplanes.Clear(); + + for(unsigned int i=0;i< otherceilingplanes.Size();i++) + { + gl_subsectorrendernode * node = otherceilingplanes[i]; + while (node) + { + gl_subsectorrendernode * n = node; + node = node->next; + SSR_List.Release(n); + } + } + otherceilingplanes.Clear(); + + // clear all the lists that might not have been cleared already + MissingUpperTextures.Clear(); + MissingLowerTextures.Clear(); + MissingUpperSegs.Clear(); + MissingLowerSegs.Clear(); + SubsectorHacks.Clear(); + CeilingStacks.Clear(); + FloorStacks.Clear(); + HandledSubsectors.Clear(); + +} +//========================================================================== +// +// Adds a subsector plane to a sector's render list +// +//========================================================================== + +void FDrawInfo::AddOtherFloorPlane(int sector, gl_subsectorrendernode * node) +{ + int oldcnt = otherfloorplanes.Size(); + + if (oldcnt<=sector) + { + otherfloorplanes.Resize(sector+1); + for(int i=oldcnt;i<=sector;i++) otherfloorplanes[i]=NULL; + } + node->next = otherfloorplanes[sector]; + otherfloorplanes[sector] = node; +} + +void FDrawInfo::AddOtherCeilingPlane(int sector, gl_subsectorrendernode * node) +{ + int oldcnt = otherceilingplanes.Size(); + + if (oldcnt<=sector) + { + otherceilingplanes.Resize(sector+1); + for(int i=oldcnt;i<=sector;i++) otherceilingplanes[i]=NULL; + } + node->next = otherceilingplanes[sector]; + otherceilingplanes[sector] = node; +} + + +//========================================================================== +// +// Collects all sectors that might need a fake ceiling +// +//========================================================================== +void FDrawInfo::AddUpperMissingTexture(side_t * side, subsector_t *sub, float Backheight) +{ + if (!side->segs[0]->backsector) return; + + totalms.Clock(); + for (int i = 0; i < side->numsegs; i++) + { + seg_t *seg = side->segs[i]; + + // we need find the seg belonging to the passed subsector + if (seg->Subsector == sub) + { + MissingTextureInfo mti = {}; + MissingSegInfo msi; + + + if (sub->render_sector != sub->sector || seg->frontsector != sub->sector) + { + totalms.Unclock(); + return; + } + + for (unsigned int i = 0; i < MissingUpperTextures.Size(); i++) + { + if (MissingUpperTextures[i].sub == sub) + { + // Use the lowest adjoining height to draw a fake ceiling if necessary + if (Backheight < MissingUpperTextures[i].Planez) + { + MissingUpperTextures[i].Planez = Backheight; + MissingUpperTextures[i].seg = seg; + } + + msi.MTI_Index = i; + msi.seg = seg; + MissingUpperSegs.Push(msi); + totalms.Unclock(); + return; + } + } + mti.seg = seg; + mti.sub = sub; + mti.Planez = Backheight; + msi.MTI_Index = MissingUpperTextures.Push(mti); + msi.seg = seg; + MissingUpperSegs.Push(msi); + } + } + totalms.Unclock(); +} + +//========================================================================== +// +// Collects all sectors that might need a fake floor +// +//========================================================================== +void FDrawInfo::AddLowerMissingTexture(side_t * side, subsector_t *sub, float Backheight) +{ + sector_t *backsec = side->segs[0]->backsector; + if (!backsec) return; + if (backsec->transdoor) + { + // Transparent door hacks alter the backsector's floor height so we should not + // process the missing texture for them. + if (backsec->transdoorheight == backsec->GetPlaneTexZ(sector_t::floor)) return; + } + + totalms.Clock(); + // we need to check all segs of this sidedef + for (int i = 0; i < side->numsegs; i++) + { + seg_t *seg = side->segs[i]; + + // we need find the seg belonging to the passed subsector + if (seg->Subsector == sub) + { + MissingTextureInfo mti = {}; + MissingSegInfo msi; + + subsector_t * sub = seg->Subsector; + + if (sub->render_sector != sub->sector || seg->frontsector != sub->sector) + { + totalms.Unclock(); + return; + } + + // Ignore FF_FIX's because they are designed to abuse missing textures + if (seg->backsector->e->XFloor.ffloors.Size() && (seg->backsector->e->XFloor.ffloors[0]->flags&(FF_FIX | FF_SEETHROUGH)) == FF_FIX) + { + totalms.Unclock(); + return; + } + + for (unsigned int i = 0; i < MissingLowerTextures.Size(); i++) + { + if (MissingLowerTextures[i].sub == sub) + { + // Use the highest adjoining height to draw a fake floor if necessary + if (Backheight > MissingLowerTextures[i].Planez) + { + MissingLowerTextures[i].Planez = Backheight; + MissingLowerTextures[i].seg = seg; + } + + msi.MTI_Index = i; + msi.seg = seg; + MissingLowerSegs.Push(msi); + totalms.Unclock(); + return; + } + } + mti.seg = seg; + mti.sub = sub; + mti.Planez = Backheight; + msi.MTI_Index = MissingLowerTextures.Push(mti); + msi.seg = seg; + MissingLowerSegs.Push(msi); + } + } + totalms.Unclock(); +} + + +//========================================================================== +// +// +// +//========================================================================== +bool FDrawInfo::DoOneSectorUpper(subsector_t * subsec, float Planez) +{ + // Is there a one-sided wall in this sector? + // Do this first to avoid unnecessary recursion + for (DWORD i = 0; i < subsec->numlines; i++) + { + if (subsec->firstline[i].backsector == NULL) return false; + if (subsec->firstline[i].PartnerSeg == NULL) return false; + } + + for (DWORD i = 0; i < subsec->numlines; i++) + { + seg_t * seg = subsec->firstline + i; + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // already checked? + if (backsub->validcount == validcount) continue; + backsub->validcount = validcount; + + if (seg->frontsector != seg->backsector && seg->linedef) + { + // Note: if this is a real line between sectors + // we can be sure that render_sector is the real sector! + + sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true); + + // Don't bother with slopes + if (sec->ceilingplane.isSlope()) return false; + + // Is the neighboring ceiling lower than the desired height? + if (sec->GetPlaneTexZ(sector_t::ceiling) < Planez) + { + // todo: check for missing textures. + return false; + } + + // This is an exact height match which means we don't have to do any further checks for this sector + if (sec->GetPlaneTexZ(sector_t::ceiling) == Planez) + { + // If there's a texture abort + FTexture * tex = TexMan[seg->sidedef->GetTexture(side_t::top)]; + if (!tex || tex->UseType == FTexture::TEX_Null) continue; + else return false; + } + } + if (!DoOneSectorUpper(backsub, Planez)) return false; + } + // all checked ok. This subsector is part of the current fake plane + + HandledSubsectors.Push(subsec); + return 1; +} + +//========================================================================== +// +// +// +//========================================================================== +bool FDrawInfo::DoOneSectorLower(subsector_t * subsec, float Planez) +{ + // Is there a one-sided wall in this subsector? + // Do this first to avoid unnecessary recursion + for (DWORD i = 0; i < subsec->numlines; i++) + { + if (subsec->firstline[i].backsector == NULL) return false; + if (subsec->firstline[i].PartnerSeg == NULL) return false; + } + + for (DWORD i = 0; i < subsec->numlines; i++) + { + seg_t * seg = subsec->firstline + i; + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // already checked? + if (backsub->validcount == validcount) continue; + backsub->validcount = validcount; + + if (seg->frontsector != seg->backsector && seg->linedef) + { + // Note: if this is a real line between sectors + // we can be sure that render_sector is the real sector! + + sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true); + + // Don't bother with slopes + if (sec->floorplane.isSlope()) return false; + + // Is the neighboring floor higher than the desired height? + if (sec->GetPlaneTexZ(sector_t::floor) > Planez) + { + // todo: check for missing textures. + return false; + } + + // This is an exact height match which means we don't have to do any further checks for this sector + if (sec->GetPlaneTexZ(sector_t::floor) == Planez) + { + // If there's a texture abort + FTexture * tex = TexMan[seg->sidedef->GetTexture(side_t::bottom)]; + if (!tex || tex->UseType == FTexture::TEX_Null) continue; + else return false; + } + } + if (!DoOneSectorLower(backsub, Planez)) return false; + } + // all checked ok. This sector is part of the current fake plane + + HandledSubsectors.Push(subsec); + return 1; +} + + +//========================================================================== +// +// +// +//========================================================================== +bool FDrawInfo::DoFakeBridge(subsector_t * subsec, float Planez) +{ + // Is there a one-sided wall in this sector? + // Do this first to avoid unnecessary recursion + for (DWORD i = 0; i < subsec->numlines; i++) + { + if (subsec->firstline[i].backsector == NULL) return false; + if (subsec->firstline[i].PartnerSeg == NULL) return false; + } + + for (DWORD i = 0; i < subsec->numlines; i++) + { + seg_t * seg = subsec->firstline + i; + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // already checked? + if (backsub->validcount == validcount) continue; + backsub->validcount = validcount; + + if (seg->frontsector != seg->backsector && seg->linedef) + { + // Note: if this is a real line between sectors + // we can be sure that render_sector is the real sector! + + sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true); + + // Don't bother with slopes + if (sec->floorplane.isSlope()) return false; + + // Is the neighboring floor higher than the desired height? + if (sec->GetPlaneTexZ(sector_t::floor) < Planez) + { + // todo: check for missing textures. + return false; + } + + // This is an exact height match which means we don't have to do any further checks for this sector + // No texture checks though! + if (sec->GetPlaneTexZ(sector_t::floor) == Planez) continue; + } + if (!DoFakeBridge(backsub, Planez)) return false; + } + // all checked ok. This sector is part of the current fake plane + + HandledSubsectors.Push(subsec); + return 1; +} + +//========================================================================== +// +// +// +//========================================================================== +bool FDrawInfo::DoFakeCeilingBridge(subsector_t * subsec, float Planez) +{ + // Is there a one-sided wall in this sector? + // Do this first to avoid unnecessary recursion + for (DWORD i = 0; i < subsec->numlines; i++) + { + if (subsec->firstline[i].backsector == NULL) return false; + if (subsec->firstline[i].PartnerSeg == NULL) return false; + } + + for (DWORD i = 0; i < subsec->numlines; i++) + { + seg_t * seg = subsec->firstline + i; + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // already checked? + if (backsub->validcount == validcount) continue; + backsub->validcount = validcount; + + if (seg->frontsector != seg->backsector && seg->linedef) + { + // Note: if this is a real line between sectors + // we can be sure that render_sector is the real sector! + + sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true); + + // Don't bother with slopes + if (sec->ceilingplane.isSlope()) return false; + + // Is the neighboring ceiling higher than the desired height? + if (sec->GetPlaneTexZ(sector_t::ceiling) > Planez) + { + // todo: check for missing textures. + return false; + } + + // This is an exact height match which means we don't have to do any further checks for this sector + // No texture checks though! + if (sec->GetPlaneTexZ(sector_t::ceiling) == Planez) continue; + } + if (!DoFakeCeilingBridge(backsub, Planez)) return false; + } + // all checked ok. This sector is part of the current fake plane + + HandledSubsectors.Push(subsec); + return 1; +} + + +//========================================================================== +// +// Draws the fake planes +// +//========================================================================== +void FDrawInfo::HandleMissingTextures() +{ + sector_t fake; + totalms.Clock(); + totalupper = MissingUpperTextures.Size(); + totallower = MissingLowerTextures.Size(); + + for (unsigned int i = 0; i < MissingUpperTextures.Size(); i++) + { + if (!MissingUpperTextures[i].seg) continue; + HandledSubsectors.Clear(); + validcount++; + + if (MissingUpperTextures[i].Planez > ViewPos.Z) + { + // close the hole only if all neighboring sectors are an exact height match + // Otherwise just fill in the missing textures. + MissingUpperTextures[i].sub->validcount = validcount; + if (DoOneSectorUpper(MissingUpperTextures[i].sub, MissingUpperTextures[i].Planez)) + { + sector_t * sec = MissingUpperTextures[i].seg->backsector; + // The mere fact that this seg has been added to the list means that the back sector + // will be rendered so we can safely assume that it is already in the render list + + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = HandledSubsectors[j]; + + AddOtherCeilingPlane(sec->sectornum, node); + } + + if (HandledSubsectors.Size() != 1) + { + // mark all subsectors in the missing list that got processed by this + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + for (unsigned int k = 0; k < MissingUpperTextures.Size(); k++) + { + if (MissingUpperTextures[k].sub == HandledSubsectors[j]) + { + MissingUpperTextures[k].seg = NULL; + } + } + } + } + else MissingUpperTextures[i].seg = NULL; + continue; + } + } + + if (!MissingUpperTextures[i].seg->PartnerSeg) continue; + subsector_t *backsub = MissingUpperTextures[i].seg->PartnerSeg->Subsector; + if (!backsub) continue; + validcount++; + HandledSubsectors.Clear(); + + { + // It isn't a hole. Now check whether it might be a fake bridge + sector_t * fakesector = gl_FakeFlat(MissingUpperTextures[i].seg->frontsector, &fake, false); + float planez = (float)fakesector->GetPlaneTexZ(sector_t::ceiling); + + backsub->validcount = validcount; + if (DoFakeCeilingBridge(backsub, planez)) + { + // The mere fact that this seg has been added to the list means that the back sector + // will be rendered so we can safely assume that it is already in the render list + + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = HandledSubsectors[j]; + AddOtherCeilingPlane(fakesector->sectornum, node); + } + } + continue; + } + } + + for (unsigned int i = 0; i < MissingLowerTextures.Size(); i++) + { + if (!MissingLowerTextures[i].seg) continue; + HandledSubsectors.Clear(); + validcount++; + + if (MissingLowerTextures[i].Planez < ViewPos.Z) + { + // close the hole only if all neighboring sectors are an exact height match + // Otherwise just fill in the missing textures. + MissingLowerTextures[i].sub->validcount = validcount; + if (DoOneSectorLower(MissingLowerTextures[i].sub, MissingLowerTextures[i].Planez)) + { + sector_t * sec = MissingLowerTextures[i].seg->backsector; + // The mere fact that this seg has been added to the list means that the back sector + // will be rendered so we can safely assume that it is already in the render list + + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = HandledSubsectors[j]; + AddOtherFloorPlane(sec->sectornum, node); + } + + if (HandledSubsectors.Size() != 1) + { + // mark all subsectors in the missing list that got processed by this + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + for (unsigned int k = 0; k < MissingLowerTextures.Size(); k++) + { + if (MissingLowerTextures[k].sub == HandledSubsectors[j]) + { + MissingLowerTextures[k].seg = NULL; + } + } + } + } + else MissingLowerTextures[i].seg = NULL; + continue; + } + } + + if (!MissingLowerTextures[i].seg->PartnerSeg) continue; + subsector_t *backsub = MissingLowerTextures[i].seg->PartnerSeg->Subsector; + if (!backsub) continue; + validcount++; + HandledSubsectors.Clear(); + + { + // It isn't a hole. Now check whether it might be a fake bridge + sector_t * fakesector = gl_FakeFlat(MissingLowerTextures[i].seg->frontsector, &fake, false); + float planez = (float)fakesector->GetPlaneTexZ(sector_t::floor); + + backsub->validcount = validcount; + if (DoFakeBridge(backsub, planez)) + { + // The mere fact that this seg has been added to the list means that the back sector + // will be rendered so we can safely assume that it is already in the render list + + for (unsigned int j = 0; j < HandledSubsectors.Size(); j++) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = HandledSubsectors[j]; + AddOtherFloorPlane(fakesector->sectornum, node); + } + } + continue; + } + } + + totalms.Unclock(); + showtotalms = totalms; + totalms.Reset(); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::DrawUnhandledMissingTextures() +{ + validcount++; + for (int i = MissingUpperSegs.Size() - 1; i >= 0; i--) + { + int index = MissingUpperSegs[i].MTI_Index; + if (index >= 0 && MissingUpperTextures[index].seg == NULL) continue; + + seg_t * seg = MissingUpperSegs[i].seg; + + // already done! + if (seg->linedef->validcount == validcount) continue; // already done + seg->linedef->validcount = validcount; + if (seg->frontsector->GetPlaneTexZ(sector_t::ceiling) < ViewPos.Z) continue; // out of sight + + // FIXME: The check for degenerate subsectors should be more precise + if (seg->PartnerSeg && (seg->PartnerSeg->Subsector->flags & SSECF_DEGENERATE)) continue; + if (seg->backsector->transdoor) continue; + if (seg->backsector->GetTexture(sector_t::ceiling) == skyflatnum) continue; + if (seg->backsector->ValidatePortal(sector_t::ceiling) != NULL) continue; + + if (!glset.notexturefill) FloodUpperGap(seg); + } + + validcount++; + for (int i = MissingLowerSegs.Size() - 1; i >= 0; i--) + { + int index = MissingLowerSegs[i].MTI_Index; + if (index >= 0 && MissingLowerTextures[index].seg == NULL) continue; + + seg_t * seg = MissingLowerSegs[i].seg; + + if (seg->linedef->validcount == validcount) continue; // already done + seg->linedef->validcount = validcount; + if (!(sectorrenderflags[seg->backsector->sectornum] & SSRF_RENDERFLOOR)) continue; + if (seg->frontsector->GetPlaneTexZ(sector_t::floor) > ViewPos.Z) continue; // out of sight + if (seg->backsector->transdoor) continue; + if (seg->backsector->GetTexture(sector_t::floor) == skyflatnum) continue; + if (seg->backsector->ValidatePortal(sector_t::floor) != NULL) continue; + + if (!glset.notexturefill) FloodLowerGap(seg); + } + MissingUpperTextures.Clear(); + MissingLowerTextures.Clear(); + MissingUpperSegs.Clear(); + MissingLowerSegs.Clear(); + +} + +void AppendMissingTextureStats(FString &out) +{ + out.AppendFormat("Missing textures: %d upper, %d lower, %.3f ms\n", + totalupper, totallower, showtotalms.TimeMS()); +} + +ADD_STAT(missingtextures) +{ + FString out; + AppendMissingTextureStats(out); + return out; +} + + +//========================================================================== +// +// Multi-sector deep water hacks +// +//========================================================================== + +void FDrawInfo::AddHackedSubsector(subsector_t * sub) +{ + if (!(level.maptype == MAPTYPE_HEXEN)) + { + SubsectorHackInfo sh={sub, 0}; + SubsectorHacks.Push (sh); + } +} + +//========================================================================== +// +// Finds a subsector whose plane can be used for rendering +// +//========================================================================== + +bool FDrawInfo::CheckAnchorFloor(subsector_t * sub) +{ + // This subsector has a one sided wall and can be used. + if (sub->hacked==3) return true; + if (sub->flags & SSECF_DEGENERATE) return false; + + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (!seg->PartnerSeg) return true; + + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // Find a linedef with a different visplane on the other side. + if (!(backsub->flags & SSECF_DEGENERATE) && seg->linedef && + (sub->render_sector != backsub->render_sector && sub->sector != backsub->sector)) + { + // I'm ignoring slopes, scaling and rotation here. The likelihood of ZDoom maps + // using such crap hacks is simply too small + if (sub->render_sector->GetTexture(sector_t::floor) == backsub->render_sector->GetTexture(sector_t::floor) && + sub->render_sector->GetPlaneTexZ(sector_t::floor) == backsub->render_sector->GetPlaneTexZ(sector_t::floor) && + sub->render_sector->GetFloorLight() == backsub->render_sector->GetFloorLight()) + { + continue; + } + // This means we found an adjoining subsector that clearly would go into another + // visplane. That means that this subsector can be used as an anchor. + return true; + } + } + return false; +} + +//========================================================================== +// +// Collect connected subsectors that have to be rendered with the same plane +// +//========================================================================== +static bool inview; +static subsector_t * viewsubsector; +static TArray lowersegs; + +bool FDrawInfo::CollectSubsectorsFloor(subsector_t * sub, sector_t * anchor) +{ + + // mark it checked + sub->validcount=validcount; + + + // We must collect any subsector that either is connected to this one with a miniseg + // or has the same visplane. + // We must not collect any subsector that has the anchor's visplane! + if (!(sub->flags & SSECF_DEGENERATE)) + { + // Is not being rendered so don't bother. + if (!(ss_renderflags[DWORD(sub - subsectors)] & SSRF_PROCESSED)) return true; + + if (sub->render_sector->GetTexture(sector_t::floor) != anchor->GetTexture(sector_t::floor) || + sub->render_sector->GetPlaneTexZ(sector_t::floor) != anchor->GetPlaneTexZ(sector_t::floor) || + sub->render_sector->GetFloorLight() != anchor->GetFloorLight()) + { + if (sub == viewsubsector && ViewPos.Z < anchor->GetPlaneTexZ(sector_t::floor)) inview = true; + HandledSubsectors.Push(sub); + } + } + + // We can assume that all segs in this subsector are connected to a subsector that has + // to be checked as well + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // could be an anchor itself. + if (!CheckAnchorFloor (backsub)) // must not be an anchor itself! + { + if (backsub->validcount!=validcount) + { + if (!CollectSubsectorsFloor (backsub, anchor)) return false; + } + } + else if (sub->render_sector == backsub->render_sector) + { + // Any anchor not within the original anchor's visplane terminates the processing. + if (sub->render_sector->GetTexture(sector_t::floor) != anchor->GetTexture(sector_t::floor) || + sub->render_sector->GetPlaneTexZ(sector_t::floor) != anchor->GetPlaneTexZ(sector_t::floor) || + sub->render_sector->GetFloorLight() != anchor->GetFloorLight()) + { + return false; + } + } + if (!seg->linedef || (seg->frontsector==seg->backsector && sub->render_sector!=backsub->render_sector)) + lowersegs.Push(seg); + } + } + return true; +} + +//========================================================================== +// +// Finds a subsector whose plane can be used for rendering +// +//========================================================================== + +bool FDrawInfo::CheckAnchorCeiling(subsector_t * sub) +{ + // This subsector has a one sided wall and can be used. + if (sub->hacked==3) return true; + if (sub->flags & SSECF_DEGENERATE) return false; + + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (!seg->PartnerSeg) return true; + + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // Find a linedef with a different visplane on the other side. + if (!(backsub->flags & SSECF_DEGENERATE) && seg->linedef && + (sub->render_sector != backsub->render_sector && sub->sector != backsub->sector)) + { + // I'm ignoring slopes, scaling and rotation here. The likelihood of ZDoom maps + // using such crap hacks is simply too small + if (sub->render_sector->GetTexture(sector_t::ceiling) == backsub->render_sector->GetTexture(sector_t::ceiling) && + sub->render_sector->GetPlaneTexZ(sector_t::ceiling) == backsub->render_sector->GetPlaneTexZ(sector_t::ceiling) && + sub->render_sector->GetCeilingLight() == backsub->render_sector->GetCeilingLight()) + { + continue; + } + // This means we found an adjoining subsector that clearly would go into another + // visplane. That means that this subsector can be used as an anchor. + return true; + } + } + return false; +} + +//========================================================================== +// +// Collect connected subsectors that have to be rendered with the same plane +// +//========================================================================== + +bool FDrawInfo::CollectSubsectorsCeiling(subsector_t * sub, sector_t * anchor) +{ + // mark it checked + sub->validcount=validcount; + + + // We must collect any subsector that either is connected to this one with a miniseg + // or has the same visplane. + // We must not collect any subsector that has the anchor's visplane! + if (!(sub->flags & SSECF_DEGENERATE)) + { + // Is not being rendererd so don't bother. + if (!(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return true; + + if (sub->render_sector->GetTexture(sector_t::ceiling) != anchor->GetTexture(sector_t::ceiling) || + sub->render_sector->GetPlaneTexZ(sector_t::ceiling) != anchor->GetPlaneTexZ(sector_t::ceiling) || + sub->render_sector->GetCeilingLight() != anchor->GetCeilingLight()) + { + HandledSubsectors.Push(sub); + } + } + + // We can assume that all segs in this subsector are connected to a subsector that has + // to be checked as well + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + // could be an anchor itself. + if (!CheckAnchorCeiling (backsub)) // must not be an anchor itself! + { + if (backsub->validcount!=validcount) + { + if (!CollectSubsectorsCeiling (backsub, anchor)) return false; + } + } + else if (sub->render_sector == backsub->render_sector) + { + // Any anchor not within the original anchor's visplane terminates the processing. + if (sub->render_sector->GetTexture(sector_t::ceiling) != anchor->GetTexture(sector_t::ceiling) || + sub->render_sector->GetPlaneTexZ(sector_t::ceiling) != anchor->GetPlaneTexZ(sector_t::ceiling) || + sub->render_sector->GetCeilingLight() != anchor->GetCeilingLight()) + { + return false; + } + } + } + } + return true; +} + +//========================================================================== +// +// Process the subsectors that have been marked as hacked +// +//========================================================================== + +void FDrawInfo::HandleHackedSubsectors() +{ + lowershcount=uppershcount=0; + totalssms.Reset(); + totalssms.Clock(); + + viewsubsector = R_PointInSubsector(ViewPos); + + // Each subsector may only be processed once in this loop! + validcount++; + for(unsigned int i=0;ivalidcount!=validcount && CheckAnchorFloor(sub)) + { + // Now collect everything that is connected with this subsector. + HandledSubsectors.Clear(); + inview=false; + lowersegs.Clear(); + if (CollectSubsectorsFloor(sub, sub->render_sector)) + { + for(unsigned int j=0;jsub = HandledSubsectors[j]; + AddOtherFloorPlane(sub->render_sector->sectornum, node); + } + if (inview) for(unsigned int j=0;jProcessLowerMiniseg (seg, seg->Subsector->render_sector, seg->PartnerSeg->Subsector->render_sector); + } + lowershcount+=HandledSubsectors.Size(); + } + } + } + + // Each subsector may only be processed once in this loop! + validcount++; + for(unsigned int i=0;ivalidcount!=validcount && CheckAnchorCeiling(sub)) + { + // Now collect everything that is connected with this subsector. + HandledSubsectors.Clear(); + if (CollectSubsectorsCeiling(sub, sub->render_sector)) + { + for(unsigned int j=0;jsub = HandledSubsectors[j]; + AddOtherCeilingPlane(sub->render_sector->sectornum, node); + } + uppershcount+=HandledSubsectors.Size(); + } + } + } + + + SubsectorHacks.Clear(); + totalssms.Unclock(); +} + +ADD_STAT(sectorhacks) +{ + FString out; + out.Format("sectorhacks = %.3f ms, %d upper, %d lower\n", totalssms.TimeMS(), uppershcount, lowershcount); + return out; +} + + +//========================================================================== +// +// This merges visplanes that lie inside a sector stack together +// to avoid rendering these unneeded flats +// +//========================================================================== + +void FDrawInfo::AddFloorStack(sector_t * sec) +{ + FloorStacks.Push(sec); +} + +void FDrawInfo::AddCeilingStack(sector_t * sec) +{ + CeilingStacks.Push(sec); +} + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::CollectSectorStacksCeiling(subsector_t * sub, sector_t * anchor) +{ + // mark it checked + sub->validcount=validcount; + + // Has a sector stack or skybox itself! + if (sub->render_sector->GetGLPortal(sector_t::ceiling) != nullptr) return; + + // Don't bother processing unrendered subsectors + if (sub->numlines>2 && !(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return; + + // Must be the exact same visplane + sector_t * me = gl_FakeFlat(sub->render_sector, &fakesec, false); + if (me->GetTexture(sector_t::ceiling) != anchor->GetTexture(sector_t::ceiling) || + me->ceilingplane != anchor->ceilingplane || + me->GetCeilingLight() != anchor->GetCeilingLight() || + me->ColorMap != anchor->ColorMap || + me->planes[sector_t::ceiling].xform != anchor->planes[sector_t::ceiling].xform) + { + // different visplane so it can't belong to this stack + return; + } + + HandledSubsectors.Push (sub); + + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + if (backsub->validcount!=validcount) CollectSectorStacksCeiling (backsub, anchor); + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::CollectSectorStacksFloor(subsector_t * sub, sector_t * anchor) +{ + // mark it checked + sub->validcount=validcount; + + // Has a sector stack or skybox itself! + if (sub->render_sector->GetGLPortal(sector_t::floor) != nullptr) return; + + // Don't bother processing unrendered subsectors + if (sub->numlines>2 && !(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return; + + // Must be the exact same visplane + sector_t * me = gl_FakeFlat(sub->render_sector, &fakesec, false); + if (me->GetTexture(sector_t::floor) != anchor->GetTexture(sector_t::floor) || + me->floorplane != anchor->floorplane || + me->GetFloorLight() != anchor->GetFloorLight() || + me->ColorMap != anchor->ColorMap || + me->planes[sector_t::floor].xform != anchor->planes[sector_t::floor].xform) + { + // different visplane so it can't belong to this stack + return; + } + + HandledSubsectors.Push (sub); + + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + if (backsub->validcount!=validcount) CollectSectorStacksFloor (backsub, anchor); + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FDrawInfo::ProcessSectorStacks() +{ + unsigned int i; + sector_t fake; + + validcount++; + for (i=0;iGetGLPortal(sector_t::ceiling); + if (portal != NULL) for(int k=0;ksubsectorcount;k++) + { + subsector_t * sub = sec->subsectors[k]; + if (ss_renderflags[sub-subsectors] & SSRF_PROCESSED) + { + HandledSubsectors.Clear(); + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + if (backsub->validcount!=validcount) CollectSectorStacksCeiling (backsub, sec); + } + } + for(unsigned int j=0;jportalcoverage[sector_t::ceiling].subsectors == NULL) + { + gl_BuildPortalCoverage(&sub->portalcoverage[sector_t::ceiling], sub, portal->mDisplacement); + } + + portal->GetRenderState()->AddSubsector(sub); + + if (sec->GetAlpha(sector_t::ceiling) != 0 && sec->GetTexture(sector_t::ceiling) != skyflatnum) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = sub; + AddOtherCeilingPlane(sec->sectornum, node); + } + } + } + } + } + + validcount++; + for (i=0;iGetGLPortal(sector_t::floor); + if (portal != NULL) for(int k=0;ksubsectorcount;k++) + { + subsector_t * sub = sec->subsectors[k]; + if (ss_renderflags[sub-subsectors] & SSRF_PROCESSED) + { + HandledSubsectors.Clear(); + for(DWORD j=0;jnumlines;j++) + { + seg_t * seg = sub->firstline + j; + if (seg->PartnerSeg) + { + subsector_t * backsub = seg->PartnerSeg->Subsector; + + if (backsub->validcount!=validcount) CollectSectorStacksFloor (backsub, sec); + } + } + + for(unsigned int j=0;jportalcoverage[sector_t::floor].subsectors == NULL) + { + gl_BuildPortalCoverage(&sub->portalcoverage[sector_t::floor], sub, portal->mDisplacement); + } + + GLSectorStackPortal *glportal = portal->GetRenderState(); + glportal->AddSubsector(sub); + + if (sec->GetAlpha(sector_t::floor) != 0 && sec->GetTexture(sector_t::floor) != skyflatnum) + { + gl_subsectorrendernode * node = SSR_List.GetNew(); + node->sub = sub; + AddOtherFloorPlane(sec->sectornum, node); + } + } + } + } + } + + FloorStacks.Clear(); + CeilingStacks.Clear(); +} + diff --git a/src/gl/scene/gl_scene.cpp b/src/gl/scene/gl_scene.cpp new file mode 100644 index 000000000..5cca167d3 --- /dev/null +++ b/src/gl/scene/gl_scene.cpp @@ -0,0 +1,1419 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_scene.cpp +** manages the rendering of the player's view +** +*/ + +#include "gl/system/gl_system.h" +#include "gi.h" +#include "m_png.h" +#include "m_random.h" +#include "st_stuff.h" +#include "dobject.h" +#include "doomstat.h" +#include "g_level.h" +#include "r_data/r_interpolate.h" +#include "r_utility.h" +#include "d_player.h" +#include "p_effect.h" +#include "sbar.h" +#include "po_man.h" +#include "r_utility.h" +#include "p_local.h" +#include "gl/gl_functions.h" +#include "serializer.h" + +#include "gl/dynlights/gl_lightbuffer.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/models/gl_models.h" +#include "gl/scene/gl_clipper.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/stereo3d/gl_stereo3d.h" +#include "gl/stereo3d/scoped_view_shifter.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_material.h" +#include "gl/textures/gl_skyboxtexture.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_convert.h" +#include "gl/utility/gl_templates.h" + +//========================================================================== +// +// CVARs +// +//========================================================================== +CVAR(Bool, gl_texture, true, 0) +CVAR(Bool, gl_no_skyclear, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +CVAR(Float, gl_mask_threshold, 0.5f,CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +CVAR(Float, gl_mask_sprite_threshold, 0.5f,CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +CVAR(Bool, gl_sort_textures, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) + +EXTERN_CVAR (Bool, cl_capfps) +EXTERN_CVAR (Bool, r_deathcamera) +EXTERN_CVAR (Float, underwater_fade_scalar) + + +extern int viewpitch; +extern bool NoInterpolateView; +extern bool r_showviewer; + +DWORD gl_fixedcolormap; +area_t in_area; +TArray currentmapsection; +int camtexcount; + +void gl_ParseDefs(); + +//----------------------------------------------------------------------------- +// +// R_FrustumAngle +// +//----------------------------------------------------------------------------- +angle_t FGLRenderer::FrustumAngle() +{ + float tilt= fabs(mAngles.Pitch.Degrees); + + // If the pitch is larger than this you can look all around at a FOV of 90° + if (tilt>46.0f) return 0xffffffff; + + // ok, this is a gross hack that barely works... + // but at least it doesn't overestimate too much... + double floatangle=2.0+(45.0+((tilt/1.9)))*mCurrentFoV*48.0/AspectMultiplier(WidescreenRatio)/90.0; + angle_t a1 = DAngle(floatangle).BAMs(); + if (a1>=ANGLE_180) return 0xffffffff; + return a1; +} + +//----------------------------------------------------------------------------- +// +// Sets the area the camera is in +// +//----------------------------------------------------------------------------- +void FGLRenderer::SetViewArea() +{ + // The render_sector is better suited to represent the current position in GL + viewsector = R_PointInSubsector(ViewPos)->render_sector; + + // Get the heightsec state from the render sector, not the current one! + if (viewsector->heightsec && !(viewsector->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC)) + { + in_area = ViewPos.Z <= viewsector->heightsec->floorplane.ZatPoint(ViewPos) ? area_below : + (ViewPos.Z > viewsector->heightsec->ceilingplane.ZatPoint(ViewPos) && + !(viewsector->heightsec->MoreFlags&SECF_FAKEFLOORONLY)) ? area_above : area_normal; + } + else + { + in_area = area_default; // depends on exposed lower sectors + } +} + +//----------------------------------------------------------------------------- +// +// resets the 3D viewport +// +//----------------------------------------------------------------------------- + +void FGLRenderer::Reset3DViewport() +{ + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); +} + +//----------------------------------------------------------------------------- +// +// sets 3D viewport and initial state +// +//----------------------------------------------------------------------------- + +void FGLRenderer::Set3DViewport(bool mainview) +{ + if (mainview && mBuffers->Setup(mScreenViewport.width, mScreenViewport.height, mSceneViewport.width, mSceneViewport.height)) + { + bool useSSAO = (gl_ssao != 0); + mBuffers->BindSceneFB(useSSAO); + gl_RenderState.SetPassType(useSSAO ? GBUFFER_PASS : NORMAL_PASS); + gl_RenderState.EnableDrawBuffers(gl_RenderState.GetPassDrawBufferCount()); + gl_RenderState.Apply(); + } + + // Always clear all buffers with scissor test disabled. + // This is faster on newer hardware because it allows the GPU to skip + // reading from slower memory where the full buffers are stored. + glDisable(GL_SCISSOR_TEST); + glClearColor(mSceneClearColor[0], mSceneClearColor[1], mSceneClearColor[2], 1.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + const auto &bounds = mSceneViewport; + glViewport(bounds.left, bounds.top, bounds.width, bounds.height); + glScissor(bounds.left, bounds.top, bounds.width, bounds.height); + + glEnable(GL_SCISSOR_TEST); + + glEnable(GL_MULTISAMPLE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_STENCIL_TEST); + glStencilFunc(GL_ALWAYS,0,~0); // default stencil + glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE); +} + +//----------------------------------------------------------------------------- +// +// Setup the camera position +// +//----------------------------------------------------------------------------- + +void FGLRenderer::SetViewAngle(DAngle viewangle) +{ + mAngles.Yaw = float(270.0-viewangle.Degrees); + DVector2 v = ViewAngle.ToVector(); + mViewVector.X = v.X; + mViewVector.Y = v.Y; + + R_SetViewAngle(); +} + + +//----------------------------------------------------------------------------- +// +// SetProjection +// sets projection matrix +// +//----------------------------------------------------------------------------- + +void FGLRenderer::SetProjection(float fov, float ratio, float fovratio) +{ + + float fovy = 2 * RAD2DEG(atan(tan(DEG2RAD(fov) / 2) / fovratio)); + gl_RenderState.mProjectionMatrix.perspective(fovy, ratio, GetZNear(), GetZFar()); +} + +// raw matrix input from stereo 3d modes +void FGLRenderer::SetProjection(VSMatrix matrix) +{ + gl_RenderState.mProjectionMatrix.loadIdentity(); + gl_RenderState.mProjectionMatrix.multMatrix(matrix); +} + +//----------------------------------------------------------------------------- +// +// Setup the modelview matrix +// +//----------------------------------------------------------------------------- + +void FGLRenderer::SetViewMatrix(float vx, float vy, float vz, bool mirror, bool planemirror) +{ + float mult = mirror? -1:1; + float planemult = planemirror? -glset.pixelstretch : glset.pixelstretch; + + gl_RenderState.mViewMatrix.loadIdentity(); + gl_RenderState.mViewMatrix.rotate(GLRenderer->mAngles.Roll.Degrees, 0.0f, 0.0f, 1.0f); + gl_RenderState.mViewMatrix.rotate(GLRenderer->mAngles.Pitch.Degrees, 1.0f, 0.0f, 0.0f); + gl_RenderState.mViewMatrix.rotate(GLRenderer->mAngles.Yaw.Degrees, 0.0f, mult, 0.0f); + gl_RenderState.mViewMatrix.translate(vx * mult, -vz * planemult , -vy); + gl_RenderState.mViewMatrix.scale(-mult, planemult, 1); +} + + +//----------------------------------------------------------------------------- +// +// SetupView +// Setup the view rotation matrix for the given viewpoint +// +//----------------------------------------------------------------------------- +void FGLRenderer::SetupView(float vx, float vy, float vz, DAngle va, bool mirror, bool planemirror) +{ + SetViewAngle(va); + SetViewMatrix(vx, vy, vz, mirror, planemirror); + gl_RenderState.ApplyMatrices(); +} + +//----------------------------------------------------------------------------- +// +// CreateScene +// +// creates the draw lists for the current scene +// +//----------------------------------------------------------------------------- + +void FGLRenderer::CreateScene() +{ + // reset the portal manager + GLPortal::StartFrame(); + PO_LinkToSubsectors(); + + ProcessAll.Clock(); + + // clip the scene and fill the drawlists + for(unsigned i=0;iglportal = NULL; + gl_spriteindex=0; + Bsp.Clock(); + GLRenderer->mVBO->Map(); + R_SetView(); + validcount++; // used for processing sidedefs only once by the renderer. + gl_RenderBSPNode (nodes + numnodes - 1); + if (GLRenderer->mCurrentPortal != NULL) GLRenderer->mCurrentPortal->RenderAttached(); + Bsp.Unclock(); + + // And now the crappy hacks that have to be done to avoid rendering anomalies: + + gl_drawinfo->HandleMissingTextures(); // Missing upper/lower textures + gl_drawinfo->HandleHackedSubsectors(); // open sector hacks for deep water + gl_drawinfo->ProcessSectorStacks(); // merge visplanes of sector stacks + GLRenderer->mVBO->Unmap(); + + ProcessAll.Unclock(); + +} + +//----------------------------------------------------------------------------- +// +// RenderScene +// +// Draws the current draw lists for the non GLSL renderer +// +//----------------------------------------------------------------------------- + +void FGLRenderer::RenderScene(int recursion) +{ + RenderAll.Clock(); + + glDepthMask(true); + if (!gl_no_skyclear) GLPortal::RenderFirstSkyPortal(recursion); + + gl_RenderState.SetCameraPos(ViewPos.X, ViewPos.Y, ViewPos.Z); + + gl_RenderState.EnableFog(true); + gl_RenderState.BlendFunc(GL_ONE,GL_ZERO); + + if (gl_sort_textures) + { + gl_drawinfo->drawlists[GLDL_PLAINWALLS].SortWalls(); + gl_drawinfo->drawlists[GLDL_PLAINFLATS].SortFlats(); + gl_drawinfo->drawlists[GLDL_MASKEDWALLS].SortWalls(); + gl_drawinfo->drawlists[GLDL_MASKEDFLATS].SortFlats(); + gl_drawinfo->drawlists[GLDL_MASKEDWALLSOFS].SortWalls(); + } + + // if we don't have a persistently mapped buffer, we have to process all the dynamic lights up front, + // so that we don't have to do repeated map/unmap calls on the buffer. + bool haslights = mLightCount > 0 && gl_fixedcolormap == CM_DEFAULT && gl_lights; + if (gl.lightmethod == LM_DEFERRED && haslights) + { + GLRenderer->mLights->Begin(); + gl_drawinfo->drawlists[GLDL_PLAINWALLS].DrawWalls(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_PLAINFLATS].DrawFlats(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_MASKEDWALLS].DrawWalls(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_MASKEDFLATS].DrawFlats(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_MASKEDWALLSOFS].DrawWalls(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_TRANSLUCENTBORDER].Draw(GLPASS_LIGHTSONLY); + gl_drawinfo->drawlists[GLDL_TRANSLUCENT].Draw(GLPASS_LIGHTSONLY, true); + GLRenderer->mLights->Finish(); + } + + // Part 1: solid geometry. This is set up so that there are no transparent parts + glDepthFunc(GL_LESS); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + glDisable(GL_POLYGON_OFFSET_FILL); + + int pass; + + if (!haslights || gl.lightmethod == LM_DEFERRED) + { + pass = GLPASS_PLAIN; + } + else if (gl.lightmethod == LM_DIRECT) + { + pass = GLPASS_ALL; + } + else + { + // process everything that needs to handle textured dynamic lights. + if (haslights) RenderMultipassStuff(); + + // The remaining lists which are unaffected by dynamic lights are just processed as normal. + pass = GLPASS_PLAIN; + } + + gl_RenderState.EnableTexture(gl_texture); + gl_RenderState.EnableBrightmap(true); + gl_drawinfo->drawlists[GLDL_PLAINWALLS].DrawWalls(pass); + gl_drawinfo->drawlists[GLDL_PLAINFLATS].DrawFlats(pass); + + + // Part 2: masked geometry. This is set up so that only pixels with alpha>gl_mask_threshold will show + if (!gl_texture) + { + gl_RenderState.EnableTexture(true); + gl_RenderState.SetTextureMode(TM_MASK); + } + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_threshold); + gl_drawinfo->drawlists[GLDL_MASKEDWALLS].DrawWalls(pass); + gl_drawinfo->drawlists[GLDL_MASKEDFLATS].DrawFlats(pass); + + // Part 3: masked geometry with polygon offset. This list is empty most of the time so only waste time on it when in use. + if (gl_drawinfo->drawlists[GLDL_MASKEDWALLSOFS].Size() > 0) + { + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + gl_drawinfo->drawlists[GLDL_MASKEDWALLSOFS].DrawWalls(pass); + glDisable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(0, 0); + } + + gl_drawinfo->drawlists[GLDL_MODELS].Draw(pass); + + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Part 4: Draw decals (not a real pass) + glDepthFunc(GL_LEQUAL); + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + glDepthMask(false); + + // this is the only geometry type on which decals can possibly appear + gl_drawinfo->drawlists[GLDL_PLAINWALLS].DrawDecals(); + if (gl.legacyMode) + { + // also process the render lists with walls and dynamic lights + gl_drawinfo->dldrawlists[GLLDL_WALLS_PLAIN].DrawDecals(); + gl_drawinfo->dldrawlists[GLLDL_WALLS_FOG].DrawDecals(); + } + + gl_RenderState.SetTextureMode(TM_MODULATE); + + glDepthMask(true); + + + // Push bleeding floor/ceiling textures back a little in the z-buffer + // so they don't interfere with overlapping mid textures. + glPolygonOffset(1.0f, 128.0f); + + // Part 5: flood all the gaps with the back sector's flat texture + // This will always be drawn like GLDL_PLAIN, depending on the fog settings + + glDepthMask(false); // don't write to Z-buffer! + gl_RenderState.EnableFog(true); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.BlendFunc(GL_ONE,GL_ZERO); + gl_drawinfo->DrawUnhandledMissingTextures(); + glDepthMask(true); + + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + RenderAll.Unclock(); + +} + +//----------------------------------------------------------------------------- +// +// RenderTranslucent +// +// Draws the current draw lists for the non GLSL renderer +// +//----------------------------------------------------------------------------- + +void FGLRenderer::RenderTranslucent() +{ + RenderAll.Clock(); + + glDepthMask(false); + gl_RenderState.SetCameraPos(ViewPos.X, ViewPos.Y, ViewPos.Z); + + // final pass: translucent stuff + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + gl_RenderState.EnableBrightmap(true); + gl_drawinfo->drawlists[GLDL_TRANSLUCENTBORDER].Draw(GLPASS_TRANSLUCENT); + gl_drawinfo->drawlists[GLDL_TRANSLUCENT].DrawSorted(); + gl_RenderState.EnableBrightmap(false); + + glDepthMask(true); + + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.5f); + RenderAll.Unclock(); +} + + +//----------------------------------------------------------------------------- +// +// gl_drawscene - this function renders the scene from the current +// viewpoint, including mirrors and skyboxes and other portals +// It is assumed that the GLPortal::EndFrame returns with the +// stencil, z-buffer and the projection matrix intact! +// +//----------------------------------------------------------------------------- + +void FGLRenderer::DrawScene(int drawmode) +{ + static int recursion=0; + static int ssao_portals_available = 0; + + bool applySSAO = false; + if (drawmode == DM_MAINVIEW) + { + ssao_portals_available = gl_ssao_portals; + applySSAO = true; + } + else if (drawmode == DM_OFFSCREEN) + { + ssao_portals_available = 0; + } + else if (ssao_portals_available > 0) + { + applySSAO = true; + ssao_portals_available--; + } + + if (camera != nullptr) + { + ActorRenderFlags savedflags = camera->renderflags; + if (drawmode != DM_PORTAL && !r_showviewer) + { + camera->renderflags |= RF_INVISIBLE; + } + CreateScene(); + camera->renderflags = savedflags; + } + else + { + CreateScene(); + } + GLRenderer->mClipPortal = NULL; // this must be reset before any portal recursion takes place. + + RenderScene(recursion); + + if (applySSAO && gl_RenderState.GetPassType() == GBUFFER_PASS) + { + gl_RenderState.EnableDrawBuffers(1); + AmbientOccludeScene(); + mBuffers->BindSceneFB(true); + gl_RenderState.EnableDrawBuffers(gl_RenderState.GetPassDrawBufferCount()); + gl_RenderState.Apply(); + gl_RenderState.ApplyMatrices(); + } + + // Handle all portals after rendering the opaque objects but before + // doing all translucent stuff + recursion++; + GLPortal::EndFrame(); + recursion--; + RenderTranslucent(); +} + + +void gl_FillScreen() +{ + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.EnableTexture(false); + gl_RenderState.Apply(); + // The fullscreen quad is stored at index 4 in the main vertex buffer. + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_STRIP, FFlatVertexBuffer::FULLSCREEN_INDEX, 4); +} + +//========================================================================== +// +// Draws a blend over the entire view +// +//========================================================================== +void FGLRenderer::DrawBlend(sector_t * viewsector) +{ + float blend[4]={0,0,0,0}; + PalEntry blendv=0; + float extra_red; + float extra_green; + float extra_blue; + player_t *player = NULL; + + if (players[consoleplayer].camera != NULL) + { + player=players[consoleplayer].camera->player; + } + + // don't draw sector based blends when an invulnerability colormap is active + if (!gl_fixedcolormap) + { + if (!viewsector->e->XFloor.ffloors.Size()) + { + if (viewsector->heightsec && !(viewsector->MoreFlags&SECF_IGNOREHEIGHTSEC)) + { + switch (in_area) + { + default: + case area_normal: blendv = viewsector->heightsec->midmap; break; + case area_above: blendv = viewsector->heightsec->topmap; break; + case area_below: blendv = viewsector->heightsec->bottommap; break; + } + } + } + else + { + TArray & lightlist = viewsector->e->XFloor.lightlist; + + for (unsigned int i = 0; i < lightlist.Size(); i++) + { + double lightbottom; + if (i < lightlist.Size() - 1) + lightbottom = lightlist[i + 1].plane.ZatPoint(ViewPos); + else + lightbottom = viewsector->floorplane.ZatPoint(ViewPos); + + if (lightbottom < ViewPos.Z && (!lightlist[i].caster || !(lightlist[i].caster->flags&FF_FADEWALLS))) + { + // 3d floor 'fog' is rendered as a blending value + blendv = lightlist[i].blend; + // If this is the same as the sector's it doesn't apply! + if (blendv == viewsector->ColorMap->Fade) blendv = 0; + // a little hack to make this work for Legacy maps. + if (blendv.a == 0 && blendv != 0) blendv.a = 128; + break; + } + } + } + + if (blendv.a == 0) + { + blendv = R_BlendForColormap(blendv); + if (blendv.a == 255) + { + // The calculated average is too dark so brighten it according to the palettes's overall brightness + int maxcol = MAX(MAX(framebuffer->palette_brightness, blendv.r), MAX(blendv.g, blendv.b)); + blendv.r = blendv.r * 255 / maxcol; + blendv.g = blendv.g * 255 / maxcol; + blendv.b = blendv.b * 255 / maxcol; + } + } + + if (blendv.a == 255) + { + + extra_red = blendv.r / 255.0f; + extra_green = blendv.g / 255.0f; + extra_blue = blendv.b / 255.0f; + + // If this is a multiplicative blend do it separately and add the additive ones on top of it. + blendv = 0; + + // black multiplicative blends are ignored + if (extra_red || extra_green || extra_blue) + { + gl_RenderState.BlendFunc(GL_DST_COLOR, GL_ZERO); + gl_RenderState.SetColor(extra_red, extra_green, extra_blue, 1.0f); + gl_FillScreen(); + } + } + else if (blendv.a) + { + // [Nash] allow user to set blend intensity + int cnt = blendv.a; + cnt = (int)(cnt * underwater_fade_scalar); + + V_AddBlend(blendv.r / 255.f, blendv.g / 255.f, blendv.b / 255.f, cnt / 255.0f, blend); + } + } + + // This mostly duplicates the code in shared_sbar.cpp + // When I was writing this the original was called too late so that I + // couldn't get the blend in time. However, since then I made some changes + // here that would get lost if I switched back so I won't do it. + + if (player) + { + V_AddPlayerBlend(player, blend, 0.5, 175); + } + + if (players[consoleplayer].camera != NULL) + { + // except for fadeto effects + player_t *player = (players[consoleplayer].camera->player != NULL) ? players[consoleplayer].camera->player : &players[consoleplayer]; + V_AddBlend (player->BlendR, player->BlendG, player->BlendB, player->BlendA, blend); + } + + gl_RenderState.SetTextureMode(TM_MODULATE); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (blend[3]>0.0f) + { + gl_RenderState.SetColor(blend[0], blend[1], blend[2], blend[3]); + gl_FillScreen(); + } + gl_RenderState.ResetColor(); + gl_RenderState.EnableTexture(true); +} + + +//----------------------------------------------------------------------------- +// +// Draws player sprites and color blend +// +//----------------------------------------------------------------------------- + + +void FGLRenderer::EndDrawScene(sector_t * viewsector) +{ + gl_RenderState.EnableFog(false); + + // [BB] HUD models need to be rendered here. Make sure that + // DrawPlayerSprites is only called once. Either to draw + // HUD models or to draw the weapon sprites. + const bool renderHUDModel = gl_IsHUDModelForPlayerAvailable( players[consoleplayer].camera->player ); + if ( renderHUDModel ) + { + // [BB] The HUD model should be drawn over everything else already drawn. + glClear(GL_DEPTH_BUFFER_BIT); + DrawPlayerSprites (viewsector, true); + } + + glDisable(GL_STENCIL_TEST); + + framebuffer->Begin2D(false); + + Reset3DViewport(); + + // [BB] Only draw the sprites if we didn't render a HUD model before. + if ( renderHUDModel == false ) + { + DrawPlayerSprites (viewsector, false); + } + if (gl.legacyMode) + { + gl_RenderState.DrawColormapOverlay(); + } + + gl_RenderState.SetFixedColormap(CM_DEFAULT); + gl_RenderState.SetSoftLightLevel(-1); + DrawTargeterSprites(); + if (!FGLRenderBuffers::IsEnabled()) + { + DrawBlend(viewsector); + } + + // Restore standard rendering state + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.ResetColor(); + gl_RenderState.EnableTexture(true); + glDisable(GL_SCISSOR_TEST); +} + + +//----------------------------------------------------------------------------- +// +// R_RenderView - renders one view - either the screen or a camera texture +// +//----------------------------------------------------------------------------- + +void FGLRenderer::ProcessScene(bool toscreen) +{ + FDrawInfo::StartDrawInfo(); + iter_dlightf = iter_dlight = draw_dlight = draw_dlightf = 0; + GLPortal::BeginScene(); + + int mapsection = R_PointInSubsector(ViewPos)->mapsection; + memset(¤tmapsection[0], 0, currentmapsection.Size()); + currentmapsection[mapsection>>3] |= 1 << (mapsection & 7); + DrawScene(toscreen ? DM_MAINVIEW : DM_OFFSCREEN); + FDrawInfo::EndDrawInfo(); + +} + +//----------------------------------------------------------------------------- +// +// gl_SetFixedColormap +// +//----------------------------------------------------------------------------- + +void FGLRenderer::SetFixedColormap (player_t *player) +{ + gl_fixedcolormap=CM_DEFAULT; + + // check for special colormaps + player_t * cplayer = player->camera->player; + if (cplayer) + { + if (cplayer->extralight == INT_MIN) + { + gl_fixedcolormap=CM_FIRSTSPECIALCOLORMAP + INVERSECOLORMAP; + extralight=0; + } + else if (cplayer->fixedcolormap != NOFIXEDCOLORMAP) + { + gl_fixedcolormap = CM_FIRSTSPECIALCOLORMAP + cplayer->fixedcolormap; + } + else if (cplayer->fixedlightlevel != -1) + { + for(AInventory * in = cplayer->mo->Inventory; in; in = in->Inventory) + { + PalEntry color = in->GetBlend (); + + // Need special handling for light amplifiers + if (in->IsKindOf(RUNTIME_CLASS(APowerTorch))) + { + gl_fixedcolormap = cplayer->fixedlightlevel + CM_TORCH; + } + else if (in->IsKindOf(RUNTIME_CLASS(APowerLightAmp))) + { + gl_fixedcolormap = CM_LITE; + } + } + } + } + gl_RenderState.SetFixedColormap(gl_fixedcolormap); +} + +//----------------------------------------------------------------------------- +// +// Renders one viewpoint in a scene +// +//----------------------------------------------------------------------------- + +sector_t * FGLRenderer::RenderViewpoint (AActor * camera, GL_IRECT * bounds, float fov, float ratio, float fovratio, bool mainview, bool toscreen) +{ + sector_t * lviewsector; + mSceneClearColor[0] = 0.0f; + mSceneClearColor[1] = 0.0f; + mSceneClearColor[2] = 0.0f; + R_SetupFrame (camera); + SetViewArea(); + + // We have to scale the pitch to account for the pixel stretching, because the playsim doesn't know about this and treats it as 1:1. + double radPitch = ViewPitch.Normalized180().Radians(); + double angx = cos(radPitch); + double angy = sin(radPitch) * glset.pixelstretch; + double alen = sqrt(angx*angx + angy*angy); + + mAngles.Pitch = (float)RAD2DEG(asin(angy / alen)); + mAngles.Roll.Degrees = ViewRoll.Degrees; + + // Scroll the sky + mSky1Pos = (float)fmod(gl_frameMS * level.skyspeed1, 1024.f) * 90.f/256.f; + mSky2Pos = (float)fmod(gl_frameMS * level.skyspeed2, 1024.f) * 90.f/256.f; + + + + if (camera->player && camera->player-players==consoleplayer && + ((camera->player->cheats & CF_CHASECAM) || (r_deathcamera && camera->health <= 0)) && camera==camera->player->mo) + { + mViewActor=NULL; + } + else + { + mViewActor=camera; + } + + // 'viewsector' will not survive the rendering so it cannot be used anymore below. + lviewsector = viewsector; + + // Render (potentially) multiple views for stereo 3d + float viewShift[3]; + const s3d::Stereo3DMode& stereo3dMode = mainview && toscreen? s3d::Stereo3DMode::getCurrentMode() : s3d::Stereo3DMode::getMonoMode(); + stereo3dMode.SetUp(); + for (int eye_ix = 0; eye_ix < stereo3dMode.eye_count(); ++eye_ix) + { + const s3d::EyePose * eye = stereo3dMode.getEyePose(eye_ix); + eye->SetUp(); + SetOutputViewport(bounds); + Set3DViewport(mainview); + mDrawingScene2D = true; + mCurrentFoV = fov; + // Stereo mode specific perspective projection + SetProjection( eye->GetProjection(fov, ratio, fovratio) ); + // SetProjection(fov, ratio, fovratio); // switch to perspective mode and set up clipper + SetViewAngle(ViewAngle); + // Stereo mode specific viewpoint adjustment - temporarily shifts global ViewPos + eye->GetViewShift(GLRenderer->mAngles.Yaw.Degrees, viewShift); + s3d::ScopedViewShifter viewShifter(viewShift); + SetViewMatrix(ViewPos.X, ViewPos.Y, ViewPos.Z, false, false); + gl_RenderState.ApplyMatrices(); + + clipper.Clear(); + angle_t a1 = FrustumAngle(); + clipper.SafeAddClipRangeRealAngles(ViewAngle.BAMs() + a1, ViewAngle.BAMs() - a1); + + ProcessScene(toscreen); + if (mainview && toscreen) EndDrawScene(lviewsector); // do not call this for camera textures. + if (mainview && FGLRenderBuffers::IsEnabled()) + { + PostProcessScene(); + + // This should be done after postprocessing, not before. + mBuffers->BindCurrentFB(); + glViewport(mScreenViewport.left, mScreenViewport.top, mScreenViewport.width, mScreenViewport.height); + DrawBlend(lviewsector); + } + mDrawingScene2D = false; + if (!stereo3dMode.IsMono() && FGLRenderBuffers::IsEnabled()) + mBuffers->BlitToEyeTexture(eye_ix); + eye->TearDown(); + } + stereo3dMode.TearDown(); + + gl_frameCount++; // This counter must be increased right before the interpolations are restored. + interpolator.RestoreInterpolations (); + return lviewsector; +} + +//----------------------------------------------------------------------------- +// +// renders the view +// +//----------------------------------------------------------------------------- + +void FGLRenderer::RenderView (player_t* player) +{ + OpenGLFrameBuffer* GLTarget = static_cast(screen); + AActor *&LastCamera = GLTarget->LastCamera; + + checkBenchActive(); + if (player->camera != LastCamera) + { + // If the camera changed don't interpolate + // Otherwise there will be some not so nice effects. + R_ResetViewInterpolation(); + LastCamera=player->camera; + } + + gl_RenderState.SetVertexBuffer(mVBO); + GLRenderer->mVBO->Reset(); + + // reset statistics counters + ResetProfilingData(); + + // Get this before everything else + if (cl_capfps || r_NoInterpolate) r_TicFracF = 1.; + else r_TicFracF = I_GetTimeFrac (&r_FrameTime); + gl_frameMS = I_MSTime(); + + P_FindParticleSubsectors (); + + if (!gl.legacyMode) GLRenderer->mLights->Clear(); + + // NoInterpolateView should have no bearing on camera textures, but needs to be preserved for the main view below. + bool saved_niv = NoInterpolateView; + NoInterpolateView = false; + // prepare all camera textures that have been used in the last frame + FCanvasTextureInfo::UpdateAll(); + NoInterpolateView = saved_niv; + + + // now render the main view + float fovratio; + float ratio = WidescreenRatio; + if (WidescreenRatio >= 1.3f) + { + fovratio = 1.333333f; + } + else + { + fovratio = ratio; + } + + SetFixedColormap (player); + + // Check if there's some lights. If not some code can be skipped. + TThinkerIterator it(STAT_DLIGHT); + GLRenderer->mLightCount = ((it.Next()) != NULL); + + sector_t * viewsector = RenderViewpoint(player->camera, NULL, FieldOfView.Degrees, ratio, fovratio, true, true); + + All.Unclock(); +} + +//=========================================================================== +// +// Render the view to a savegame picture +// +//=========================================================================== + +void FGLRenderer::WriteSavePic (player_t *player, FileWriter *file, int width, int height) +{ + GL_IRECT bounds; + + bounds.left=0; + bounds.top=0; + bounds.width=width; + bounds.height=height; + glFlush(); + SetFixedColormap(player); + gl_RenderState.SetVertexBuffer(mVBO); + GLRenderer->mVBO->Reset(); + if (!gl.legacyMode) GLRenderer->mLights->Clear(); + + // Check if there's some lights. If not some code can be skipped. + TThinkerIterator it(STAT_DLIGHT); + GLRenderer->mLightCount = ((it.Next()) != NULL); + + sector_t *viewsector = RenderViewpoint(players[consoleplayer].camera, &bounds, + FieldOfView.Degrees, 1.6f, 1.6f, true, false); + glDisable(GL_STENCIL_TEST); + gl_RenderState.SetFixedColormap(CM_DEFAULT); + gl_RenderState.SetSoftLightLevel(-1); + screen->Begin2D(false); + if (!FGLRenderBuffers::IsEnabled()) + { + DrawBlend(viewsector); + } + CopyToBackbuffer(&bounds, false); + glFlush(); + + byte * scr = (byte *)M_Malloc(width * height * 3); + glReadPixels(0,0,width, height,GL_RGB,GL_UNSIGNED_BYTE,scr); + M_CreatePNG (file, scr + ((height-1) * width * 3), NULL, SS_RGB, width, height, -width*3); + M_Free(scr); +} + + +//=========================================================================== +// +// +// +//=========================================================================== + +struct FGLInterface : public FRenderer +{ + bool UsesColormap() const override; + void PrecacheTexture(FTexture *tex, int cache); + void PrecacheSprite(FTexture *tex, SpriteHits &hits); + void Precache(BYTE *texhitlist, TMap &actorhitlist) override; + void RenderView(player_t *player) override; + void WriteSavePic (player_t *player, FileWriter *file, int width, int height) override; + void StateChanged(AActor *actor) override; + void StartSerialize(FSerializer &arc) override; + void EndSerialize(FSerializer &arc) override; + void RenderTextureView (FCanvasTexture *self, AActor *viewpoint, int fov) override; + sector_t *FakeFlat(sector_t *sec, sector_t *tempsec, int *floorlightlevel, int *ceilinglightlevel, bool back) override; + void SetFogParams(int _fogdensity, PalEntry _outsidefogcolor, int _outsidefogdensity, int _skyfog) override; + void PreprocessLevel() override; + void CleanLevelData() override; + bool RequireGLNodes() override; + + int GetMaxViewPitch(bool down) override; + void ClearBuffer(int color) override; + void Init() override; +}; + +//=========================================================================== +// +// The GL renderer has no use for colormaps so let's +// not create them and save us some time. +// +//=========================================================================== + +bool FGLInterface::UsesColormap() const +{ + return false; +} + +//========================================================================== +// +// DFrameBuffer :: PrecacheTexture +// +//========================================================================== + +void FGLInterface::PrecacheTexture(FTexture *tex, int cache) +{ + if (cache & (FTextureManager::HIT_Wall | FTextureManager::HIT_Flat | FTextureManager::HIT_Sky)) + { + FMaterial * gltex = FMaterial::ValidateTexture(tex, false); + if (gltex) gltex->Precache(); + } +} + +//========================================================================== +// +// DFrameBuffer :: PrecacheSprite +// +//========================================================================== + +void FGLInterface::PrecacheSprite(FTexture *tex, SpriteHits &hits) +{ + FMaterial * gltex = FMaterial::ValidateTexture(tex, true); + if (gltex) gltex->PrecacheList(hits); +} + +//========================================================================== +// +// DFrameBuffer :: Precache +// +//========================================================================== + +void FGLInterface::Precache(BYTE *texhitlist, TMap &actorhitlist) +{ + SpriteHits *spritelist = new SpriteHits[sprites.Size()]; + SpriteHits **spritehitlist = new SpriteHits*[TexMan.NumTextures()]; + TMap::Iterator it(actorhitlist); + TMap::Pair *pair; + BYTE *modellist = new BYTE[Models.Size()]; + memset(modellist, 0, Models.Size()); + memset(spritehitlist, 0, sizeof(SpriteHits**) * TexMan.NumTextures()); + + // this isn't done by the main code so it needs to be done here first: + // check skybox textures and mark the separate faces as used + for (int i = 0; igl_info.bSkybox) + { + FSkyBox *sb = static_cast(tex); + for (int i = 0; i<6; i++) + { + if (sb->faces[i]) + { + int index = sb->faces[i]->id.GetIndex(); + texhitlist[index] |= FTextureManager::HIT_Flat; + } + } + } + } + } + + // Check all used actors. + // 1. mark all sprites associated with its states + // 2. mark all model data and skins associated with its states + while (it.NextPair(pair)) + { + PClassActor *cls = pair->Key; + int gltrans = GLTranslationPalette::GetInternalTranslation(GetDefaultByType(cls)->Translation); + + for (int i = 0; i < cls->NumOwnedStates; i++) + { + spritelist[cls->OwnedStates[i].sprite].Insert(gltrans, true); + FSpriteModelFrame * smf = gl_FindModelFrame(cls, cls->OwnedStates[i].sprite, cls->OwnedStates[i].Frame, false); + if (smf != NULL) + { + for (int i = 0; i < MAX_MODELS_PER_FRAME; i++) + { + if (smf->skinIDs[i].isValid()) + { + texhitlist[smf->skinIDs[i].GetIndex()] |= FTexture::TEX_Flat; + } + else if (smf->modelIDs[i] != -1) + { + Models[smf->modelIDs[i]]->PushSpriteMDLFrame(smf, i); + Models[smf->modelIDs[i]]->AddSkins(texhitlist); + } + if (smf->modelIDs[i] != -1) + { + modellist[smf->modelIDs[i]] = 1; + } + } + } + } + } + + // mark all sprite textures belonging to the marked sprites. + for (int i = (int)(sprites.Size() - 1); i >= 0; i--) + { + if (spritelist[i].CountUsed()) + { + int j, k; + for (j = 0; j < sprites[i].numframes; j++) + { + const spriteframe_t *frame = &SpriteFrames[sprites[i].spriteframes + j]; + + for (k = 0; k < 16; k++) + { + FTextureID pic = frame->Texture[k]; + if (pic.isValid()) + { + spritehitlist[pic.GetIndex()] = &spritelist[i]; + } + } + } + } + } + + // delete everything unused before creating any new resources to avoid memory usage peaks. + + // delete unused models + for (unsigned i = 0; i < Models.Size(); i++) + { + if (!modellist[i]) Models[i]->DestroyVertexBuffer(); + } + + // delete unused textures + int cnt = TexMan.NumTextures(); + for (int i = cnt - 1; i >= 0; i--) + { + FTexture *tex = TexMan.ByIndex(i); + if (tex != nullptr) + { + if (!texhitlist[i]) + { + if (tex->gl_info.Material[0]) tex->gl_info.Material[0]->Clean(true); + } + if (spritehitlist[i] == nullptr || (*spritehitlist[i]).CountUsed() == 0) + { + if (tex->gl_info.Material[1]) tex->gl_info.Material[1]->Clean(true); + } + } + } + + if (gl_precache) + { + // cache all used textures + for (int i = cnt - 1; i >= 0; i--) + { + FTexture *tex = TexMan.ByIndex(i); + if (tex != nullptr) + { + PrecacheTexture(tex, texhitlist[i]); + if (spritehitlist[i] != nullptr && (*spritehitlist[i]).CountUsed() > 0) + { + PrecacheSprite(tex, *spritehitlist[i]); + } + } + } + + // cache all used models + for (unsigned i = 0; i < Models.Size(); i++) + { + if (modellist[i]) + Models[i]->BuildVertexBuffer(); + } + } + + delete[] spritehitlist; + delete[] spritelist; + delete[] modellist; +} + + +//========================================================================== +// +// DFrameBuffer :: StateChanged +// +//========================================================================== + +void FGLInterface::StateChanged(AActor *actor) +{ + gl_SetActorLights(actor); +} + +//=========================================================================== +// +// notify the renderer that serialization of the curent level is about to start/end +// +//=========================================================================== + +void FGLInterface::StartSerialize(FSerializer &arc) +{ + if (arc.BeginObject("glinfo")) + { + arc("fogdensity", fogdensity) + ("outsidefogdensity", outsidefogdensity) + ("skyfog", skyfog) + .EndObject(); + } +} + +void FGLInterface::EndSerialize(FSerializer &arc) +{ + if (arc.isReading()) + { + gl_RecreateAllAttachedLights(); + gl_InitPortals(); + } +} + +//=========================================================================== +// +// Get max. view angle (renderer specific information so it goes here now) +// +//=========================================================================== + +EXTERN_CVAR(Float, maxviewpitch) + +int FGLInterface::GetMaxViewPitch(bool down) +{ + return int(maxviewpitch); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLInterface::ClearBuffer(int color) +{ + PalEntry pe = GPalette.BaseColors[color]; + GLRenderer->mSceneClearColor[0] = pe.r / 255.f; + GLRenderer->mSceneClearColor[1] = pe.g / 255.f; + GLRenderer->mSceneClearColor[2] = pe.b / 255.f; +} + +//=========================================================================== +// +// Render the view to a savegame picture +// +//=========================================================================== + +void FGLInterface::WriteSavePic (player_t *player, FileWriter *file, int width, int height) +{ + GLRenderer->WriteSavePic(player, file, width, height); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLInterface::RenderView(player_t *player) +{ + GLRenderer->RenderView(player); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLInterface::Init() +{ + gl_ParseDefs(); + gl_InitData(); +} + +//=========================================================================== +// +// Camera texture rendering +// +//=========================================================================== +CVAR(Bool, gl_usefb, false , CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +extern TexFilter_s TexFilter[]; + +void FGLInterface::RenderTextureView (FCanvasTexture *tex, AActor *Viewpoint, int FOV) +{ + FMaterial * gltex = FMaterial::ValidateTexture(tex, false); + + int width = gltex->TextureWidth(); + int height = gltex->TextureHeight(); + + gl_fixedcolormap=CM_DEFAULT; + gl_RenderState.SetFixedColormap(CM_DEFAULT); + + if (gl.legacyMode) + { + // In legacy mode, fail if the requested texture is too large. + if (gltex->GetWidth() > screen->GetWidth() || gltex->GetHeight() > screen->GetHeight()) return; + glFlush(); + } + else + { + GLRenderer->StartOffscreen(); + gltex->BindToFrameBuffer(); + } + + GL_IRECT bounds; + bounds.left=bounds.top=0; + bounds.width=FHardwareTexture::GetTexDimension(gltex->GetWidth()); + bounds.height=FHardwareTexture::GetTexDimension(gltex->GetHeight()); + + GLRenderer->RenderViewpoint(Viewpoint, &bounds, FOV, (float)width/height, (float)width/height, false, false); + + if (gl.legacyMode) + { + glFlush(); + gl_RenderState.SetMaterial(gltex, 0, 0, -1, false); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, bounds.width, bounds.height); + } + else + { + GLRenderer->EndOffscreen(); + } + + tex->SetUpdated(); + camtexcount++; +} + +//========================================================================== +// +// +// +//========================================================================== + +sector_t *FGLInterface::FakeFlat(sector_t *sec, sector_t *tempsec, int *floorlightlevel, int *ceilinglightlevel, bool back) +{ + if (floorlightlevel != NULL) + { + *floorlightlevel = sec->GetFloorLight (); + } + if (ceilinglightlevel != NULL) + { + *ceilinglightlevel = sec->GetCeilingLight (); + } + return gl_FakeFlat(sec, tempsec, back); +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FGLInterface::SetFogParams(int _fogdensity, PalEntry _outsidefogcolor, int _outsidefogdensity, int _skyfog) +{ + gl_SetFogParams(_fogdensity, _outsidefogcolor, _outsidefogdensity, _skyfog); +} + +void FGLInterface::PreprocessLevel() +{ + gl_PreprocessLevel(); +} + +void FGLInterface::CleanLevelData() +{ + gl_CleanLevelData(); +} + +bool FGLInterface::RequireGLNodes() +{ + return true; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +FRenderer *gl_CreateInterface() +{ + return new FGLInterface; +} + + diff --git a/src/gl/scene/gl_sky.cpp b/src/gl/scene/gl_sky.cpp new file mode 100644 index 000000000..2a2952548 --- /dev/null +++ b/src/gl/scene/gl_sky.cpp @@ -0,0 +1,396 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "a_sharedglobal.h" +#include "g_level.h" +#include "r_sky.h" +#include "r_state.h" +#include "r_utility.h" +#include "doomdata.h" +#include "portal.h" +#include "gl/gl_functions.h" + +#include "gl/data/gl_data.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_convert.h" + +CVAR(Bool,gl_noskyboxes, false, 0) +extern int skyfog; + +//========================================================================== +// +// Set up the skyinfo struct +// +//========================================================================== + +void GLSkyInfo::init(int sky1, PalEntry FadeColor) +{ + memset(this, 0, sizeof(*this)); + if ((sky1 & PL_SKYFLAT) && (sky1 & (PL_SKYFLAT - 1))) + { + const line_t *l = &lines[(sky1&(PL_SKYFLAT - 1)) - 1]; + const side_t *s = l->sidedef[0]; + int pos; + + if (level.flags & LEVEL_SWAPSKIES && s->GetTexture(side_t::bottom).isValid()) + { + pos = side_t::bottom; + } + else + { + pos = side_t::top; + } + + FTextureID texno = s->GetTexture(pos); + texture[0] = FMaterial::ValidateTexture(texno, false, true); + if (!texture[0] || texture[0]->tex->UseType == FTexture::TEX_Null) goto normalsky; + skytexno1 = texno; + x_offset[0] = s->GetTextureXOffset(pos) * (360.f/65536.f); + y_offset = s->GetTextureYOffset(pos); + mirrored = !l->args[2]; + } + else + { + normalsky: + if (level.flags&LEVEL_DOUBLESKY) + { + texture[1] = FMaterial::ValidateTexture(sky1texture, false, true); + x_offset[1] = GLRenderer->mSky1Pos; + doublesky = true; + } + + if ((level.flags&LEVEL_SWAPSKIES || (sky1 == PL_SKYFLAT) || (level.flags&LEVEL_DOUBLESKY)) && + sky2texture != sky1texture) // If both skies are equal use the scroll offset of the first! + { + texture[0] = FMaterial::ValidateTexture(sky2texture, false, true); + skytexno1 = sky2texture; + sky2 = true; + x_offset[0] = GLRenderer->mSky2Pos; + } + else if (!doublesky) + { + texture[0] = FMaterial::ValidateTexture(sky1texture, false, true); + skytexno1 = sky1texture; + x_offset[0] = GLRenderer->mSky1Pos; + } + } + if (skyfog > 0) + { + fadecolor = FadeColor; + fadecolor.a = 0; + } + else fadecolor = 0; + +} + + +//========================================================================== +// +// Calculate sky texture for ceiling or floor +// +//========================================================================== + +void GLWall::SkyPlane(sector_t *sector, int plane, bool allowreflect) +{ + int ptype = -1; + + FSectorPortal *sportal = sector->ValidatePortal(plane); + if (sportal != nullptr && sportal->mFlags & PORTSF_INSKYBOX) sportal = nullptr; // no recursions, delete it here to simplify the following code + + // Either a regular sky or a skybox with skyboxes disabled + if ((sportal == nullptr && sector->GetTexture(plane) == skyflatnum) || (gl_noskyboxes && sportal != nullptr && sportal->mType == PORTS_SKYVIEWPOINT)) + { + GLSkyInfo skyinfo; + skyinfo.init(sector->sky, Colormap.FadeColor); + ptype = PORTALTYPE_SKY; + sky = UniqueSkies.Get(&skyinfo); + } + else if (sportal != nullptr) + { + switch (sportal->mType) + { + case PORTS_STACKEDSECTORTHING: + case PORTS_PORTAL: + case PORTS_LINKEDPORTAL: + { + FPortal *glport = sector->GetGLPortal(plane); + if (glport != NULL) + { + if (sector->PortalBlocksView(plane)) return; + + if (GLPortal::instack[1 - plane]) return; + ptype = PORTALTYPE_SECTORSTACK; + portal = glport; + } + break; + } + + case PORTS_SKYVIEWPOINT: + case PORTS_HORIZON: + case PORTS_PLANE: + ptype = PORTALTYPE_SKYBOX; + secportal = sportal; + break; + } + } + else if (allowreflect && sector->GetReflect(plane) > 0) + { + if ((plane == sector_t::ceiling && ViewPos.Z > sector->ceilingplane.fD()) || + (plane == sector_t::floor && ViewPos.Z < -sector->floorplane.fD())) return; + ptype = PORTALTYPE_PLANEMIRROR; + planemirror = plane == sector_t::ceiling ? §or->ceilingplane : §or->floorplane; + } + if (ptype != -1) + { + PutPortal(ptype); + } +} + + +//========================================================================== +// +// Calculate sky texture for a line +// +//========================================================================== + +void GLWall::SkyLine(sector_t *fs, line_t *line) +{ + FSectorPortal *secport = line->GetTransferredPortal(); + GLSkyInfo skyinfo; + int ptype; + + // JUSTHIT is used as an indicator that a skybox is in use. + // This is to avoid recursion + + if (!gl_noskyboxes && secport && (secport->mSkybox == nullptr || !(secport->mFlags & PORTSF_INSKYBOX))) + { + ptype = PORTALTYPE_SKYBOX; + secportal = secport; + } + else + { + skyinfo.init(fs->sky, Colormap.FadeColor); + ptype = PORTALTYPE_SKY; + sky = UniqueSkies.Get(&skyinfo); + } + ztop[0] = zceil[0]; + ztop[1] = zceil[1]; + zbottom[0] = zfloor[0]; + zbottom[1] = zfloor[1]; + PutPortal(ptype); +} + + +//========================================================================== +// +// Skies on one sided walls +// +//========================================================================== + +void GLWall::SkyNormal(sector_t * fs,vertex_t * v1,vertex_t * v2) +{ + ztop[0]=ztop[1]=32768.0f; + zbottom[0]=zceil[0]; + zbottom[1]=zceil[1]; + SkyPlane(fs, sector_t::ceiling, true); + + ztop[0]=zfloor[0]; + ztop[1]=zfloor[1]; + zbottom[0]=zbottom[1]=-32768.0f; + SkyPlane(fs, sector_t::floor, true); +} + +//========================================================================== +// +// Upper Skies on two sided walls +// +//========================================================================== + +void GLWall::SkyTop(seg_t * seg,sector_t * fs,sector_t * bs,vertex_t * v1,vertex_t * v2) +{ + if (fs->GetTexture(sector_t::ceiling)==skyflatnum) + { + if (bs->special == GLSector_NoSkyDraw) return; + if (bs->GetTexture(sector_t::ceiling)==skyflatnum) + { + // if the back sector is closed the sky must be drawn! + if (bs->ceilingplane.ZatPoint(v1) > bs->floorplane.ZatPoint(v1) || + bs->ceilingplane.ZatPoint(v2) > bs->floorplane.ZatPoint(v2) || bs->transdoor) + return; + + // one more check for some ugly transparent door hacks + if (!bs->floorplane.isSlope() && !fs->floorplane.isSlope()) + { + if (bs->GetPlaneTexZ(sector_t::floor)==fs->GetPlaneTexZ(sector_t::floor)+1.) + { + FTexture * tex = TexMan(seg->sidedef->GetTexture(side_t::bottom)); + if (!tex || tex->UseType==FTexture::TEX_Null) return; + + // very, very, very ugly special case (See Icarus MAP14) + // It is VERY important that this is only done for a floor height difference of 1 + // or it will cause glitches elsewhere. + tex = TexMan(seg->sidedef->GetTexture(side_t::mid)); + if (tex != NULL && !(seg->linedef->flags & ML_DONTPEGTOP) && + seg->sidedef->GetTextureYOffset(side_t::mid) > 0) + { + ztop[0]=ztop[1]=32768.0f; + zbottom[0]=zbottom[1]= + bs->ceilingplane.ZatPoint(v2) + seg->sidedef->GetTextureYOffset(side_t::mid); + SkyPlane(fs, sector_t::ceiling, false); + return; + } + } + } + } + + ztop[0]=ztop[1]=32768.0f; + + FTexture * tex = TexMan(seg->sidedef->GetTexture(side_t::top)); + if (bs->GetTexture(sector_t::ceiling) != skyflatnum) + + { + zbottom[0]=zceil[0]; + zbottom[1]=zceil[1]; + } + else + { + zbottom[0] = bs->ceilingplane.ZatPoint(v1); + zbottom[1] = bs->ceilingplane.ZatPoint(v2); + flags|=GLWF_SKYHACK; // mid textures on such lines need special treatment! + } + } + else + { + float frontreflect = fs->GetReflect(sector_t::ceiling); + if (frontreflect > 0) + { + float backreflect = bs->GetReflect(sector_t::ceiling); + if (backreflect > 0 && bs->ceilingplane.fD() == fs->ceilingplane.fD()) + { + // Don't add intra-portal line to the portal. + return; + } + } + else + { + int type = fs->GetPortalType(sector_t::ceiling); + if (type == PORTS_STACKEDSECTORTHING || type == PORTS_PORTAL || type == PORTS_LINKEDPORTAL) + { + FPortal *pfront = fs->GetGLPortal(sector_t::ceiling); + FPortal *pback = bs->GetGLPortal(sector_t::ceiling); + if (pfront == NULL || fs->PortalBlocksView(sector_t::ceiling)) return; + if (pfront == pback && !bs->PortalBlocksView(sector_t::ceiling)) return; + } + } + + // stacked sectors + ztop[0] = ztop[1] = 32768.0f; + zbottom[0] = fs->ceilingplane.ZatPoint(v1); + zbottom[1] = fs->ceilingplane.ZatPoint(v2); + + } + + SkyPlane(fs, sector_t::ceiling, true); +} + + +//========================================================================== +// +// Lower Skies on two sided walls +// +//========================================================================== + +void GLWall::SkyBottom(seg_t * seg,sector_t * fs,sector_t * bs,vertex_t * v1,vertex_t * v2) +{ + if (fs->GetTexture(sector_t::floor)==skyflatnum) + { + if (bs->special == GLSector_NoSkyDraw) return; + FTexture * tex = TexMan(seg->sidedef->GetTexture(side_t::bottom)); + + // For lower skies the normal logic only applies to walls with no lower texture! + if (tex->UseType==FTexture::TEX_Null) + { + if (bs->GetTexture(sector_t::floor)==skyflatnum) + { + // if the back sector is closed the sky must be drawn! + if (bs->ceilingplane.ZatPoint(v1) > bs->floorplane.ZatPoint(v1) || + bs->ceilingplane.ZatPoint(v2) > bs->floorplane.ZatPoint(v2)) + return; + + } + else + { + // Special hack for Vrack2b + if (bs->floorplane.ZatPoint(ViewPos) > ViewPos.Z) return; + } + } + zbottom[0]=zbottom[1]=-32768.0f; + + if ((tex && tex->UseType!=FTexture::TEX_Null) || bs->GetTexture(sector_t::floor)!=skyflatnum) + { + ztop[0]=zfloor[0]; + ztop[1]=zfloor[1]; + } + else + { + ztop[0] = bs->floorplane.ZatPoint(v1); + ztop[1] = bs->floorplane.ZatPoint(v2); + flags|=GLWF_SKYHACK; // mid textures on such lines need special treatment! + } + } + else + { + float frontreflect = fs->GetReflect(sector_t::floor); + if (frontreflect > 0) + { + float backreflect = bs->GetReflect(sector_t::floor); + if (backreflect > 0 && bs->floorplane.fD() == fs->floorplane.fD()) + { + // Don't add intra-portal line to the portal. + return; + } + } + else + { + int type = fs->GetPortalType(sector_t::floor); + if (type == PORTS_STACKEDSECTORTHING || type == PORTS_PORTAL || type == PORTS_LINKEDPORTAL) + { + FPortal *pfront = fs->GetGLPortal(sector_t::floor); + FPortal *pback = bs->GetGLPortal(sector_t::floor); + if (pfront == NULL || fs->PortalBlocksView(sector_t::floor)) return; + if (pfront == pback && !bs->PortalBlocksView(sector_t::floor)) return; + } + } + + // stacked sectors + zbottom[0]=zbottom[1]=-32768.0f; + ztop[0] = fs->floorplane.ZatPoint(v1); + ztop[1] = fs->floorplane.ZatPoint(v2); + } + + SkyPlane(fs, sector_t::floor, true); +} + diff --git a/src/gl/scene/gl_skydome.cpp b/src/gl/scene/gl_skydome.cpp new file mode 100644 index 000000000..015b42016 --- /dev/null +++ b/src/gl/scene/gl_skydome.cpp @@ -0,0 +1,560 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2003-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** +** Draws the sky. Loosely based on the JDoom sky and the ZDoomGL 0.66.2 sky. +** +** for FSkyVertexBuffer::SkyVertex only: +**--------------------------------------------------------------------------- +** Copyright 2003 Tim Stump +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ +#include "gl/system/gl_system.h" +#include "doomtype.h" +#include "g_level.h" +#include "sc_man.h" +#include "w_wad.h" +#include "r_state.h" +#include "r_utility.h" +//#include "gl/gl_intern.h" + +#include "gl/system/gl_interface.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_bitmap.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_skyboxtexture.h" +#include "gl/textures/gl_material.h" + + +//----------------------------------------------------------------------------- +// +// Shamelessly lifted from Doomsday (written by Jaakko Keränen) +// also shamelessly lifted from ZDoomGL! ;) +// +//----------------------------------------------------------------------------- + +CVAR(Float, skyoffset, 0, 0) // for testing + +extern int skyfog; + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +FSkyVertexBuffer::FSkyVertexBuffer() +{ + CreateDome(); +} + +FSkyVertexBuffer::~FSkyVertexBuffer() +{ +} + +void FSkyVertexBuffer::BindVBO() +{ + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + if (!gl.legacyMode) + { + glVertexAttribPointer(VATTR_VERTEX, 3, GL_FLOAT, false, sizeof(FSkyVertex), &VSO->x); + glVertexAttribPointer(VATTR_TEXCOORD, 2, GL_FLOAT, false, sizeof(FSkyVertex), &VSO->u); + glVertexAttribPointer(VATTR_COLOR, 4, GL_UNSIGNED_BYTE, true, sizeof(FSkyVertex), &VSO->color); + glEnableVertexAttribArray(VATTR_VERTEX); + glEnableVertexAttribArray(VATTR_TEXCOORD); + glEnableVertexAttribArray(VATTR_COLOR); + glDisableVertexAttribArray(VATTR_VERTEX2); + glDisableVertexAttribArray(VATTR_NORMAL); + } + else + { + glVertexPointer(3, GL_FLOAT, sizeof(FSkyVertex), &VSO->x); + glTexCoordPointer(2, GL_FLOAT, sizeof(FSkyVertex), &VSO->u); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(FSkyVertex), &VSO->color); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + } +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void FSkyVertexBuffer::SkyVertex(int r, int c, bool zflip) +{ + static const FAngle maxSideAngle = 60.f; + static const float scale = 10000.; + + FAngle topAngle = (c / (float)mColumns * 360.f); + FAngle sideAngle = maxSideAngle * (mRows - r) / mRows; + float height = sideAngle.Sin(); + float realRadius = scale * sideAngle.Cos(); + FVector2 pos = topAngle.ToVector(realRadius); + float z = (!zflip) ? scale * height : -scale * height; + + FSkyVertex vert; + + vert.color = r == 0 ? 0xffffff : 0xffffffff; + + // And the texture coordinates. + if (!zflip) // Flipped Y is for the lower hemisphere. + { + vert.u = (-c / (float)mColumns); + vert.v = (r / (float)mRows); + } + else + { + vert.u = (-c / (float)mColumns); + vert.v = 1.0f + ((mRows - r) / (float)mRows); + } + + if (r != 4) z += 300; + // And finally the vertex. + vert.x = -pos.X; // Doom mirrors the sky vertically! + vert.y = z - 1.f; + vert.z = pos.Y; + + mVertices.Push(vert); +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void FSkyVertexBuffer::CreateSkyHemisphere(int hemi) +{ + int r, c; + bool zflip = !!(hemi & SKYHEMI_LOWER); + + mPrimStart.Push(mVertices.Size()); + + for (c = 0; c < mColumns; c++) + { + SkyVertex(1, c, zflip); + } + + // The total number of triangles per hemisphere can be calculated + // as follows: rows * columns * 2 + 2 (for the top cap). + for (r = 0; r < mRows; r++) + { + mPrimStart.Push(mVertices.Size()); + for (c = 0; c <= mColumns; c++) + { + SkyVertex(r + zflip, c, zflip); + SkyVertex(r + 1 - zflip, c, zflip); + } + } +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void FSkyVertexBuffer::CreateDome() +{ + // the first thing we put into the buffer is the fog layer object which is just 4 triangles around the viewpoint. + + mVertices.Reserve(12); + mVertices[0].Set(1.0f, 1.0f, -1.0f); + mVertices[1].Set(1.0f, -1.0f, -1.0f); + mVertices[2].Set(-1.0f, 0.0f, -1.0f); + + mVertices[3].Set(1.0f, 1.0f, -1.0f); + mVertices[4].Set(1.0f, -1.0f, -1.0f); + mVertices[5].Set(0.0f, 0.0f, 1.0f); + + mVertices[6].Set(-1.0f, 0.0f, -1.0f); + mVertices[7].Set(1.0f, 1.0f, -1.0f); + mVertices[8].Set(0.0f, 0.0f, 1.0f); + + mVertices[9].Set(1.0f, -1.0f, -1.0f); + mVertices[10].Set(-1.0f, 0.0f, -1.0f); + mVertices[11].Set(0.0f, 0.0f, 1.0f); + + mColumns = 128; + mRows = 4; + CreateSkyHemisphere(SKYHEMI_UPPER); + CreateSkyHemisphere(SKYHEMI_LOWER); + mPrimStart.Push(mVertices.Size()); + + mSideStart = mVertices.Size(); + mFaceStart[0] = mSideStart + 10; + mFaceStart[1] = mFaceStart[0] + 4; + mFaceStart[2] = mFaceStart[1] + 4; + mFaceStart[3] = mFaceStart[2] + 4; + mFaceStart[4] = mFaceStart[3] + 4; + mFaceStart[5] = mFaceStart[4] + 4; + mFaceStart[6] = mFaceStart[5] + 4; + mVertices.Reserve(10 + 7*4); + FSkyVertex *ptr = &mVertices[mSideStart]; + + // all sides + ptr[0].SetXYZ(128.f, 128.f, -128.f, 0, 0); + ptr[1].SetXYZ(128.f, -128.f, -128.f, 0, 1); + ptr[2].SetXYZ(-128.f, 128.f, -128.f, 0.25f, 0); + ptr[3].SetXYZ(-128.f, -128.f, -128.f, 0.25f, 1); + ptr[4].SetXYZ(-128.f, 128.f, 128.f, 0.5f, 0); + ptr[5].SetXYZ(-128.f, -128.f, 128.f, 0.5f, 1); + ptr[6].SetXYZ(128.f, 128.f, 128.f, 0.75f, 0); + ptr[7].SetXYZ(128.f, -128.f, 128.f, 0.75f, 1); + ptr[8].SetXYZ(128.f, 128.f, -128.f, 1, 0); + ptr[9].SetXYZ(128.f, -128.f, -128.f, 1, 1); + + // north face + ptr[10].SetXYZ(128.f, 128.f, -128.f, 0, 0); + ptr[11].SetXYZ(-128.f, 128.f, -128.f, 1, 0); + ptr[12].SetXYZ(128.f, -128.f, -128.f, 0, 1); + ptr[13].SetXYZ(-128.f, -128.f, -128.f, 1, 1); + + // east face + ptr[14].SetXYZ(-128.f, 128.f, -128.f, 0, 0); + ptr[15].SetXYZ(-128.f, 128.f, 128.f, 1, 0); + ptr[16].SetXYZ(-128.f, -128.f, -128.f, 0, 1); + ptr[17].SetXYZ(-128.f, -128.f, 128.f, 1, 1); + + // south face + ptr[18].SetXYZ(-128.f, 128.f, 128.f, 0, 0); + ptr[19].SetXYZ(128.f, 128.f, 128.f, 1, 0); + ptr[20].SetXYZ(-128.f, -128.f, 128.f, 0, 1); + ptr[21].SetXYZ(128.f, -128.f, 128.f, 1, 1); + + // west face + ptr[22].SetXYZ(128.f, 128.f, 128.f, 0, 0); + ptr[23].SetXYZ(128.f, 128.f, -128.f, 1, 0); + ptr[24].SetXYZ(128.f, -128.f, 128.f, 0, 1); + ptr[25].SetXYZ(128.f, -128.f, -128.f, 1, 1); + + // bottom face + ptr[26].SetXYZ(128.f, -128.f, -128.f, 0, 0); + ptr[27].SetXYZ(-128.f, -128.f, -128.f, 1, 0); + ptr[28].SetXYZ(128.f, -128.f, 128.f, 0, 1); + ptr[29].SetXYZ(-128.f, -128.f, 128.f, 1, 1); + + // top face + ptr[30].SetXYZ(128.f, 128.f, -128.f, 0, 0); + ptr[31].SetXYZ(-128.f, 128.f, -128.f, 1, 0); + ptr[32].SetXYZ(128.f, 128.f, 128.f, 0, 1); + ptr[33].SetXYZ(-128.f, 128.f, 128.f, 1, 1); + + // top face flipped + ptr[34].SetXYZ(128.f, 128.f, -128.f, 0, 1); + ptr[35].SetXYZ(-128.f, 128.f, -128.f, 1, 1); + ptr[36].SetXYZ(128.f, 128.f, 128.f, 0, 0); + ptr[37].SetXYZ(-128.f, 128.f, 128.f, 1, 0); + + glBindBuffer(GL_ARRAY_BUFFER, vbo_id); + glBufferData(GL_ARRAY_BUFFER, mVertices.Size() * sizeof(FSkyVertex), &mVertices[0], GL_STATIC_DRAW); +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +inline void FSkyVertexBuffer::RenderRow(int prim, int row) +{ + glDrawArrays(prim, mPrimStart[row], mPrimStart[row + 1] - mPrimStart[row]); +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void FSkyVertexBuffer::RenderDome(FMaterial *tex, int mode) +{ + int rc = mRows + 1; + + // The caps only get drawn for the main layer but not for the overlay. + if (mode == SKYMODE_MAINLAYER && tex != NULL) + { + PalEntry pe = tex->tex->GetSkyCapColor(false); + gl_RenderState.SetObjectColor(pe); + gl_RenderState.EnableTexture(false); + gl_RenderState.Apply(); + RenderRow(GL_TRIANGLE_FAN, 0); + + pe = tex->tex->GetSkyCapColor(true); + gl_RenderState.SetObjectColor(pe); + gl_RenderState.Apply(); + RenderRow(GL_TRIANGLE_FAN, rc); + gl_RenderState.EnableTexture(true); + // The color array can only be activated now if this is drawn without shader + if (gl.legacyMode) + { + glEnableClientState(GL_COLOR_ARRAY); + } + } + gl_RenderState.SetObjectColor(0xffffffff); + gl_RenderState.Apply(); + for (int i = 1; i <= mRows; i++) + { + RenderRow(GL_TRIANGLE_STRIP, i); + RenderRow(GL_TRIANGLE_STRIP, rc + i); + } +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void RenderDome(FMaterial * tex, float x_offset, float y_offset, bool mirror, int mode) +{ + int texh = 0; + int texw = 0; + + // 57 world units roughly represent one sky texel for the glTranslate call. + const float skyoffsetfactor = 57; + + if (tex) + { + gl_RenderState.SetMaterial(tex, CLAMP_NONE, 0, -1, false); + texw = tex->TextureWidth(); + texh = tex->TextureHeight(); + gl_RenderState.EnableModelMatrix(true); + + gl_RenderState.mModelMatrix.loadIdentity(); + gl_RenderState.mModelMatrix.rotate(-180.0f + x_offset, 0.f, 1.f, 0.f); + + float xscale = texw < 1024.f ? floor(1024.f / float(texw)) : 1.f; + float yscale = 1.f; + if (texh < 128) + { + // smaller sky textures must be tiled. We restrict it to 128 sky pixels, though + gl_RenderState.mModelMatrix.translate(0.f, -1250.f, 0.f); + gl_RenderState.mModelMatrix.scale(1.f, 128 / 230.f, 1.f); + yscale = 128 / texh; // intentionally left as integer. + } + else if (texh < 200) + { + gl_RenderState.mModelMatrix.translate(0.f, -1250.f, 0.f); + gl_RenderState.mModelMatrix.scale(1.f, texh / 230.f, 1.f); + } + else if (texh <= 240) + { + gl_RenderState.mModelMatrix.translate(0.f, (200 - texh + tex->tex->SkyOffset + skyoffset)*skyoffsetfactor, 0.f); + gl_RenderState.mModelMatrix.scale(1.f, 1.f + ((texh - 200.f) / 200.f) * 1.17f, 1.f); + } + else + { + gl_RenderState.mModelMatrix.translate(0.f, (-40 + tex->tex->SkyOffset + skyoffset)*skyoffsetfactor, 0.f); + gl_RenderState.mModelMatrix.scale(1.f, 1.2f * 1.17f, 1.f); + yscale = 240.f / texh; + } + gl_RenderState.EnableTextureMatrix(true); + gl_RenderState.mTextureMatrix.loadIdentity(); + gl_RenderState.mTextureMatrix.scale(mirror ? -xscale : xscale, yscale, 1.f); + gl_RenderState.mTextureMatrix.translate(1.f, y_offset / texh, 1.f); + } + + GLRenderer->mSkyVBO->RenderDome(tex, mode); + gl_RenderState.EnableTextureMatrix(false); + gl_RenderState.EnableModelMatrix(false); +} + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +static void RenderBox(FTextureID texno, FMaterial * gltex, float x_offset, bool sky2) +{ + FSkyBox * sb = static_cast(gltex->tex); + int faces; + FMaterial * tex; + + gl_RenderState.EnableModelMatrix(true); + gl_RenderState.mModelMatrix.loadIdentity(); + + if (!sky2) + gl_RenderState.mModelMatrix.rotate(-180.0f+x_offset, glset.skyrotatevector.X, glset.skyrotatevector.Z, glset.skyrotatevector.Y); + else + gl_RenderState.mModelMatrix.rotate(-180.0f+x_offset, glset.skyrotatevector2.X, glset.skyrotatevector2.Z, glset.skyrotatevector2.Y); + + if (sb->faces[5]) + { + faces=4; + + // north + tex = FMaterial::ValidateTexture(sb->faces[0], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(0), 4); + + // east + tex = FMaterial::ValidateTexture(sb->faces[1], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(1), 4); + + // south + tex = FMaterial::ValidateTexture(sb->faces[2], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(2), 4); + + // west + tex = FMaterial::ValidateTexture(sb->faces[3], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(3), 4); + } + else + { + faces=1; + tex = FMaterial::ValidateTexture(sb->faces[0], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(-1), 10); + } + + // top + tex = FMaterial::ValidateTexture(sb->faces[faces], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(sb->fliptop? 6:5), 4); + + // bottom + tex = FMaterial::ValidateTexture(sb->faces[faces+1], false); + gl_RenderState.SetMaterial(tex, CLAMP_XY, 0, -1, false); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLE_STRIP, GLRenderer->mSkyVBO->FaceStart(4), 4); + + gl_RenderState.EnableModelMatrix(false); +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- +void GLSkyPortal::DrawContents() +{ + bool drawBoth = false; + + // We have no use for Doom lighting special handling here, so disable it for this function. + int oldlightmode = glset.lightmode; + if (glset.lightmode == 8) + { + glset.lightmode = 2; + gl_RenderState.SetSoftLightLevel(-1); + } + + + gl_RenderState.ResetColor(); + gl_RenderState.EnableFog(false); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + bool oldClamp = gl_RenderState.SetDepthClamp(true); + + gl_MatrixStack.Push(gl_RenderState.mViewMatrix); + GLRenderer->SetupView(0, 0, 0, ViewAngle, !!(MirrorFlag & 1), !!(PlaneMirrorFlag & 1)); + + gl_RenderState.SetVertexBuffer(GLRenderer->mSkyVBO); + if (origin->texture[0] && origin->texture[0]->tex->gl_info.bSkybox) + { + RenderBox(origin->skytexno1, origin->texture[0], origin->x_offset[0], origin->sky2); + } + else + { + if (origin->texture[0]==origin->texture[1] && origin->doublesky) origin->doublesky=false; + + if (origin->texture[0]) + { + gl_RenderState.SetTextureMode(TM_OPAQUE); + RenderDome(origin->texture[0], origin->x_offset[0], origin->y_offset, origin->mirrored, FSkyVertexBuffer::SKYMODE_MAINLAYER); + gl_RenderState.SetTextureMode(TM_MODULATE); + } + + gl_RenderState.AlphaFunc(GL_GREATER, 0.f); + + if (origin->doublesky && origin->texture[1]) + { + RenderDome(origin->texture[1], origin->x_offset[1], origin->y_offset, false, FSkyVertexBuffer::SKYMODE_SECONDLAYER); + } + + if (skyfog>0 && gl_fixedcolormap == CM_DEFAULT && (origin->fadecolor & 0xffffff) != 0) + { + PalEntry FadeColor = origin->fadecolor; + FadeColor.a = clamp(skyfog, 0, 255); + + gl_RenderState.EnableTexture(false); + gl_RenderState.SetObjectColor(FadeColor); + gl_RenderState.Apply(); + glDrawArrays(GL_TRIANGLES, 0, 12); + gl_RenderState.EnableTexture(true); + gl_RenderState.SetObjectColor(0xffffffff); + } + } + gl_RenderState.SetVertexBuffer(GLRenderer->mVBO); + gl_MatrixStack.Pop(gl_RenderState.mViewMatrix); + gl_RenderState.ApplyMatrices(); + glset.lightmode = oldlightmode; + gl_RenderState.SetDepthClamp(oldClamp); +} + diff --git a/src/gl/scene/gl_sprite.cpp b/src/gl/scene/gl_sprite.cpp new file mode 100644 index 000000000..f79549a39 --- /dev/null +++ b/src/gl/scene/gl_sprite.cpp @@ -0,0 +1,1215 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_sprite.cpp +** Sprite/Particle rendering +** +*/ + +#include "gl/system/gl_system.h" +#include "p_local.h" +#include "p_effect.h" +#include "g_level.h" +#include "doomstat.h" +#include "gl/gl_functions.h" +#include "r_defs.h" +#include "r_sky.h" +#include "r_utility.h" +#include "a_pickups.h" +#include "d_player.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/models/gl_models.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_quaddrawer.h" + +CVAR(Bool, gl_usecolorblending, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +CVAR(Bool, gl_spritebrightfog, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG); +CVAR(Bool, gl_sprite_blend, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG); +CVAR(Int, gl_spriteclip, 1, CVAR_ARCHIVE) +CVAR(Float, gl_sclipthreshold, 10.0, CVAR_ARCHIVE) +CVAR(Float, gl_sclipfactor, 1.8, CVAR_ARCHIVE) +CVAR(Int, gl_particles_style, 2, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) // 0 = square, 1 = round, 2 = smooth +CVAR(Int, gl_billboard_mode, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Bool, gl_billboard_faces_camera, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Bool, gl_billboard_particles, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Int, gl_enhanced_nv_stealth, 3, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CUSTOM_CVAR(Int, gl_fuzztype, 0, CVAR_ARCHIVE) +{ + if (self < 0 || self > 7) self = 0; +} + +EXTERN_CVAR (Float, transsouls) + +extern TArray sprites; +extern TArray SpriteFrames; +extern TArray BloodTranslationColors; + +enum HWRenderStyle +{ + STYLEHW_Normal, // default + STYLEHW_Solid, // drawn solid (needs special treatment for sprites) + STYLEHW_NoAlphaTest, // disable alpha test +}; + + +void gl_SetRenderStyle(FRenderStyle style, bool drawopaque, bool allowcolorblending) +{ + int tm, sb, db, be; + + gl_GetRenderStyle(style, drawopaque, allowcolorblending, &tm, &sb, &db, &be); + gl_RenderState.BlendEquation(be); + gl_RenderState.BlendFunc(sb, db); + gl_RenderState.SetTextureMode(tm); +} + +CVAR(Bool, gl_nolayer, false, 0) + +static const float LARGE_VALUE = 1e19f; + + +//========================================================================== +// +// +// +//========================================================================== + +void GLSprite::CalculateVertices(FVector3 *v) +{ + if (actor != nullptr && (actor->renderflags & RF_SPRITETYPEMASK) == RF_FLATSPRITE) + { + Matrix3x4 mat; + mat.MakeIdentity(); + + // [MC] Rotate around the center or offsets given to the sprites. + // Counteract any existing rotations, then rotate the angle. + // Tilt the actor up or down based on pitch (increase 'somersaults' forward). + // Then counteract the roll and DO A BARREL ROLL. + + FAngle pitch = (float)-actor->Angles.Pitch.Degrees; + pitch.Normalized180(); + + mat.Translate(x, z, y); + mat.Rotate(0, 1, 0, 270. - actor->Angles.Yaw.Degrees); + mat.Rotate(1, 0, 0, pitch.Degrees); + + if (actor->renderflags & RF_ROLLCENTER) + { + float cx = (x1 + x2) * 0.5; + float cy = (y1 + y2) * 0.5; + + mat.Translate(cx - x, 0, cy - y); + mat.Rotate(0, 1, 0, - actor->Angles.Roll.Degrees); + mat.Translate(-cx, -z, -cy); + } + else + { + mat.Rotate(0, 1, 0, - actor->Angles.Roll.Degrees); + mat.Translate(-x, -z, -y); + } + v[0] = mat * FVector3(x2, z, y2); + v[1] = mat * FVector3(x1, z, y2); + v[2] = mat * FVector3(x2, z, y1); + v[3] = mat * FVector3(x1, z, y1); + + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + return; + } + + // [BB] Billboard stuff + const bool drawWithXYBillboard = ((particle && gl_billboard_particles) || (!(actor && actor->renderflags & RF_FORCEYBILLBOARD) + //&& GLRenderer->mViewActor != NULL + && (gl_billboard_mode == 1 || (actor && actor->renderflags & RF_FORCEXYBILLBOARD)))); + + const bool drawBillboardFacingCamera = gl_billboard_faces_camera; + // [Nash] has +ROLLSPRITE + const bool drawRollSpriteActor = (actor != nullptr && actor->renderflags & RF_ROLLSPRITE); + + + // [fgsfds] check sprite type mask + DWORD spritetype = (DWORD)-1; + if (actor != nullptr) spritetype = actor->renderflags & RF_SPRITETYPEMASK; + + // [Nash] is a flat sprite + const bool isFlatSprite = (actor != nullptr) && (spritetype == RF_WALLSPRITE || spritetype == RF_FLATSPRITE); + const bool useOffsets = (actor != nullptr) && !(actor->renderflags & RF_ROLLCENTER); + + // [Nash] check for special sprite drawing modes + if (drawWithXYBillboard || drawBillboardFacingCamera || drawRollSpriteActor || isFlatSprite) + { + // Compute center of sprite + float xcenter = (x1 + x2)*0.5; + float ycenter = (y1 + y2)*0.5; + float zcenter = (z1 + z2)*0.5; + float xx = -xcenter + x; + float zz = -zcenter + z; + float yy = -ycenter + y; + Matrix3x4 mat; + mat.MakeIdentity(); + mat.Translate(xcenter, zcenter, ycenter); // move to sprite center + + // Order of rotations matters. Perform yaw rotation (Y, face camera) before pitch (X, tilt up/down). + if (drawBillboardFacingCamera && !isFlatSprite) + { + // [CMB] Rotate relative to camera XY position, not just camera direction, + // which is nicer in VR + float xrel = xcenter - ViewPos.X; + float yrel = ycenter - ViewPos.Y; + float absAngleDeg = RAD2DEG(atan2(-yrel, xrel)); + float counterRotationDeg = 270. - GLRenderer->mAngles.Yaw.Degrees; // counteracts existing sprite rotation + float relAngleDeg = counterRotationDeg + absAngleDeg; + + mat.Rotate(0, 1, 0, relAngleDeg); + } + + // [fgsfds] calculate yaw vectors + float yawvecX = 0, yawvecY = 0, rollDegrees = 0; + float angleRad = (270. - GLRenderer->mAngles.Yaw).Radians(); + if (actor) rollDegrees = actor->Angles.Roll.Degrees; + if (isFlatSprite) + { + yawvecX = actor->Angles.Yaw.Cos(); + yawvecY = actor->Angles.Yaw.Sin(); + } + + // [fgsfds] Rotate the sprite about the sight vector (roll) + if (spritetype == RF_WALLSPRITE) + { + mat.Rotate(0, 1, 0, 0); + if (drawRollSpriteActor) + { + if (useOffsets) mat.Translate(xx, zz, yy); + mat.Rotate(yawvecX, 0, yawvecY, rollDegrees); + if (useOffsets) mat.Translate(-xx, -zz, -yy); + } + } + else if (drawRollSpriteActor) + { + if (useOffsets) mat.Translate(xx, zz, yy); + if (drawWithXYBillboard) + { + mat.Rotate(-sin(angleRad), 0, cos(angleRad), -GLRenderer->mAngles.Pitch.Degrees); + } + mat.Rotate(cos(angleRad), 0, sin(angleRad), rollDegrees); + if (useOffsets) mat.Translate(-xx, -zz, -yy); + } + else if (drawWithXYBillboard) + { + // Rotate the sprite about the vector starting at the center of the sprite + // triangle strip and with direction orthogonal to where the player is looking + // in the x/y plane. + mat.Rotate(-sin(angleRad), 0, cos(angleRad), -GLRenderer->mAngles.Pitch.Degrees); + } + + mat.Translate(-xcenter, -zcenter, -ycenter); // retreat from sprite center + v[0] = mat * FVector3(x1, z1, y1); + v[1] = mat * FVector3(x2, z1, y2); + v[2] = mat * FVector3(x1, z2, y1); + v[3] = mat * FVector3(x2, z2, y2); + } + else // traditional "Y" billboard mode + { + v[0] = FVector3(x1, z1, y1); + v[1] = FVector3(x2, z1, y2); + v[2] = FVector3(x1, z2, y1); + v[3] = FVector3(x2, z2, y2); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLSprite::Draw(int pass) +{ + if (pass == GLPASS_DECALS || pass == GLPASS_LIGHTSONLY) return; + + bool additivefog = false; + bool foglayer = false; + int rel = fullbright? 0 : getExtraLight(); + + if (pass==GLPASS_TRANSLUCENT) + { + // The translucent pass requires special setup for the various modes. + + // for special render styles brightmaps would not look good - especially for subtractive. + if (RenderStyle.BlendOp != STYLEOP_Add) + { + gl_RenderState.EnableBrightmap(false); + } + + gl_SetRenderStyle(RenderStyle, false, + // The rest of the needed checks are done inside gl_SetRenderStyle + trans > 1.f - FLT_EPSILON && gl_usecolorblending && gl_fixedcolormap == CM_DEFAULT && actor && + fullbright && gltexture && !gltexture->GetTransparent()); + + if (hw_styleflags == STYLEHW_NoAlphaTest) + { + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + } + else + { + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + } + + if (RenderStyle.BlendOp == STYLEOP_Shadow) + { + float fuzzalpha=0.44f; + float minalpha=0.1f; + + // fog + fuzz don't work well without some fiddling with the alpha value! + if (!gl_isBlack(Colormap.FadeColor)) + { + float dist=Dist2(ViewPos.X, ViewPos.Y, x,y); + + if (!Colormap.FadeColor.a) Colormap.FadeColor.a=clamp(255-lightlevel,60,255); + + // this value was determined by trial and error and is scale dependent! + float factor=0.05f+exp(-Colormap.FadeColor.a*dist/62500.f); + fuzzalpha*=factor; + minalpha*=factor; + } + + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + gl_RenderState.SetColor(0.2f,0.2f,0.2f,fuzzalpha, Colormap.desaturation); + additivefog = true; + } + else if (RenderStyle.BlendOp == STYLEOP_Add && RenderStyle.DestAlpha == STYLEALPHA_One) + { + additivefog = true; + } + } + else if (modelframe == nullptr) + { + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + } + if (RenderStyle.BlendOp!=STYLEOP_Shadow) + { + if (gl_lights && GLRenderer->mLightCount && !gl_fixedcolormap && !fullbright) + { + gl_SetDynSpriteLight(gl_light_sprites ? actor : NULL, gl_light_particles ? particle : NULL); + } + gl_SetColor(lightlevel, rel, Colormap, trans); + } + gl_RenderState.SetObjectColor(ThingColor); + + if (gl_isBlack(Colormap.FadeColor)) foglevel=lightlevel; + + if (RenderStyle.Flags & STYLEF_FadeToBlack) + { + Colormap.FadeColor=0; + additivefog = true; + } + + if (RenderStyle.BlendOp == STYLEOP_RevSub || RenderStyle.BlendOp == STYLEOP_Sub) + { + if (!modelframe) + { + // non-black fog with subtractive style needs special treatment + if (!gl_isBlack(Colormap.FadeColor)) + { + foglayer = true; + // Due to the two-layer approach we need to force an alpha test that lets everything pass + gl_RenderState.AlphaFunc(GL_GREATER, 0); + } + } + else RenderStyle.BlendOp = STYLEOP_Fuzz; // subtractive with models is not going to work. + } + + if (!foglayer) gl_SetFog(foglevel, rel, &Colormap, additivefog); + else + { + gl_RenderState.EnableFog(false); + gl_RenderState.SetFog(0, 0); + } + + if (gltexture) gl_RenderState.SetMaterial(gltexture, CLAMP_XY, translation, OverrideShader, !!(RenderStyle.Flags & STYLEF_RedIsAlpha)); + else if (!modelframe) gl_RenderState.EnableTexture(false); + + //gl_SetColor(lightlevel, rel, Colormap, trans); + + unsigned int iter = lightlist? lightlist->Size() : 1; + bool clipping = false; + if (lightlist || topclip != LARGE_VALUE || bottomclip != -LARGE_VALUE) + { + clipping = true; + gl_RenderState.EnableSplit(true); + } + + secplane_t bottomp = { { 0, 0, -1. }, bottomclip }; + secplane_t topp = { { 0, 0, -1. }, topclip }; + for (unsigned i = 0; i < iter; i++) + { + if (lightlist) + { + // set up the light slice + secplane_t *topplane = i == 0 ? &topp : &(*lightlist)[i].plane; + secplane_t *lowplane = i == (*lightlist).Size() - 1 ? &bottomp : &(*lightlist)[i + 1].plane; + + int thislight = (*lightlist)[i].caster != NULL ? gl_ClampLight(*(*lightlist)[i].p_lightlevel) : lightlevel; + int thisll = actor == nullptr? thislight : (uint8_t)gl_CheckSpriteGlow(actor->Sector, thislight, actor->InterpolatedPosition(r_TicFracF)); + + FColormap thiscm; + thiscm.FadeColor = Colormap.FadeColor; + thiscm.CopyFrom3DLight(&(*lightlist)[i]); + if (glset.nocoloredspritelighting) + { + thiscm.Decolorize(); + } + + gl_SetColor(thisll, rel, thiscm, trans); + if (!foglayer) + { + gl_SetFog(thislight, rel, &thiscm, additivefog); + } + gl_RenderState.SetSplitPlanes(*topplane, *lowplane); + } + else if (clipping) + { + gl_RenderState.SetSplitPlanes(topp, bottomp); + } + + if (!modelframe) + { + gl_RenderState.Apply(); + + FVector3 v[4]; + gl_RenderState.SetNormal(0, 0, 0); + CalculateVertices(v); + + FQuadDrawer qd; + qd.Set(0, v[0][0], v[0][1], v[0][2], ul, vt); + qd.Set(1, v[1][0], v[1][1], v[1][2], ur, vt); + qd.Set(2, v[2][0], v[2][1], v[2][2], ul, vb); + qd.Set(3, v[3][0], v[3][1], v[3][2], ur, vb); + qd.Render(GL_TRIANGLE_STRIP); + + if (foglayer) + { + // If we get here we know that we have colored fog and no fixed colormap. + gl_SetFog(foglevel, rel, &Colormap, additivefog); + gl_RenderState.SetFixedColormap(CM_FOGLAYER); + gl_RenderState.BlendEquation(GL_FUNC_ADD); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.Apply(); + qd.Render(GL_TRIANGLE_STRIP); + gl_RenderState.SetFixedColormap(CM_DEFAULT); + } + } + else + { + gl_RenderModel(this); + } + } + + if (clipping) + { + gl_RenderState.EnableSplit(false); + } + + if (pass==GLPASS_TRANSLUCENT) + { + gl_RenderState.EnableBrightmap(true); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.BlendEquation(GL_FUNC_ADD); + gl_RenderState.SetTextureMode(TM_MODULATE); + if (actor != nullptr && (actor->renderflags & RF_SPRITETYPEMASK) == RF_FLATSPRITE) + { + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + } + } + else if (modelframe == nullptr) + { + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + } + + gl_RenderState.SetObjectColor(0xffffffff); + gl_RenderState.EnableTexture(true); + gl_RenderState.SetDynLight(0,0,0); +} + + +//========================================================================== +// +// +// +//========================================================================== +inline void GLSprite::PutSprite(bool translucent) +{ + int list; + // [BB] Allow models to be drawn in the GLDL_TRANSLUCENT pass. + if (translucent || actor == nullptr || (!modelframe && (actor->renderflags & RF_SPRITETYPEMASK) != RF_WALLSPRITE)) + { + list = GLDL_TRANSLUCENT; + } + else + { + list = GLDL_MODELS; + } + gl_drawinfo->drawlists[list].AddSprite(this); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLSprite::SplitSprite(sector_t * frontsector, bool translucent) +{ + GLSprite copySprite; + double lightbottom; + unsigned int i; + bool put=false; + TArray & lightlist=frontsector->e->XFloor.lightlist; + + for(i=0;ifloorplane.ZatPoint(actor); + + if (lightbottom>8; + copySprite.Colormap.LightColor.g=(copySprite.Colormap.LightColor.g*ThingColor.g)>>8; + copySprite.Colormap.LightColor.b=(copySprite.Colormap.LightColor.b*ThingColor.b)>>8; + } + + z1=copySprite.z2=lightbottom; + vt=copySprite.vb=copySprite.vt+ + (lightbottom-copySprite.z1)*(copySprite.vb-copySprite.vt)/(z2-copySprite.z1); + copySprite.PutSprite(translucent); + put=true; + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLSprite::PerformSpriteClipAdjustment(AActor *thing, const DVector2 &thingpos, float spriteheight) +{ + const float NO_VAL = 100000000.0f; + bool clipthing = (thing->player || thing->flags3&MF3_ISMONSTER || thing->IsKindOf(RUNTIME_CLASS(AInventory))) && (thing->flags&MF_ICECORPSE || !(thing->flags&MF_CORPSE)); + bool smarterclip = !clipthing && gl_spriteclip == 3; + if (clipthing || gl_spriteclip > 1) + { + + float btm = NO_VAL; + float top = -NO_VAL; + extsector_t::xfloor &x = thing->Sector->e->XFloor; + + if (x.ffloors.Size()) + { + for (unsigned int i = 0; i < x.ffloors.Size(); i++) + { + F3DFloor * ff = x.ffloors[i]; + float floorh = ff->top.plane->ZatPoint(thingpos); + float ceilingh = ff->bottom.plane->ZatPoint(thingpos); + if (floorh == thing->floorz) + { + btm = floorh; + } + if (ceilingh == thing->ceilingz) + { + top = ceilingh; + } + if (btm != NO_VAL && top != -NO_VAL) + { + break; + } + } + } + else if (thing->Sector->heightsec && !(thing->Sector->heightsec->MoreFlags & SECF_IGNOREHEIGHTSEC)) + { + if (thing->flags2&MF2_ONMOBJ && thing->floorz == + thing->Sector->heightsec->floorplane.ZatPoint(thingpos)) + { + btm = thing->floorz; + top = thing->ceilingz; + } + } + if (btm == NO_VAL) + btm = thing->Sector->floorplane.ZatPoint(thing) - thing->Floorclip; + if (top == NO_VAL) + top = thing->Sector->ceilingplane.ZatPoint(thingpos); + + // +/-1 to account for the one pixel empty frame around the sprite. + float diffb = (z2+1) - btm; + float difft = (z1-1) - top; + if (diffb >= 0 /*|| !gl_sprite_clip_to_floor*/) diffb = 0; + // Adjust sprites clipping into ceiling and adjust clipping adjustment for tall graphics + if (smarterclip) + { + // Reduce slightly clipping adjustment of corpses + if (thing->flags & MF_CORPSE || spriteheight > fabs(diffb)) + { + float ratio = clamp((fabs(diffb) * (float)gl_sclipfactor / (spriteheight + 1)), 0.5, 1.0); + diffb *= ratio; + } + if (!diffb) + { + if (difft <= 0) difft = 0; + if (difft >= (float)gl_sclipthreshold) + { + // dumb copy of the above. + if (!(thing->flags3&MF3_ISMONSTER) || (thing->flags&MF_NOGRAVITY) || (thing->flags&MF_CORPSE) || difft > (float)gl_sclipthreshold) + { + difft = 0; + } + } + if (spriteheight > fabs(difft)) + { + float ratio = clamp((fabs(difft) * (float)gl_sclipfactor / (spriteheight + 1)), 0.5, 1.0); + difft *= ratio; + } + z2 -= difft; + z1 -= difft; + } + } + if (diffb <= (0 - (float)gl_sclipthreshold)) // such a large displacement can't be correct! + { + // for living monsters standing on the floor allow a little more. + if (!(thing->flags3&MF3_ISMONSTER) || (thing->flags&MF_NOGRAVITY) || (thing->flags&MF_CORPSE) || diffb < (-1.8*(float)gl_sclipthreshold)) + { + diffb = 0; + } + } + z2 -= diffb; + z1 -= diffb; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLSprite::Process(AActor* thing, sector_t * sector, int thruportal) +{ + sector_t rs; + sector_t * rendersector; + + // Don't waste time projecting sprites that are definitely not visible. + if (thing == nullptr || thing->sprite == 0 || !thing->IsVisibleToPlayer() || !thing->IsInsideVisibleAngles()) + { + return; + } + + if (thing->renderflags & RF_INVISIBLE || !thing->RenderStyle.IsVisible(thing->Alpha)) + { + if (!(thing->flags & MF_STEALTH) || !gl_fixedcolormap || !gl_enhanced_nightvision || thing == camera) + return; + } + + int spritenum = thing->sprite; + DVector2 sprscale = thing->Scale; + if (thing->player != NULL) + { + P_CheckPlayerSprite(thing, spritenum, sprscale); + } + + // If this thing is in a map section that's not in view it can't possibly be visible + if (!thruportal && !(currentmapsection[thing->subsector->mapsection >> 3] & (1 << (thing->subsector->mapsection & 7)))) return; + + // [RH] Interpolate the sprite's position to make it look smooth + DVector3 thingpos = thing->InterpolatedPosition(r_TicFracF); + if (thruportal == 1) thingpos += Displacements.getOffset(thing->Sector->PortalGroup, sector->PortalGroup); + + // Too close to the camera. This doesn't look good if it is a sprite. + if (fabs(thingpos.X - ViewPos.X) < 2 && fabs(thingpos.Y - ViewPos.Y) < 2) + { + if (ViewPos.Z >= thingpos.Z - 2 && ViewPos.Z <= thingpos.Z + thing->Height + 2) + { + // exclude vertically moving objects from this check. + if (!thing->Vel.isZero()) + { + if (!gl_FindModelFrame(thing->GetClass(), spritenum, thing->frame, false)) + { + return; + } + } + } + } + + // don't draw first frame of a player missile + if (thing->flags&MF_MISSILE) + { + if (!(thing->flags7 & MF7_FLYCHEAT) && thing->target == GLRenderer->mViewActor && GLRenderer->mViewActor != NULL) + { + double speed = thing->Vel.Length(); + if (speed >= thing->target->radius / 2) + { + double clipdist = clamp(thing->Speed, thing->target->radius, thing->target->radius * 2); + if ((thingpos - ViewPos).LengthSquared() < clipdist * clipdist) return; + } + } + thing->flags7 |= MF7_FLYCHEAT; // do this only once for the very first frame, but not if it gets into range again. + } + + if (thruportal != 2 && GLRenderer->mClipPortal) + { + int clipres = GLRenderer->mClipPortal->ClipPoint(thingpos); + if (clipres == GLPortal::PClip_InFront) return; + } + + player_t *player = &players[consoleplayer]; + FloatRect r; + + if (sector->sectornum != thing->Sector->sectornum && !thruportal) + { + rendersector = gl_FakeFlat(thing->Sector, &rs, false); + } + else + { + rendersector = sector; + } + topclip = rendersector->PortalBlocksMovement(sector_t::ceiling) ? LARGE_VALUE : rendersector->GetPortalPlaneZ(sector_t::ceiling); + bottomclip = rendersector->PortalBlocksMovement(sector_t::floor) ? -LARGE_VALUE : rendersector->GetPortalPlaneZ(sector_t::floor); + + DWORD spritetype = (thing->renderflags & RF_SPRITETYPEMASK); + x = thingpos.X; + z = thingpos.Z; + y = thingpos.Y; + if (spritetype == RF_FACESPRITE) z -= thing->Floorclip; // wall and flat sprites are to be considered level geometry so this may not apply. + + // [RH] Make floatbobbing a renderer-only effect. + if (thing->flags2 & MF2_FLOATBOB) + { + float fz = thing->GetBobOffset(r_TicFracF); + z += fz; + } + + modelframe = gl_FindModelFrame(thing->GetClass(), spritenum, thing->frame, !!(thing->flags & MF_DROPPED)); + if (!modelframe) + { + bool mirror; + DAngle ang = (thingpos - ViewPos).Angle(); + FTextureID patch; + if (thing->flags7 & MF7_SPRITEANGLE) + { + patch = gl_GetSpriteFrame(spritenum, thing->frame, -1, (thing->SpriteAngle).BAMs(), &mirror); + } + else if (!(thing->renderflags & RF_FLATSPRITE)) + { + patch = gl_GetSpriteFrame(spritenum, thing->frame, -1, (ang - (thing->Angles.Yaw + thing->SpriteRotation)).BAMs(), &mirror); + } + else + { + // Flat sprites cannot rotate in a predictable manner. + patch = gl_GetSpriteFrame(spritenum, thing->frame, 0, 0, &mirror); + } + + if (!patch.isValid()) return; + int type = thing->renderflags & RF_SPRITETYPEMASK; + gltexture = FMaterial::ValidateTexture(patch, (type == RF_FACESPRITE), false); + if (!gltexture) return; + + vt = gltexture->GetSpriteVT(); + vb = gltexture->GetSpriteVB(); + gltexture->GetSpriteRect(&r); + if (mirror) + { + r.left = -r.width - r.left; // mirror the sprite's x-offset + ul = gltexture->GetSpriteUL(); + ur = gltexture->GetSpriteUR(); + } + else + { + ul = gltexture->GetSpriteUR(); + ur = gltexture->GetSpriteUL(); + } + + r.Scale(sprscale.X, sprscale.Y); + + float rightfac = -r.left; + float leftfac = rightfac - r.width; + float bottomfac = -r.top; + float topfac = bottomfac - r.height; + z1 = z - r.top; + z2 = z1 - r.height; + + float spriteheight = sprscale.Y * r.height; + + // Tests show that this doesn't look good for many decorations and corpses + if (spriteheight > 0 && gl_spriteclip > 0 && (thing->renderflags & RF_SPRITETYPEMASK) == RF_FACESPRITE) + { + PerformSpriteClipAdjustment(thing, thingpos, spriteheight); + } + + float viewvecX; + float viewvecY; + switch (spritetype) + { + case RF_FACESPRITE: + viewvecX = GLRenderer->mViewVector.X; + viewvecY = GLRenderer->mViewVector.Y; + + x1 = x - viewvecY*leftfac; + x2 = x - viewvecY*rightfac; + y1 = y + viewvecX*leftfac; + y2 = y + viewvecX*rightfac; + break; + + case RF_FLATSPRITE: + { + x1 = x + leftfac; + x2 = x + rightfac; + y1 = y - topfac; + y2 = y - bottomfac; + } + break; + case RF_WALLSPRITE: + viewvecX = thing->Angles.Yaw.Cos(); + viewvecY = thing->Angles.Yaw.Sin(); + + x1 = x + viewvecY*leftfac; + x2 = x + viewvecY*rightfac; + y1 = y - viewvecX*leftfac; + y2 = y - viewvecX*rightfac; + break; + } + } + else + { + x1 = x2 = x; + y1 = y2 = y; + z1 = z2 = z; + gltexture=NULL; + } + + depth = FloatToFixed((x - ViewPos.X) * ViewTanCos + (y - ViewPos.Y) * ViewTanSin); + + // light calculation + + bool enhancedvision=false; + + // allow disabling of the fullbright flag by a brightmap definition + // (e.g. to do the gun flashes of Doom's zombies correctly. + fullbright = (thing->flags5 & MF5_BRIGHT) || + ((thing->renderflags & RF_FULLBRIGHT) && (!gltexture || !gltexture->tex->gl_info.bDisableFullbright)); + + lightlevel=fullbright? 255 : + gl_ClampLight(rendersector->GetTexture(sector_t::ceiling) == skyflatnum ? + rendersector->GetCeilingLight() : rendersector->GetFloorLight()); + foglevel = (BYTE)clamp(rendersector->lightlevel, 0, 255); + + lightlevel = (byte)gl_CheckSpriteGlow(rendersector, lightlevel, thingpos); + + ThingColor = (thing->RenderStyle.Flags & STYLEF_ColorIsFixed) ? thing->fillcolor : 0xffffff; + ThingColor.a = 255; + RenderStyle = thing->RenderStyle; + + // colormap stuff is a little more complicated here... + if (gl_fixedcolormap) + { + if ((gl_enhanced_nv_stealth > 0 && gl_fixedcolormap == CM_LITE) // Infrared powerup only + || (gl_enhanced_nv_stealth == 2 && gl_fixedcolormap >= CM_TORCH)// Also torches + || (gl_enhanced_nv_stealth == 3)) // Any fixed colormap + enhancedvision=true; + + Colormap.Clear(); + + if (gl_fixedcolormap==CM_LITE) + { + if (gl_enhanced_nightvision && + (thing->IsKindOf(RUNTIME_CLASS(AInventory)) || thing->flags3&MF3_ISMONSTER || thing->flags&MF_MISSILE || thing->flags&MF_CORPSE)) + { + RenderStyle.Flags |= STYLEF_InvertSource; + } + } + } + else + { + Colormap=rendersector->ColorMap; + if (fullbright) + { + if (rendersector == §ors[rendersector->sectornum] || in_area != area_below) + // under water areas keep their color for fullbright objects + { + // Only make the light white but keep everything else (fog, desaturation and Boom colormap.) + Colormap.LightColor.r= + Colormap.LightColor.g= + Colormap.LightColor.b=0xff; + } + else + { + Colormap.LightColor.r = (3*Colormap.LightColor.r + 0xff)/4; + Colormap.LightColor.g = (3*Colormap.LightColor.g + 0xff)/4; + Colormap.LightColor.b = (3*Colormap.LightColor.b + 0xff)/4; + } + } + else if (glset.nocoloredspritelighting) + { + Colormap.Decolorize(); + } + } + + translation=thing->Translation; + + OverrideShader = -1; + trans = thing->Alpha; + hw_styleflags = STYLEHW_Normal; + + if (RenderStyle.BlendOp >= STYLEOP_Fuzz && RenderStyle.BlendOp <= STYLEOP_FuzzOrRevSub) + { + RenderStyle.CheckFuzz(); + if (RenderStyle.BlendOp == STYLEOP_Fuzz) + { + if (gl_fuzztype != 0 && !gl.legacyMode) + { + // Todo: implement shader selection here + RenderStyle = LegacyRenderStyles[STYLE_Translucent]; + OverrideShader = gl_fuzztype + 4; + trans = 0.99f; // trans may not be 1 here + hw_styleflags |= STYLEHW_NoAlphaTest; + } + else + { + RenderStyle.BlendOp = STYLEOP_Shadow; + } + } + } + + if (RenderStyle.Flags & STYLEF_TransSoulsAlpha) + { + trans = transsouls; + } + else if (RenderStyle.Flags & STYLEF_Alpha1) + { + trans = 1.f; + } + + if (trans >= 1.f-FLT_EPSILON && RenderStyle.BlendOp != STYLEOP_Shadow && ( + (RenderStyle.SrcAlpha == STYLEALPHA_One && RenderStyle.DestAlpha == STYLEALPHA_Zero) || + (RenderStyle.SrcAlpha == STYLEALPHA_Src && RenderStyle.DestAlpha == STYLEALPHA_InvSrc) + )) + { + // This is a non-translucent sprite (i.e. STYLE_Normal or equivalent) + trans=1.f; + + if (!gl_sprite_blend || modelframe || (thing->renderflags & (RF_FLATSPRITE|RF_WALLSPRITE)) || gl_billboard_faces_camera) + { + RenderStyle.SrcAlpha = STYLEALPHA_One; + RenderStyle.DestAlpha = STYLEALPHA_Zero; + hw_styleflags = STYLEHW_Solid; + } + else + { + RenderStyle.SrcAlpha = STYLEALPHA_Src; + RenderStyle.DestAlpha = STYLEALPHA_InvSrc; + } + } + if ((gltexture && gltexture->GetTransparent()) || (RenderStyle.Flags & STYLEF_RedIsAlpha)) + { + if (hw_styleflags == STYLEHW_Solid) + { + RenderStyle.SrcAlpha = STYLEALPHA_Src; + RenderStyle.DestAlpha = STYLEALPHA_InvSrc; + } + hw_styleflags = STYLEHW_NoAlphaTest; + } + + if (enhancedvision && gl_enhanced_nightvision) + { + if (RenderStyle.BlendOp == STYLEOP_Shadow) + { + // enhanced vision makes them more visible! + trans=0.5f; + FRenderStyle rs = RenderStyle; + RenderStyle = STYLE_Translucent; + RenderStyle.Flags = rs.Flags; // Flags must be preserved, at this point it can only be STYLEF_InvertSource + } + else if (thing->flags & MF_STEALTH) + { + // enhanced vision overcomes stealth! + if (trans < 0.5f) trans = 0.5f; + } + } + + if (trans==0.0f) return; + + // end of light calculation + + actor=thing; + index = GLRenderer->gl_spriteindex++; + particle=NULL; + + const bool drawWithXYBillboard = ( !(actor->renderflags & RF_FORCEYBILLBOARD) + && (actor->renderflags & RF_SPRITETYPEMASK) == RF_FACESPRITE + && players[consoleplayer].camera + && (gl_billboard_mode == 1 || actor->renderflags & RF_FORCEXYBILLBOARD ) ); + + + // no light splitting when: + // 1. no lightlist + // 2. any fixed colormap + // 3. any bright object + // 4. any with render style shadow (which doesn't use the sector light) + // 5. anything with render style reverse subtract (light effect is not what would be desired here) + if (thing->Sector->e->XFloor.lightlist.Size() != 0 && gl_fixedcolormap == CM_DEFAULT && !fullbright && + RenderStyle.BlendOp != STYLEOP_Shadow && RenderStyle.BlendOp != STYLEOP_RevSub) + { + if (gl.flags & RFL_NO_CLIP_PLANES) // on old hardware we are rather limited... + { + lightlist = NULL; + if (!drawWithXYBillboard && !modelframe) + { + SplitSprite(thing->Sector, hw_styleflags != STYLEHW_Solid); + } + } + else + { + lightlist = &thing->Sector->e->XFloor.lightlist; + } + } + else + { + lightlist = NULL; + } + + PutSprite(hw_styleflags != STYLEHW_Solid); + rendered_sprites++; +} + + +//========================================================================== +// +// +// +//========================================================================== + +void GLSprite::ProcessParticle (particle_t *particle, sector_t *sector)//, int shade, int fakeside) +{ + if (GLRenderer->mClipPortal) + { + int clipres = GLRenderer->mClipPortal->ClipPoint(particle->Pos); + if (clipres == GLPortal::PClip_InFront) return; + } + + player_t *player=&players[consoleplayer]; + + if (particle->trans==0) return; + + lightlevel = gl_ClampLight(sector->GetTexture(sector_t::ceiling) == skyflatnum ? + sector->GetCeilingLight() : sector->GetFloorLight()); + foglevel = (BYTE)clamp(sector->lightlevel, 0, 255); + + if (gl_fixedcolormap) + { + Colormap.Clear(); + } + else if (!particle->bright) + { + TArray & lightlist=sector->e->XFloor.lightlist; + double lightbottom; + + Colormap = sector->ColorMap; + for(unsigned int i=0;iPos); + else lightbottom = sector->floorplane.ZatPoint(particle->Pos); + + if (lightbottom < particle->Pos.Z) + { + lightlevel = gl_ClampLight(*lightlist[i].p_lightlevel); + Colormap.LightColor = (lightlist[i].extra_colormap)->Color; + break; + } + } + if (glset.nocoloredspritelighting) + { + Colormap.Decolorize(); // ZDoom never applies colored light to particles. + } + } + else + { + lightlevel = 255; + Colormap = sector->ColorMap; + Colormap.ClearColor(); + } + + trans=particle->trans/255.0f; + RenderStyle = STYLE_Translucent; + OverrideShader = 0; + + ThingColor = particle->color; + ThingColor.a = 255; + + modelframe=NULL; + gltexture=NULL; + topclip = LARGE_VALUE; + bottomclip = -LARGE_VALUE; + + // [BB] Load the texture for round or smooth particles + if (gl_particles_style) + { + FTexture *lump = NULL; + if (gl_particles_style == 1) + { + lump = GLRenderer->glpart2; + } + else if (gl_particles_style == 2) + { + lump = GLRenderer->glpart; + } + + if (lump != NULL) + { + gltexture = FMaterial::ValidateTexture(lump, true); + translation = 0; + + ul = gltexture->GetUL(); + ur = gltexture->GetUR(); + vt = gltexture->GetVT(); + vb = gltexture->GetVB(); + FloatRect r; + gltexture->GetSpriteRect(&r); + } + } + + x = particle->Pos.X; + y = particle->Pos.Y; + z = particle->Pos.Z; + + float scalefac=particle->size/4.0f; + // [BB] The smooth particles are smaller than the other ones. Compensate for this here. + if (gl_particles_style==2) + scalefac *= 1.7; + + float viewvecX = GLRenderer->mViewVector.X; + float viewvecY = GLRenderer->mViewVector.Y; + + x1=x+viewvecY*scalefac; + x2=x-viewvecY*scalefac; + y1=y-viewvecX*scalefac; + y2=y+viewvecX*scalefac; + z1=z-scalefac; + z2=z+scalefac; + + depth = FloatToFixed((x - ViewPos.X) * ViewTanCos + (y - ViewPos.Y) * ViewTanSin); + + actor=NULL; + this->particle=particle; + fullbright = !!particle->bright; + + // [BB] Translucent particles have to be rendered without the alpha test. + if (gl_particles_style != 2 && trans>=1.0f-FLT_EPSILON) hw_styleflags = STYLEHW_Solid; + else hw_styleflags = STYLEHW_NoAlphaTest; + + if (sector->e->XFloor.lightlist.Size() != 0 && gl_fixedcolormap == CM_DEFAULT && !fullbright) + lightlist = §or->e->XFloor.lightlist; + else + lightlist = NULL; + + PutSprite(hw_styleflags != STYLEHW_Solid); + rendered_sprites++; +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_RenderActorsInPortal(FGLLinePortal *glport) +{ + TMap processcheck; + if (glport->validcount == validcount) return; // only process once per frame + glport->validcount = validcount; + for (auto port : glport->lines) + { + line_t *line = port->mOrigin; + if (line->isLinePortal()) // only crossable ones + { + FLinePortal *port2 = port->mDestination->getPortal(); + // process only if the other side links back to this one. + if (port2 != nullptr && port->mDestination == port2->mOrigin && port->mOrigin == port2->mDestination) + { + + for (portnode_t *node = port->render_thinglist; node != nullptr; node = node->m_snext) + { + AActor *th = node->m_thing; + + // process each actor only once per portal. + bool *check = processcheck.CheckKey(th); + if (check && *check) continue; + processcheck[th] = true; + + DAngle savedangle = th->Angles.Yaw; + DVector3 savedpos = th->Pos(); + DVector3 newpos = savedpos; + sector_t fakesector; + + P_TranslatePortalXY(line, newpos.X, newpos.Y); + P_TranslatePortalZ(line, newpos.Z); + P_TranslatePortalAngle(line, th->Angles.Yaw); + th->SetXYZ(newpos); + th->Prev += newpos - savedpos; + + GLSprite spr; + th->fillcolor = 0xff0000ff; + spr.Process(th, gl_FakeFlat(th->Sector, &fakesector, false), 2); + th->fillcolor = 0xffffffff; + th->Angles.Yaw = savedangle; + th->SetXYZ(savedpos); + th->Prev -= newpos - savedpos; + } + } + } + } +} \ No newline at end of file diff --git a/src/gl/scene/gl_spritelight.cpp b/src/gl/scene/gl_spritelight.cpp new file mode 100644 index 000000000..6efa078ca --- /dev/null +++ b/src/gl/scene/gl_spritelight.cpp @@ -0,0 +1,129 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2002-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_light.cpp +** Light level / fog management / dynamic lights +** +*/ + +#include "gl/system/gl_system.h" +#include "c_dispatch.h" +#include "p_local.h" +#include "p_effect.h" +#include "vectors.h" +#include "gl/gl_functions.h" +#include "g_level.h" + +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" + + +//========================================================================== +// +// Sets a single light value from all dynamic lights affecting the specified location +// +//========================================================================== + +void gl_SetDynSpriteLight(AActor *self, float x, float y, float z, subsector_t * subsec) +{ + ADynamicLight *light; + float frac, lr, lg, lb; + float radius; + float out[3] = { 0.0f, 0.0f, 0.0f }; + + // Go through both light lists + FLightNode * node = subsec->lighthead; + while (node) + { + light=node->lightsource; + if (light->visibletoplayer && !(light->flags2&MF2_DORMANT) && (!(light->flags4&MF4_DONTLIGHTSELF) || light->target != self)) + { + float dist; + + // This is a performance critical section of code where we cannot afford to let the compiler decide whether to inline the function or not. + // This will do the calculations explicitly rather than calling one of AActor's utility functions. + if (Displacements.size > 0) + { + int fromgroup = light->Sector->PortalGroup; + int togroup = subsec->sector->PortalGroup; + if (fromgroup == togroup || fromgroup == 0 || togroup == 0) goto direct; + + DVector2 offset = Displacements.getOffset(fromgroup, togroup); + dist = FVector3(x - light->X() - offset.X, y - light->Y() - offset.Y, z - light->Z()).LengthSquared(); + } + else + { + direct: + dist = FVector3(x - light->X(), y - light->Y(), z - light->Z()).LengthSquared(); + } + + radius = light->GetRadius(); + + if (dist < radius * radius) + { + dist = sqrtf(dist); // only calculate the square root if we really need it. + + frac = 1.0f - (dist / radius); + + if (frac > 0) + { + lr = light->GetRed() / 255.0f; + lg = light->GetGreen() / 255.0f; + lb = light->GetBlue() / 255.0f; + if (light->IsSubtractive()) + { + float bright = FVector3(lr, lg, lb).Length(); + FVector3 lightColor(lr, lg, lb); + lr = (bright - lr) * -1; + lg = (bright - lg) * -1; + lb = (bright - lb) * -1; + } + + out[0] += lr * frac; + out[1] += lg * frac; + out[2] += lb * frac; + } + } + } + node = node->nextLight; + } + gl_RenderState.SetDynLight(out[0], out[1], out[2]); +} + +void gl_SetDynSpriteLight(AActor *thing, particle_t *particle) +{ + if (thing != NULL) + { + gl_SetDynSpriteLight(thing, thing->X(), thing->Y(), thing->Center(), thing->subsector); + } + else if (particle != NULL) + { + gl_SetDynSpriteLight(NULL, particle->Pos.X, particle->Pos.Y, particle->Pos.Z, particle->subsector); + } +} diff --git a/src/gl/scene/gl_vertex.cpp b/src/gl/scene/gl_vertex.cpp new file mode 100644 index 000000000..d693227d5 --- /dev/null +++ b/src/gl/scene/gl_vertex.cpp @@ -0,0 +1,180 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2006-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + + + +#include "gl/system/gl_system.h" +#include "gl/gl_functions.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_templates.h" + +EXTERN_CVAR(Bool, gl_seamless) + +//========================================================================== +// +// Split upper edge of wall +// +//========================================================================== + +void GLWall::SplitUpperEdge(FFlatVertex *&ptr) +{ + if (seg == NULL || seg->sidedef == NULL || (seg->sidedef->Flags & WALLF_POLYOBJ) || seg->sidedef->numsegs == 1) return; + + side_t *sidedef = seg->sidedef; + float polyw = glseg.fracright - glseg.fracleft; + float facu = (tcs[UPRGT].u - tcs[UPLFT].u) / polyw; + float facv = (tcs[UPRGT].v - tcs[UPLFT].v) / polyw; + float fact = (ztop[1] - ztop[0]) / polyw; + float facc = (zceil[1] - zceil[0]) / polyw; + float facf = (zfloor[1] - zfloor[0]) / polyw; + + for (int i = 0; i < sidedef->numsegs - 1; i++) + { + seg_t *cseg = sidedef->segs[i]; + float sidefrac = cseg->sidefrac; + if (sidefrac <= glseg.fracleft) continue; + if (sidefrac >= glseg.fracright) return; + + float fracfac = sidefrac - glseg.fracleft; + + ptr->x = cseg->v2->fX(); + ptr->y = cseg->v2->fY(); + ptr->z = ztop[0] + fact * fracfac; + ptr->u = tcs[UPLFT].u + facu * fracfac; + ptr->v = tcs[UPLFT].v + facv * fracfac; + ptr++; + } +} + +//========================================================================== +// +// Split upper edge of wall +// +//========================================================================== + +void GLWall::SplitLowerEdge(FFlatVertex *&ptr) +{ + if (seg == NULL || seg->sidedef == NULL || (seg->sidedef->Flags & WALLF_POLYOBJ) || seg->sidedef->numsegs == 1) return; + + side_t *sidedef = seg->sidedef; + float polyw = glseg.fracright - glseg.fracleft; + float facu = (tcs[LORGT].u - tcs[LOLFT].u) / polyw; + float facv = (tcs[LORGT].v - tcs[LOLFT].v) / polyw; + float facb = (zbottom[1] - zbottom[0]) / polyw; + float facc = (zceil[1] - zceil[0]) / polyw; + float facf = (zfloor[1] - zfloor[0]) / polyw; + + for (int i = sidedef->numsegs - 2; i >= 0; i--) + { + seg_t *cseg = sidedef->segs[i]; + float sidefrac = cseg->sidefrac; + if (sidefrac >= glseg.fracright) continue; + if (sidefrac <= glseg.fracleft) return; + + float fracfac = sidefrac - glseg.fracleft; + + ptr->x = cseg->v2->fX(); + ptr->y = cseg->v2->fY(); + ptr->z = zbottom[0] + facb * fracfac; + ptr->u = tcs[LOLFT].u + facu * fracfac; + ptr->v = tcs[LOLFT].v + facv * fracfac; + ptr++; + } +} + +//========================================================================== +// +// Split left edge of wall +// +//========================================================================== + +void GLWall::SplitLeftEdge(FFlatVertex *&ptr) +{ + if (vertexes[0] == NULL) return; + + vertex_t * vi = vertexes[0]; + + if (vi->numheights) + { + int i = 0; + + float polyh1 = ztop[0] - zbottom[0]; + float factv1 = polyh1 ? (tcs[UPLFT].v - tcs[LOLFT].v) / polyh1 : 0; + float factu1 = polyh1 ? (tcs[UPLFT].u - tcs[LOLFT].u) / polyh1 : 0; + + while (inumheights && vi->heightlist[i] <= zbottom[0]) i++; + while (inumheights && vi->heightlist[i] < ztop[0]) + { + ptr->x = glseg.x1; + ptr->y = glseg.y1; + ptr->z = vi->heightlist[i]; + ptr->u = factu1*(vi->heightlist[i] - ztop[0]) + tcs[UPLFT].u; + ptr->v = factv1*(vi->heightlist[i] - ztop[0]) + tcs[UPLFT].v; + ptr++; + i++; + } + } +} + +//========================================================================== +// +// Split right edge of wall +// +//========================================================================== + +void GLWall::SplitRightEdge(FFlatVertex *&ptr) +{ + if (vertexes[1] == NULL) return; + + vertex_t * vi = vertexes[1]; + + if (vi->numheights) + { + int i = vi->numheights - 1; + + float polyh2 = ztop[1] - zbottom[1]; + float factv2 = polyh2 ? (tcs[UPRGT].v - tcs[LORGT].v) / polyh2 : 0; + float factu2 = polyh2 ? (tcs[UPRGT].u - tcs[LORGT].u) / polyh2 : 0; + + while (i>0 && vi->heightlist[i] >= ztop[1]) i--; + while (i>0 && vi->heightlist[i] > zbottom[1]) + { + ptr->x = glseg.x2; + ptr->y = glseg.y2; + ptr->z = vi->heightlist[i]; + ptr->u = factu2*(vi->heightlist[i] - ztop[1]) + tcs[UPRGT].u; + ptr->v = factv2*(vi->heightlist[i] - ztop[1]) + tcs[UPRGT].v; + ptr++; + i--; + } + } +} + diff --git a/src/gl/scene/gl_wall.h b/src/gl/scene/gl_wall.h new file mode 100644 index 000000000..bdee5761f --- /dev/null +++ b/src/gl/scene/gl_wall.h @@ -0,0 +1,408 @@ +#ifndef __GL_WALL_H +#define __GL_WALL_H +//========================================================================== +// +// One wall segment in the draw list +// +//========================================================================== +#include "r_defs.h" +#include "textures/textures.h" +#include "gl/renderer/gl_colormap.h" + +struct GLHorizonInfo; +struct F3DFloor; +struct model_t; +struct FSpriteModelFrame; +struct particle_t; +class ADynamicLight; +class FMaterial; +struct GLDrawList; +struct GLSkyInfo; +struct FTexCoordInfo; +struct FPortal; +struct FFlatVertex; +struct FGLLinePortal; + +enum +{ + GLSector_NoSkyDraw = 89, + GLSector_Skybox = 90, +}; + +enum WallTypes +{ + RENDERWALL_NONE, + RENDERWALL_TOP, + RENDERWALL_M1S, + RENDERWALL_M2S, + RENDERWALL_BOTTOM, + RENDERWALL_FOGBOUNDARY, + RENDERWALL_MIRRORSURFACE, + RENDERWALL_M2SNF, + RENDERWALL_COLOR, + RENDERWALL_FFBLOCK, + // Insert new types at the end! +}; + +enum PortalTypes +{ + PORTALTYPE_SKY, + PORTALTYPE_HORIZON, + PORTALTYPE_SKYBOX, + PORTALTYPE_SECTORSTACK, + PORTALTYPE_PLANEMIRROR, + PORTALTYPE_MIRROR, + PORTALTYPE_LINETOLINE, +}; + +struct GLSeg +{ + float x1,x2; + float y1,y2; + float fracleft, fracright; // fractional offset of the 2 vertices on the linedef + + FVector3 Normal() const + { + // we do not use the vector math inlines here because they are not optimized for speed but accuracy in the playsim + float x = y2 - y1; + float y = x1 - x2; + float length = sqrtf(x*x + y*y); + return FVector3(x / length, 0, y / length); + } +}; + +struct texcoord +{ + float u,v; +}; + +//========================================================================== +// +// One sector plane, still in fixed point +// +//========================================================================== + +struct GLSectorPlane +{ + FTextureID texture; + secplane_t plane; + float Texheight; + float Angle; + FVector2 Offs; + FVector2 Scale; + + void GetFromSector(sector_t * sec, int ceiling) + { + Offs.X = (float)sec->GetXOffset(ceiling); + Offs.Y = (float)sec->GetYOffset(ceiling); + Scale.X = (float)sec->GetXScale(ceiling); + Scale.Y = (float)sec->GetYScale(ceiling); + Angle = (float)sec->GetAngle(ceiling).Degrees; + texture = sec->GetTexture(ceiling); + plane = sec->GetSecPlane(ceiling); + Texheight = (float)((ceiling == sector_t::ceiling)? plane.fD() : -plane.fD()); + } +}; + + +class GLWall +{ +public: + + enum + { + //GLWF_CLAMPX=1, use GLT_* for these! + //GLWF_CLAMPY=2, + GLWF_SKYHACK=4, + GLWF_GLOW=8, // illuminated by glowing flats + GLWF_NOSPLITUPPER=16, + GLWF_NOSPLITLOWER=32, + GLWF_NOSPLIT=64, + }; + + enum + { + RWF_BLANK = 0, + RWF_TEXTURED = 1, // actually not being used anymore because with buffers it's even less efficient not writing the texture coordinates - but leave it here + RWF_NOSPLIT = 4, + RWF_NORENDER = 8, + }; + + enum + { + LOLFT, + UPLFT, + UPRGT, + LORGT, + }; + + friend struct GLDrawList; + friend class GLPortal; + + GLSeg glseg; + vertex_t * vertexes[2]; // required for polygon splitting + float ztop[2],zbottom[2]; + texcoord tcs[4]; + float alpha; + FMaterial *gltexture; + + FColormap Colormap; + ERenderStyle RenderStyle; + + float ViewDistance; + + TArray *lightlist; + int lightlevel; + BYTE type; + BYTE flags; + short rellight; + + float topglowcolor[4]; + float bottomglowcolor[4]; + + int dynlightindex; + + union + { + // it's either one of them but never more! + FSectorPortal *secportal; // sector portal (formerly skybox) + GLSkyInfo * sky; // for normal sky + GLHorizonInfo * horizon; // for horizon information + FPortal * portal; // stacked sector portals + secplane_t * planemirror; // for plane mirrors + FGLLinePortal *lineportal; // line-to-line portals + }; + + + FTextureID topflat,bottomflat; + secplane_t topplane, bottomplane; // we need to save these to pass them to the shader for calculating glows. + + // these are not the same as ytop and ybottom!!! + float zceil[2]; + float zfloor[2]; + + unsigned int vertindex; + unsigned int vertcount; + +public: + seg_t * seg; // this gives the easiest access to all other structs involved + subsector_t * sub; // For polyobjects +private: + + void CheckGlowing(); + bool PutWallCompat(int passflag); + void PutWall(bool translucent); + void PutPortal(int ptype); + void CheckTexturePosition(); + + void RenderFogBoundaryCompat(); + void RenderLightsCompat(int pass); + + void Put3DWall(lightlist_t * lightlist, bool translucent); + bool SplitWallComplex(sector_t * frontsector, bool translucent, float& maplightbottomleft, float& maplightbottomright); + void SplitWall(sector_t * frontsector, bool translucent); + + void SetupLights(); + bool PrepareLight(ADynamicLight * light, int pass); + void MakeVertices(bool nosplit); + void RenderWall(int textured); + void RenderTextured(int rflags); + + void FloodPlane(int pass); + + void SkyPlane(sector_t *sector, int plane, bool allowmirror); + void SkyLine(sector_t *sec, line_t *line); + void SkyNormal(sector_t * fs,vertex_t * v1,vertex_t * v2); + void SkyTop(seg_t * seg,sector_t * fs,sector_t * bs,vertex_t * v1,vertex_t * v2); + void SkyBottom(seg_t * seg,sector_t * fs,sector_t * bs,vertex_t * v1,vertex_t * v2); + + void LightPass(); + void SetHorizon(vertex_t * ul, vertex_t * ur, vertex_t * ll, vertex_t * lr); + bool DoHorizon(seg_t * seg,sector_t * fs, vertex_t * v1,vertex_t * v2); + + bool SetWallCoordinates(seg_t * seg, FTexCoordInfo *tci, float ceilingrefheight, + float topleft, float topright, float bottomleft, float bottomright, float t_ofs); + + void DoTexture(int type,seg_t * seg,int peg, + float ceilingrefheight, float floorrefheight, + float CeilingHeightstart,float CeilingHeightend, + float FloorHeightstart,float FloorHeightend, + float v_offset); + + void DoMidTexture(seg_t * seg, bool drawfogboundary, + sector_t * front, sector_t * back, + sector_t * realfront, sector_t * realback, + float fch1, float fch2, float ffh1, float ffh2, + float bch1, float bch2, float bfh1, float bfh2); + + void GetPlanePos(F3DFloor::planeref * planeref, float & left, float & right); + + void BuildFFBlock(seg_t * seg, F3DFloor * rover, + float ff_topleft, float ff_topright, + float ff_bottomleft, float ff_bottomright); + void InverseFloors(seg_t * seg, sector_t * frontsector, + float topleft, float topright, + float bottomleft, float bottomright); + void ClipFFloors(seg_t * seg, F3DFloor * ffloor, sector_t * frontsector, + float topleft, float topright, + float bottomleft, float bottomright); + void DoFFloorBlocks(seg_t * seg, sector_t * frontsector, sector_t * backsector, + float fch1, float fch2, float ffh1, float ffh2, + float bch1, float bch2, float bfh1, float bfh2); + + void DrawDecal(DBaseDecal *actor); + void DoDrawDecals(); + + void RenderFogBoundary(); + void RenderMirrorSurface(); + void RenderTranslucentWall(); + + void SplitLeftEdge (FFlatVertex *&ptr); + void SplitRightEdge(FFlatVertex *&ptr); + void SplitUpperEdge(FFlatVertex *&ptr); + void SplitLowerEdge(FFlatVertex *&ptr); + +public: + + void Process(seg_t *seg, sector_t *frontsector, sector_t *backsector); + void ProcessLowerMiniseg(seg_t *seg, sector_t *frontsector, sector_t *backsector); + void Draw(int pass); + + float PointOnSide(float x,float y) + { + return -((y-glseg.y1)*(glseg.x2-glseg.x1)-(x-glseg.x1)*(glseg.y2-glseg.y1)); + } + + // Lines start-end and fdiv must intersect. + double CalcIntersectionVertex(GLWall * w2) + { + float ax = glseg.x1, ay=glseg.y1; + float bx = glseg.x2, by=glseg.y2; + float cx = w2->glseg.x1, cy=w2->glseg.y1; + float dx = w2->glseg.x2, dy=w2->glseg.y2; + return ((ay-cy)*(dx-cx)-(ax-cx)*(dy-cy)) / ((bx-ax)*(dy-cy)-(by-ay)*(dx-cx)); + } + +}; + +//========================================================================== +// +// One flat plane in the draw list +// +//========================================================================== + +class GLFlat +{ +public: + friend struct GLDrawList; + + sector_t * sector; + float dz; // z offset for rendering hacks + float z; // the z position of the flat (only valid for non-sloped planes) + FMaterial *gltexture; + + FColormap Colormap; // light and fog + ERenderStyle renderstyle; + + float alpha; + GLSectorPlane plane; + int lightlevel; + bool stack; + bool ceiling; + BYTE renderflags; + int vboindex; + //int vboheight; + + int dynlightindex; + + // compatibility fallback stuff. + void DrawSubsectorLights(subsector_t * sub, int pass); + void DrawLightsCompat(int pass); + bool PutFlatCompat(bool fog); + + void SetupSubsectorLights(int pass, subsector_t * sub, int *dli = NULL); + void DrawSubsector(subsector_t * sub); + void DrawSkyboxSector(int pass, bool processlights); + void DrawSubsectors(int pass, bool processlights, bool istrans); + void ProcessLights(bool istrans); + + void PutFlat(bool fog = false); + void Process(sector_t * model, int whichplane, bool notexture); + void SetFrom3DFloor(F3DFloor *rover, bool top, bool underside); + void ProcessSector(sector_t * frontsector); + void Draw(int pass, bool trans); +}; + + +//========================================================================== +// +// One sprite in the draw list +// +//========================================================================== + + +class GLSprite +{ +public: + friend struct GLDrawList; + friend void Mod_RenderModel(GLSprite * spr, model_t * mdl, int framenumber); + + int lightlevel; + BYTE foglevel; + BYTE hw_styleflags; + bool fullbright; + PalEntry ThingColor; // thing's own color + FColormap Colormap; + FSpriteModelFrame * modelframe; + FRenderStyle RenderStyle; + int OverrideShader; + + int translation; + int index; + int depth; + + float topclip; + float bottomclip; + + float x,y,z; // needed for sorting! + + float ul,ur; + float vt,vb; + float x1,y1,z1; + float x2,y2,z2; + + FMaterial *gltexture; + float trans; + AActor * actor; + particle_t * particle; + TArray *lightlist; + + void SplitSprite(sector_t * frontsector, bool translucent); + void SetLowerParam(); + void PerformSpriteClipAdjustment(AActor *thing, const DVector2 &thingpos, float spriteheight); + void CalculateVertices(FVector3 *v); + +public: + + void Draw(int pass); + void PutSprite(bool translucent); + void Process(AActor* thing,sector_t * sector, int thruportal = false); + void ProcessParticle (particle_t *particle, sector_t *sector);//, int shade, int fakeside) + void SetThingColor(PalEntry); + + // Lines start-end and fdiv must intersect. + double CalcIntersectionVertex(GLWall * w2); +}; + +inline float Dist2(float x1,float y1,float x2,float y2) +{ + return sqrtf((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); +} + +// Light + color + +void gl_SetDynSpriteLight(AActor *self, float x, float y, float z, subsector_t *subsec); +void gl_SetDynSpriteLight(AActor *actor, particle_t *particle); +void gl_RenderActorsInPortal(FGLLinePortal *glport); + +#endif diff --git a/src/gl/scene/gl_walls.cpp b/src/gl/scene/gl_walls.cpp new file mode 100644 index 000000000..30e10b73f --- /dev/null +++ b/src/gl/scene/gl_walls.cpp @@ -0,0 +1,1803 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "p_local.h" +#include "p_lnspec.h" +#include "a_sharedglobal.h" +#include "g_level.h" +#include "templates.h" +#include "vectors.h" +#include "r_defs.h" +#include "r_sky.h" +#include "r_utility.h" +#include "p_maputl.h" +#include "doomdata.h" +#include "portal.h" + +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_geometric.h" +#include "gl/utility/gl_templates.h" +#include "gl/shaders/gl_shader.h" + + +//========================================================================== +// +// Checks whether a wall should glow +// +//========================================================================== +void GLWall::CheckGlowing() +{ + bottomglowcolor[3] = topglowcolor[3] = 0; + if (!gl_isFullbright(Colormap.LightColor, lightlevel)) + { + FTexture *tex = TexMan[topflat]; + if (tex != NULL && tex->isGlowing()) + { + flags |= GLWall::GLWF_GLOW; + tex->GetGlowColor(topglowcolor); + topglowcolor[3] = tex->gl_info.GlowHeight; + } + + tex = TexMan[bottomflat]; + if (tex != NULL && tex->isGlowing()) + { + flags |= GLWall::GLWF_GLOW; + tex->GetGlowColor(bottomglowcolor); + bottomglowcolor[3] = tex->gl_info.GlowHeight; + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::PutWall(bool translucent) +{ + int list; + + static char passflag[] = { + 0, //RENDERWALL_NONE, + 1, //RENDERWALL_TOP, // unmasked + 1, //RENDERWALL_M1S, // unmasked + 2, //RENDERWALL_M2S, // depends on render and texture settings + 1, //RENDERWALL_BOTTOM, // unmasked + 3, //RENDERWALL_FOGBOUNDARY, // translucent + 1, //RENDERWALL_MIRRORSURFACE, // only created from PORTALTYPE_MIRROR + 2, //RENDERWALL_M2SNF, // depends on render and texture settings, no fog, used on mid texture lines with a fog boundary. + 3, //RENDERWALL_COLOR, // translucent + 2, //RENDERWALL_FFBLOCK // depends on render and texture settings + }; + + + if (gltexture && gltexture->GetTransparent() && passflag[type] == 2) + { + translucent = true; + } + + if (gl_fixedcolormap) + { + // light planes don't get drawn with fullbright rendering + if (gltexture == NULL) return; + Colormap.Clear(); + } + + CheckGlowing(); + + if (translucent) // translucent walls + { + ViewDistance = (ViewPos - (seg->linedef->v1->fPos() + seg->linedef->Delta() / 2)).XY().LengthSquared(); + if (gl.buffermethod == BM_DEFERRED) MakeVertices(true); + gl_drawinfo->drawlists[GLDL_TRANSLUCENT].AddWall(this); + } + else + { + if (gl.legacyMode && !translucent) + { + if (PutWallCompat(passflag[type])) return; + } + + bool masked; + + masked = passflag[type] == 1 ? false : (gltexture && gltexture->isMasked()); + + if ((flags&GLWF_SKYHACK && type == RENDERWALL_M2S)) + { + list = GLDL_MASKEDWALLSOFS; + } + else + { + list = masked ? GLDL_MASKEDWALLS : GLDL_PLAINWALLS; + } + if (gl.buffermethod == BM_DEFERRED) MakeVertices(false); + gl_drawinfo->drawlists[list].AddWall(this); + + } + lightlist = NULL; + vertcount = 0; // make sure that following parts of the same linedef do not get this one's vertex info. +} + +void GLWall::PutPortal(int ptype) +{ + GLPortal * portal; + + if (gl.buffermethod == BM_DEFERRED) MakeVertices(false); + switch (ptype) + { + // portals don't go into the draw list. + // Instead they are added to the portal manager + case PORTALTYPE_HORIZON: + horizon=UniqueHorizons.Get(horizon); + portal=GLPortal::FindPortal(horizon); + if (!portal) portal=new GLHorizonPortal(horizon); + portal->AddLine(this); + break; + + case PORTALTYPE_SKYBOX: + portal = GLPortal::FindPortal(secportal); + if (!portal) + { + // either a regular skybox or an Eternity-style horizon + if (secportal->mType != PORTS_SKYVIEWPOINT) portal = new GLEEHorizonPortal(secportal); + else portal = new GLSkyboxPortal(secportal); + } + portal->AddLine(this); + break; + + case PORTALTYPE_SECTORSTACK: + portal = this->portal->GetRenderState(); + portal->AddLine(this); + break; + + case PORTALTYPE_PLANEMIRROR: + if (GLPortal::PlaneMirrorMode * planemirror->fC() <=0) + { + //@sync-portal + planemirror=UniquePlaneMirrors.Get(planemirror); + portal=GLPortal::FindPortal(planemirror); + if (!portal) portal=new GLPlaneMirrorPortal(planemirror); + portal->AddLine(this); + } + break; + + case PORTALTYPE_MIRROR: + portal=GLPortal::FindPortal(seg->linedef); + if (!portal) portal=new GLMirrorPortal(seg->linedef); + portal->AddLine(this); + if (gl_mirror_envmap) + { + // draw a reflective layer over the mirror + type=RENDERWALL_MIRRORSURFACE; + gl_drawinfo->drawlists[GLDL_TRANSLUCENTBORDER].AddWall(this); + } + break; + + case PORTALTYPE_LINETOLINE: + portal=GLPortal::FindPortal(lineportal); + if (!portal) + { + line_t *otherside = lineportal->lines[0]->mDestination; + if (otherside != NULL && otherside->portalindex < linePortals.Size()) + { + gl_RenderActorsInPortal(linePortalToGL[otherside->portalindex]); + } + portal = new GLLineToLinePortal(lineportal); + } + portal->AddLine(this); + break; + + case PORTALTYPE_SKY: + portal=GLPortal::FindPortal(sky); + if (!portal) portal=new GLSkyPortal(sky); + portal->AddLine(this); + break; + } + vertcount = 0; +} +//========================================================================== +// +// Sets 3D-floor lighting info +// +//========================================================================== + +void GLWall::Put3DWall(lightlist_t * lightlist, bool translucent) +{ + // only modify the light level if it doesn't originate from the seg's frontsector. This is to account for light transferring effects + if (lightlist->p_lightlevel != &seg->sidedef->sector->lightlevel) + { + lightlevel = gl_ClampLight(*lightlist->p_lightlevel); + } + // relative light won't get changed here. It is constant across the entire wall. + + Colormap.CopyFrom3DLight(lightlist); + PutWall(translucent); +} + +//========================================================================== +// +// Splits a wall vertically if a 3D-floor +// creates different lighting across the wall +// +//========================================================================== + +bool GLWall::SplitWallComplex(sector_t * frontsector, bool translucent, float& maplightbottomleft, float& maplightbottomright) +{ + GLWall copyWall1, copyWall2; + + // check for an intersection with the upper plane + if ((maplightbottomleftztop[1]) || + (maplightbottomleft>ztop[0] && maplightbottomright(fabsf(glseg.x2 - glseg.x1), fabsf(glseg.y2 - glseg.y1)); + + float dch = ztop[1] - ztop[0]; + float dfh = maplightbottomright - maplightbottomleft; + float coeff = (ztop[0] - maplightbottomleft) / (dfh - dch); + + // check for inaccuracies - let's be a little generous here! + if (coeff*clen<.1f) + { + maplightbottomleft = ztop[0]; + } + else if (coeff*clen>clen - .1f) + { + maplightbottomright = ztop[1]; + } + else + { + // split the wall in two at the intersection and recursively split both halves + copyWall1 = copyWall2 = *this; + + copyWall1.glseg.x2 = copyWall2.glseg.x1 = glseg.x1 + coeff * (glseg.x2 - glseg.x1); + copyWall1.glseg.y2 = copyWall2.glseg.y1 = glseg.y1 + coeff * (glseg.y2 - glseg.y1); + copyWall1.ztop[1] = copyWall2.ztop[0] = ztop[0] + coeff * (ztop[1] - ztop[0]); + copyWall1.zbottom[1] = copyWall2.zbottom[0] = zbottom[0] + coeff * (zbottom[1] - zbottom[0]); + copyWall1.glseg.fracright = copyWall2.glseg.fracleft = glseg.fracleft + coeff * (glseg.fracright - glseg.fracleft); + copyWall1.tcs[UPRGT].u = copyWall2.tcs[UPLFT].u = tcs[UPLFT].u + coeff * (tcs[UPRGT].u - tcs[UPLFT].u); + copyWall1.tcs[UPRGT].v = copyWall2.tcs[UPLFT].v = tcs[UPLFT].v + coeff * (tcs[UPRGT].v - tcs[UPLFT].v); + copyWall1.tcs[LORGT].u = copyWall2.tcs[LOLFT].u = tcs[LOLFT].u + coeff * (tcs[LORGT].u - tcs[LOLFT].u); + copyWall1.tcs[LORGT].v = copyWall2.tcs[LOLFT].v = tcs[LOLFT].v + coeff * (tcs[LORGT].v - tcs[LOLFT].v); + + copyWall1.SplitWall(frontsector, translucent); + copyWall2.SplitWall(frontsector, translucent); + return true; + } + } + + // check for an intersection with the lower plane + if ((maplightbottomleftzbottom[1]) || + (maplightbottomleft>zbottom[0] && maplightbottomright(fabsf(glseg.x2 - glseg.x1), fabsf(glseg.y2 - glseg.y1)); + + float dch = zbottom[1] - zbottom[0]; + float dfh = maplightbottomright - maplightbottomleft; + float coeff = (zbottom[0] - maplightbottomleft) / (dfh - dch); + + // check for inaccuracies - let's be a little generous here because there's + // some conversions between floats and fixed_t's involved + if (coeff*clen<.1f) + { + maplightbottomleft = zbottom[0]; + } + else if (coeff*clen>clen - .1f) + { + maplightbottomright = zbottom[1]; + } + else + { + // split the wall in two at the intersection and recursively split both halves + copyWall1 = copyWall2 = *this; + + copyWall1.glseg.x2 = copyWall2.glseg.x1 = glseg.x1 + coeff * (glseg.x2 - glseg.x1); + copyWall1.glseg.y2 = copyWall2.glseg.y1 = glseg.y1 + coeff * (glseg.y2 - glseg.y1); + copyWall1.ztop[1] = copyWall2.ztop[0] = ztop[0] + coeff * (ztop[1] - ztop[0]); + copyWall1.zbottom[1] = copyWall2.zbottom[0] = zbottom[0] + coeff * (zbottom[1] - zbottom[0]); + copyWall1.glseg.fracright = copyWall2.glseg.fracleft = glseg.fracleft + coeff * (glseg.fracright - glseg.fracleft); + copyWall1.tcs[UPRGT].u = copyWall2.tcs[UPLFT].u = tcs[UPLFT].u + coeff * (tcs[UPRGT].u - tcs[UPLFT].u); + copyWall1.tcs[UPRGT].v = copyWall2.tcs[UPLFT].v = tcs[UPLFT].v + coeff * (tcs[UPRGT].v - tcs[UPLFT].v); + copyWall1.tcs[LORGT].u = copyWall2.tcs[LOLFT].u = tcs[LOLFT].u + coeff * (tcs[LORGT].u - tcs[LOLFT].u); + copyWall1.tcs[LORGT].v = copyWall2.tcs[LOLFT].v = tcs[LOLFT].v + coeff * (tcs[LORGT].v - tcs[LOLFT].v); + + copyWall1.SplitWall(frontsector, translucent); + copyWall2.SplitWall(frontsector, translucent); + return true; + } + } + + return false; +} + +void GLWall::SplitWall(sector_t * frontsector, bool translucent) +{ + GLWall copyWall1; + float maplightbottomleft; + float maplightbottomright; + unsigned int i; + int origlight = lightlevel; + FColormap origcm=Colormap; + + TArray & lightlist=frontsector->e->XFloor.lightlist; + + if (glseg.x1==glseg.x2 && glseg.y1==glseg.y2) + { + return; + } + //::SplitWall.Clock(); + +#ifdef _DEBUG + if (seg->linedef-lines==1) + { + int a = 0; + } +#endif + + if (lightlist.Size()>1) + { + for(i=0;i=ztop[0] && maplightbottomright>=ztop[1]) + { + continue; + } + + // check for an intersection with the upper and lower planes of the wall segment + if ((maplightbottomleftztop[1]) || + (maplightbottomleft > ztop[0] && maplightbottomright < ztop[1]) || + (maplightbottomleftzbottom[1]) || + (maplightbottomleft > zbottom[0] && maplightbottomright < zbottom[1])) + { + if (!(gl.flags & RFL_NO_CLIP_PLANES)) + { + // Use hardware clipping if this cannot be done cleanly. + this->lightlist = &lightlist; + PutWall(translucent); + + goto out; + } + // crappy fallback if no clip planes available + else if (SplitWallComplex(frontsector, translucent, maplightbottomleft, maplightbottomright)) + { + goto out; + } + } + + // 3D floor is completely within this light + if (maplightbottomleft<=zbottom[0] && maplightbottomright<=zbottom[1]) + { + Put3DWall(&lightlist[i], translucent); + goto out; + } + + if (maplightbottomleft<=ztop[0] && maplightbottomright<=ztop[1] && + (maplightbottomleft!=ztop[0] || maplightbottomright!=ztop[1])) + { + copyWall1=*this; + + copyWall1.flags |= GLWF_NOSPLITLOWER; + flags |= GLWF_NOSPLITUPPER; + ztop[0]=copyWall1.zbottom[0]=maplightbottomleft; + ztop[1]=copyWall1.zbottom[1]=maplightbottomright; + tcs[UPLFT].v=copyWall1.tcs[LOLFT].v=copyWall1.tcs[UPLFT].v+ + (maplightbottomleft-copyWall1.ztop[0])*(copyWall1.tcs[LOLFT].v-copyWall1.tcs[UPLFT].v)/(zbottom[0]-copyWall1.ztop[0]); + tcs[UPRGT].v=copyWall1.tcs[LORGT].v=copyWall1.tcs[UPRGT].v+ + (maplightbottomright-copyWall1.ztop[1])*(copyWall1.tcs[LORGT].v-copyWall1.tcs[UPRGT].v)/(zbottom[1]-copyWall1.ztop[1]); + copyWall1.Put3DWall(&lightlist[i], translucent); + } + if (ztop[0]==zbottom[0] && ztop[1]==zbottom[1]) + { + //::SplitWall.Unclock(); + goto out; + } + } + } + + Put3DWall(&lightlist[lightlist.Size()-1], translucent); + +out: + lightlevel=origlight; + Colormap=origcm; + flags &= ~GLWF_NOSPLITUPPER; + this->lightlist = NULL; + //::SplitWall.Unclock(); +} + + +//========================================================================== +// +// +// +//========================================================================== +bool GLWall::DoHorizon(seg_t * seg,sector_t * fs, vertex_t * v1,vertex_t * v2) +{ + GLHorizonInfo hi; + lightlist_t * light; + + // ZDoom doesn't support slopes in a horizon sector so I won't either! + ztop[1] = ztop[0] = fs->GetPlaneTexZ(sector_t::ceiling); + zbottom[1] = zbottom[0] = fs->GetPlaneTexZ(sector_t::floor); + + if (ViewPos.Z < fs->GetPlaneTexZ(sector_t::ceiling)) + { + if (ViewPos.Z > fs->GetPlaneTexZ(sector_t::floor)) + zbottom[1] = zbottom[0] = ViewPos.Z; + + if (fs->GetTexture(sector_t::ceiling) == skyflatnum) + { + SkyPlane(fs, sector_t::ceiling, false); + } + else + { + hi.plane.GetFromSector(fs, sector_t::ceiling); + hi.lightlevel = gl_ClampLight(fs->GetCeilingLight()); + hi.colormap = fs->ColorMap; + + if (fs->e->XFloor.ffloors.Size()) + { + light = P_GetPlaneLight(fs, &fs->ceilingplane, true); + + if(!(fs->GetFlags(sector_t::ceiling)&PLANEF_ABSLIGHTING)) hi.lightlevel = gl_ClampLight(*light->p_lightlevel); + hi.colormap.LightColor = (light->extra_colormap)->Color; + } + + if (gl_fixedcolormap) hi.colormap.Clear(); + horizon = &hi; + PutPortal(PORTALTYPE_HORIZON); + } + ztop[1] = ztop[0] = zbottom[0]; + } + + if (ViewPos.Z > fs->GetPlaneTexZ(sector_t::floor)) + { + zbottom[1] = zbottom[0] = fs->GetPlaneTexZ(sector_t::floor); + if (fs->GetTexture(sector_t::floor) == skyflatnum) + { + SkyPlane(fs, sector_t::floor, false); + } + else + { + hi.plane.GetFromSector(fs, sector_t::floor); + hi.lightlevel = gl_ClampLight(fs->GetFloorLight()); + hi.colormap = fs->ColorMap; + + if (fs->e->XFloor.ffloors.Size()) + { + light = P_GetPlaneLight(fs, &fs->floorplane, false); + + if(!(fs->GetFlags(sector_t::floor)&PLANEF_ABSLIGHTING)) hi.lightlevel = gl_ClampLight(*light->p_lightlevel); + hi.colormap.LightColor = (light->extra_colormap)->Color; + } + + if (gl_fixedcolormap) hi.colormap.Clear(); + horizon = &hi; + PutPortal(PORTALTYPE_HORIZON); + } + } + return true; +} + +//========================================================================== +// +// +// +//========================================================================== +bool GLWall::SetWallCoordinates(seg_t * seg, FTexCoordInfo *tci, float texturetop, + float topleft, float topright, float bottomleft, float bottomright, float t_ofs) +{ + // + // + // set up texture coordinate stuff + // + // + float l_ul; + float texlength; + + if (gltexture) + { + float length = seg->sidedef ? seg->sidedef->TexelLength : Dist2(glseg.x1, glseg.y1, glseg.x2, glseg.y2); + + l_ul = tci->FloatToTexU(tci->TextureOffset(t_ofs)); + texlength = tci->FloatToTexU(length); + } + else + { + tci = NULL; + l_ul = 0; + texlength = 0; + } + + + // + // + // set up coordinates for the left side of the polygon + // + // check left side for intersections + if (topleft >= bottomleft) + { + // normal case + ztop[0] = topleft; + zbottom[0] = bottomleft; + + if (tci) + { + tcs[UPLFT].v = tci->FloatToTexV(-ztop[0] + texturetop); + tcs[LOLFT].v = tci->FloatToTexV(-zbottom[0] + texturetop); + } + } + else + { + // ceiling below floor - clip to the visible part of the wall + float dch = topright - topleft; + float dfh = bottomright - bottomleft; + float inter_x = (bottomleft - topleft) / (dch - dfh); + + float inter_y = topleft + inter_x * dch; + + glseg.x1 = glseg.x1 + inter_x * (glseg.x2 - glseg.x1); + glseg.y1 = glseg.y1 + inter_x * (glseg.y2 - glseg.y1); + glseg.fracleft = inter_x; + + zbottom[0] = ztop[0] = inter_y; + + if (tci) + { + tcs[LOLFT].v = tcs[UPLFT].v = tci->FloatToTexV(-ztop[0] + texturetop); + } + } + + // + // + // set up coordinates for the right side of the polygon + // + // check left side for intersections + if (topright >= bottomright) + { + // normal case + ztop[1] = topright; + zbottom[1] = bottomright; + + if (tci) + { + tcs[UPRGT].v = tci->FloatToTexV(-ztop[1] + texturetop); + tcs[LORGT].v = tci->FloatToTexV(-zbottom[1] + texturetop); + } + } + else + { + // ceiling below floor - clip to the visible part of the wall + float dch = topright - topleft; + float dfh = bottomright - bottomleft; + float inter_x = (bottomleft - topleft) / (dch - dfh); + + float inter_y = topleft + inter_x * dch; + + glseg.x2 = glseg.x1 + inter_x * (glseg.x2 - glseg.x1); + glseg.y2 = glseg.y1 + inter_x * (glseg.y2 - glseg.y1); + glseg.fracright = inter_x; + + zbottom[1] = ztop[1] = inter_y; + if (tci) + { + tcs[LORGT].v = tcs[UPRGT].v = tci->FloatToTexV(-ztop[1] + texturetop); + } + } + + tcs[UPLFT].u = tcs[LOLFT].u = l_ul + texlength * glseg.fracleft; + tcs[UPRGT].u = tcs[LORGT].u = l_ul + texlength * glseg.fracright; + + if (gltexture != NULL) + { + bool normalize = false; + if (gltexture->tex->bHasCanvas) normalize = true; + else if (flags & GLT_CLAMPY) + { + // for negative scales we can get negative coordinates here. + normalize = (tcs[UPLFT].v > tcs[LOLFT].v || tcs[UPRGT].v > tcs[LORGT].v); + } + if (normalize) + { + // we have to shift the y-coordinate from [-1..0] to [0..1] when using texture clamping with a negative scale + tcs[UPLFT].v += 1.f; + tcs[UPRGT].v += 1.f; + tcs[LOLFT].v += 1.f; + tcs[LORGT].v += 1.f; + } + } + + return true; +} + +//========================================================================== +// +// Do some tweaks with the texture coordinates to reduce visual glitches +// +//========================================================================== + +void GLWall::CheckTexturePosition() +{ + float sub; + + if (gltexture->tex->bHasCanvas) return; + + // clamp texture coordinates to a reasonable range. + // Extremely large values can cause visual problems + if (tcs[UPLFT].v < tcs[UPRGT].v) + { + sub = float(xs_FloorToInt(tcs[UPLFT].v)); + } + else + { + sub = float(xs_FloorToInt(tcs[UPRGT].v)); + } + tcs[UPLFT].v -= sub; + tcs[UPRGT].v -= sub; + tcs[LOLFT].v -= sub; + tcs[LORGT].v -= sub; + + if ((tcs[UPLFT].v == 0.f && tcs[UPRGT].v == 0.f && tcs[LOLFT].v <= 1.f && tcs[LORGT].v <= 1.f) || + (tcs[UPLFT].v >= 0.f && tcs[UPRGT].v >= 0.f && tcs[LOLFT].v == 1.f && tcs[LORGT].v == 1.f)) + { + flags |= GLT_CLAMPY; + } + + // Check if this is marked as a skybox and if so, do the same for x. + // This intentionally only tests the seg's frontsector. + if (seg->frontsector->special == GLSector_Skybox) + { + sub = (float)xs_FloorToInt(tcs[UPLFT].u); + tcs[UPLFT].u -= sub; + tcs[UPRGT].u -= sub; + tcs[LOLFT].u -= sub; + tcs[LORGT].u -= sub; + if ((tcs[UPLFT].u == 0.f && tcs[LOLFT].u == 0.f && tcs[UPRGT].u <= 1.f && tcs[LORGT].u <= 1.f) || + (tcs[UPLFT].u >= 0.f && tcs[LOLFT].u >= 0.f && tcs[UPRGT].u == 1.f && tcs[LORGT].u == 1.f)) + { + flags |= GLT_CLAMPX; + } + } +} + +//========================================================================== +// +// Handle one sided walls, upper and lower texture +// +//========================================================================== +void GLWall::DoTexture(int _type,seg_t * seg, int peg, + float ceilingrefheight,float floorrefheight, + float topleft,float topright, + float bottomleft,float bottomright, + float v_offset) +{ + if (topleft<=bottomleft && topright<=bottomright) return; + + // The Vertex values can be destroyed in this function and must be restored aferward! + GLSeg glsave=glseg; + float flh=ceilingrefheight-floorrefheight; + int texpos; + BYTE savedflags = flags; + + switch (_type) + { + case RENDERWALL_TOP: + texpos = side_t::top; + break; + case RENDERWALL_BOTTOM: + texpos = side_t::bottom; + break; + default: + texpos = side_t::mid; + break; + } + + FTexCoordInfo tci; + + gltexture->GetTexCoordInfo(&tci, seg->sidedef, texpos); + + type = _type; + + float floatceilingref = ceilingrefheight + tci.RowOffset(seg->sidedef->GetTextureYOffset(texpos)); + if (peg) floatceilingref += tci.mRenderHeight - flh - v_offset; + + if (!SetWallCoordinates(seg, &tci, floatceilingref, topleft, topright, bottomleft, bottomright, + seg->sidedef->GetTextureXOffset(texpos))) return; + + if (seg->linedef->special == Line_Mirror && _type == RENDERWALL_M1S && gl_mirrors) + { + PutPortal(PORTALTYPE_MIRROR); + } + else + { + + CheckTexturePosition(); + + // Add this wall to the render list + sector_t * sec = sub ? sub->sector : seg->frontsector; + if (sec->e->XFloor.lightlist.Size()==0 || gl_fixedcolormap) PutWall(false); + else SplitWall(sec, false); + } + + glseg = glsave; + flags = savedflags; +} + + +//========================================================================== +// +// +// +//========================================================================== + +void GLWall::DoMidTexture(seg_t * seg, bool drawfogboundary, + sector_t * front, sector_t * back, + sector_t * realfront, sector_t * realback, + float fch1, float fch2, float ffh1, float ffh2, + float bch1, float bch2, float bfh1, float bfh2) + +{ + FTexCoordInfo tci; + float topleft,bottomleft,topright,bottomright; + GLSeg glsave=glseg; + float texturetop, texturebottom; + bool wrap = (seg->linedef->flags&ML_WRAP_MIDTEX) || (seg->sidedef->Flags&WALLF_WRAP_MIDTEX); + bool mirrory = false; + + // + // + // Get the base coordinates for the texture + // + // + if (gltexture) + { + // Align the texture to the ORIGINAL sector's height!! + // At this point slopes don't matter because they don't affect the texture's z-position + + gltexture->GetTexCoordInfo(&tci, seg->sidedef, side_t::mid); + if (tci.mRenderHeight < 0) + { + mirrory = true; + tci.mRenderHeight = -tci.mRenderHeight; + tci.mScale.Y = -tci.mScale.Y; + } + float rowoffset = tci.RowOffset(seg->sidedef->GetTextureYOffset(side_t::mid)); + if ((seg->linedef->flags & ML_DONTPEGBOTTOM) >0) + { + texturebottom = MAX(realfront->GetPlaneTexZ(sector_t::floor), realback->GetPlaneTexZ(sector_t::floor)) + rowoffset; + texturetop = texturebottom + tci.mRenderHeight; + } + else + { + texturetop = MIN(realfront->GetPlaneTexZ(sector_t::ceiling), realback->GetPlaneTexZ(sector_t::ceiling)) + rowoffset; + texturebottom = texturetop - tci.mRenderHeight; + } + } + else texturetop=texturebottom=0; + + // + // + // Depending on missing textures and possible plane intersections + // decide which planes to use for the polygon + // + // + if (realfront!=realback || drawfogboundary || wrap || realfront->GetHeightSec()) + { + // + // + // Set up the top + // + // + FTexture * tex = TexMan(seg->sidedef->GetTexture(side_t::top)); + if (!tex || tex->UseType==FTexture::TEX_Null) + { + if (front->GetTexture(sector_t::ceiling) == skyflatnum && + back->GetTexture(sector_t::ceiling) == skyflatnum) + { + // intra-sky lines do not clip the texture at all if there's no upper texture + topleft = topright = texturetop; + } + else + { + // texture is missing - use the higher plane + topleft = MAX(bch1,fch1); + topright = MAX(bch2,fch2); + } + } + else if ((bch1>fch1 || bch2>fch2) && + (seg->frontsector->GetTexture(sector_t::ceiling)!=skyflatnum || seg->backsector->GetTexture(sector_t::ceiling)==skyflatnum)) + // (!((bch1<=fch1 && bch2<=fch2) || (bch1>=fch1 && bch2>=fch2))) + { + // Use the higher plane and let the geometry clip the extruding part + topleft = bch1; + topright = bch2; + } + else + { + // But not if there can be visual artifacts. + topleft = MIN(bch1,fch1); + topright = MIN(bch2,fch2); + } + + // + // + // Set up the bottom + // + // + tex = TexMan(seg->sidedef->GetTexture(side_t::bottom)); + if (!tex || tex->UseType==FTexture::TEX_Null) + { + // texture is missing - use the lower plane + bottomleft = MIN(bfh1,ffh1); + bottomright = MIN(bfh2,ffh2); + } + else if (bfh1=ffh1 && bfh2>=ffh2))) + { + // the floor planes intersect. Use the backsector's floor for drawing so that + // drawing the front sector's plane clips the polygon automatically. + bottomleft = bfh1; + bottomright = bfh2; + } + else + { + // normal case - use the higher plane + bottomleft = MAX(bfh1,ffh1); + bottomright = MAX(bfh2,ffh2); + } + + // + // + // if we don't need a fog sheet let's clip away some unnecessary parts of the polygon + // + // + if (!drawfogboundary && !wrap) + { + if (texturetopbottomleft && texturebottom>bottomright) bottomleft=bottomright=texturebottom; + } + } + else + { + // + // + // if both sides of the line are in the same sector and the sector + // doesn't have a Transfer_Heights special don't clip to the planes + // Clipping to the planes is not necessary and can even produce + // unwanted side effects. + // + // + topleft=topright=texturetop; + bottomleft=bottomright=texturebottom; + } + + // nothing visible - skip the rest + if (topleft<=bottomleft && topright<=bottomright) return; + + + // + // + // set up texture coordinate stuff + // + // + float t_ofs = seg->sidedef->GetTextureXOffset(side_t::mid); + + if (gltexture) + { + // First adjust the texture offset so that the left edge of the linedef is inside the range [0..1]. + float texwidth = tci.TextureAdjustWidth(); + + if (t_ofs >= 0) + { + float div = t_ofs / texwidth; + t_ofs = (div - xs_FloorToInt(div)) * texwidth; + } + else + { + float div = (-t_ofs) / texwidth; + t_ofs = texwidth - (div - xs_FloorToInt(div)) * texwidth; + } + + + // Now check whether the linedef is completely within the texture range of [0..1]. + // If so we should use horizontal texture clamping to prevent filtering artifacts + // at the edges. + + float textureoffset = tci.TextureOffset(t_ofs); + int righttex = int(textureoffset) + seg->sidedef->TexelLength; + + if ((textureoffset == 0 && righttex <= tci.mRenderWidth) || + (textureoffset >= 0 && righttex == tci.mRenderWidth)) + { + flags |= GLT_CLAMPX; + } + else + { + flags &= ~GLT_CLAMPX; + } + if (!wrap) + { + flags |= GLT_CLAMPY; + } + } + if (mirrory) + { + tci.mRenderHeight = -tci.mRenderHeight; + tci.mScale.Y = -tci.mScale.Y; + } + SetWallCoordinates(seg, &tci, texturetop, topleft, topright, bottomleft, bottomright, t_ofs); + + // + // + // draw fog sheet if required + // + // + if (drawfogboundary) + { + flags |= GLWF_NOSPLITUPPER|GLWF_NOSPLITLOWER; + type=RENDERWALL_FOGBOUNDARY; + FMaterial *savetex = gltexture; + gltexture = NULL; + PutWall(true); + if (!savetex) + { + flags &= ~(GLWF_NOSPLITUPPER|GLWF_NOSPLITLOWER); + return; + } + gltexture = savetex; + type=RENDERWALL_M2SNF; + } + else type=RENDERWALL_M2S; + + // + // + // set up alpha blending + // + // + if (seg->linedef->alpha != 0) + { + bool translucent = false; + + switch (seg->linedef->flags& ML_ADDTRANS)//TRANSBITS) + { + case 0: + RenderStyle=STYLE_Translucent; + alpha = seg->linedef->alpha; + translucent =alpha < 1. || (gltexture && gltexture->GetTransparent()); + break; + + case ML_ADDTRANS: + RenderStyle=STYLE_Add; + alpha = seg->linedef->alpha; + translucent=true; + break; + } + + // + // + // for textures with large empty areas only the visible parts are drawn. + // If these textures come too close to the camera they severely affect performance + // if stacked closely together + // Recognizing vertical gaps is rather simple and well worth the effort. + // + // + FloatRect *splitrect; + int v = gltexture->GetAreas(&splitrect); + if (seg->frontsector == seg->backsector) flags |= GLWF_NOSPLIT; // we don't need to do vertex splits if a line has both sides in the same sector + if (v>0 && !drawfogboundary && !(seg->linedef->flags&ML_WRAP_MIDTEX)) + { + // split the poly! + GLWall split; + int i,t=0; + float v_factor=(zbottom[0]-ztop[0])/(tcs[LOLFT].v-tcs[UPLFT].v); + // only split the vertical area of the polygon that does not contain slopes. + float splittopv = MAX(tcs[UPLFT].v, tcs[UPRGT].v); + float splitbotv = MIN(tcs[LOLFT].v, tcs[LORGT].v); + + // this is split vertically into sections. + for(i=0;i=splitbotv) break; + + float splitbot=splitrect[i].top+splitrect[i].height; + + // the current segment is above the top line of the splittable area + if (splitbot<=splittopv) continue; + + split=*this; + + // the top line of the current segment is inside the splittable area + // use the splitrect's top as top of this segment + // if not use the top of the remaining polygon + if (splitrect[i].top>splittopv) + { + split.ztop[0]=split.ztop[1]= ztop[0]+v_factor*(splitrect[i].top-tcs[UPLFT].v); + split.tcs[UPLFT].v=split.tcs[UPRGT].v=splitrect[i].top; + } + // the bottom line of the current segment is inside the splittable area + // use the splitrect's bottom as bottom of this segment + // if not use the bottom of the remaining polygon + if (splitbot<=splitbotv) + { + split.zbottom[0]=split.zbottom[1]=ztop[0]+v_factor*(splitbot-tcs[UPLFT].v); + split.tcs[LOLFT].v=split.tcs[LORGT].v=splitbot; + } + // + // + // Draw the stuff + // + // + if (realfront->e->XFloor.lightlist.Size()==0 || gl_fixedcolormap) split.PutWall(translucent); + else split.SplitWall(realfront, translucent); + + t=1; + } + render_texsplit+=t; + } + else + { + // + // + // Draw the stuff without splitting + // + // + if (realfront->e->XFloor.lightlist.Size()==0 || gl_fixedcolormap) PutWall(translucent); + else SplitWall(realfront, translucent); + } + alpha=1.0f; + } + // restore some values that have been altered in this function + glseg=glsave; + flags&=~(GLT_CLAMPX|GLT_CLAMPY|GLWF_NOSPLITUPPER|GLWF_NOSPLITLOWER); +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::BuildFFBlock(seg_t * seg, F3DFloor * rover, + float ff_topleft, float ff_topright, + float ff_bottomleft, float ff_bottomright) +{ + side_t * mastersd = rover->master->sidedef[0]; + float to; + lightlist_t * light; + bool translucent; + int savelight = lightlevel; + FColormap savecolor = Colormap; + float ul; + float texlength; + FTexCoordInfo tci; + + if (rover->flags&FF_FOG) + { + if (!gl_fixedcolormap) + { + // this may not yet be done + light = P_GetPlaneLight(rover->target, rover->top.plane, true); + Colormap.Clear(); + Colormap.LightColor = (light->extra_colormap)->Fade; + // the fog plane defines the light level, not the front sector + lightlevel = gl_ClampLight(*light->p_lightlevel); + gltexture = NULL; + type = RENDERWALL_FFBLOCK; + } + else return; + } + else + { + + if (rover->flags&FF_UPPERTEXTURE) + { + gltexture = FMaterial::ValidateTexture(seg->sidedef->GetTexture(side_t::top), false, true); + if (!gltexture) return; + gltexture->GetTexCoordInfo(&tci, seg->sidedef, side_t::top); + } + else if (rover->flags&FF_LOWERTEXTURE) + { + gltexture = FMaterial::ValidateTexture(seg->sidedef->GetTexture(side_t::bottom), false, true); + if (!gltexture) return; + gltexture->GetTexCoordInfo(&tci, seg->sidedef, side_t::bottom); + } + else + { + gltexture = FMaterial::ValidateTexture(mastersd->GetTexture(side_t::mid), false, true); + if (!gltexture) return; + gltexture->GetTexCoordInfo(&tci, mastersd, side_t::mid); + } + + to = (rover->flags&(FF_UPPERTEXTURE | FF_LOWERTEXTURE)) ? 0 : tci.TextureOffset(mastersd->GetTextureXOffset(side_t::mid)); + + ul = tci.FloatToTexU(to + tci.TextureOffset(seg->sidedef->GetTextureXOffset(side_t::mid))); + + texlength = tci.FloatToTexU(seg->sidedef->TexelLength); + + tcs[UPLFT].u = tcs[LOLFT].u = ul + texlength * glseg.fracleft; + tcs[UPRGT].u = tcs[LORGT].u = ul + texlength * glseg.fracright; + + float rowoffset = tci.RowOffset(seg->sidedef->GetTextureYOffset(side_t::mid)); + to = (rover->flags&(FF_UPPERTEXTURE | FF_LOWERTEXTURE)) ? + 0.f : tci.RowOffset(mastersd->GetTextureYOffset(side_t::mid)); + + to += rowoffset + rover->top.model->GetPlaneTexZ(rover->top.isceiling); + + tcs[UPLFT].v = tci.FloatToTexV(to - ff_topleft); + tcs[UPRGT].v = tci.FloatToTexV(to - ff_topright); + tcs[LOLFT].v = tci.FloatToTexV(to - ff_bottomleft); + tcs[LORGT].v = tci.FloatToTexV(to - ff_bottomright); + type = RENDERWALL_FFBLOCK; + CheckTexturePosition(); + } + + ztop[0] = ff_topleft; + ztop[1] = ff_topright; + zbottom[0] = ff_bottomleft;//-0.001f; + zbottom[1] = ff_bottomright; + + if (rover->flags&(FF_TRANSLUCENT | FF_ADDITIVETRANS | FF_FOG)) + { + alpha = rover->alpha / 255.0f; + RenderStyle = (rover->flags&FF_ADDITIVETRANS) ? STYLE_Add : STYLE_Translucent; + translucent = true; + type = gltexture ? RENDERWALL_M2S : RENDERWALL_COLOR; + } + else + { + alpha = 1.0f; + RenderStyle = STYLE_Normal; + translucent = false; + } + + sector_t * sec = sub ? sub->sector : seg->frontsector; + + if (sec->e->XFloor.lightlist.Size() == 0 || gl_fixedcolormap) PutWall(translucent); + else SplitWall(sec, translucent); + + alpha = 1.0f; + lightlevel = savelight; + Colormap = savecolor; + flags &= ~GLT_CLAMPY; +} + + +//========================================================================== +// +// +// +//========================================================================== + +__forceinline void GLWall::GetPlanePos(F3DFloor::planeref *planeref, float &left, float &right) +{ + left=planeref->plane->ZatPoint(vertexes[0]); + right=planeref->plane->ZatPoint(vertexes[1]); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::InverseFloors(seg_t * seg, sector_t * frontsector, + float topleft, float topright, + float bottomleft, float bottomright) +{ + TArray & frontffloors = frontsector->e->XFloor.ffloors; + + for (unsigned int i = 0; i < frontffloors.Size(); i++) + { + F3DFloor * rover = frontffloors[i]; + if (!(rover->flags&FF_EXISTS)) continue; + if (!(rover->flags&FF_RENDERSIDES)) continue; + if (!(rover->flags&(FF_INVERTSIDES | FF_ALLSIDES))) continue; + + float ff_topleft; + float ff_topright; + float ff_bottomleft; + float ff_bottomright; + + GetPlanePos(&rover->top, ff_topleft, ff_topright); + GetPlanePos(&rover->bottom, ff_bottomleft, ff_bottomright); + + // above ceiling + if (ff_bottomleft > topleft && ff_bottomright > topright) continue; + + if (ff_topleft > topleft && ff_topright > topright) + { + // the new section overlaps with the previous one - clip it! + ff_topleft = topleft; + ff_topright = topright; + } + if (ff_bottomleft < bottomleft && ff_bottomright < bottomright) + { + ff_bottomleft = bottomleft; + ff_bottomright = bottomright; + } + if (ff_topleft < ff_bottomleft || ff_topright < ff_bottomright) continue; + + BuildFFBlock(seg, rover, ff_topleft, ff_topright, ff_bottomleft, ff_bottomright); + topleft = ff_bottomleft; + topright = ff_bottomright; + + if (topleft <= bottomleft && topright <= bottomright) return; + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::ClipFFloors(seg_t * seg, F3DFloor * ffloor, sector_t * frontsector, + float topleft, float topright, + float bottomleft, float bottomright) +{ + TArray & frontffloors = frontsector->e->XFloor.ffloors; + + int flags = ffloor->flags & (FF_SWIMMABLE | FF_TRANSLUCENT); + + for (unsigned int i = 0; i < frontffloors.Size(); i++) + { + F3DFloor * rover = frontffloors[i]; + if (!(rover->flags&FF_EXISTS)) continue; + if (!(rover->flags&FF_RENDERSIDES)) continue; + if ((rover->flags&(FF_SWIMMABLE | FF_TRANSLUCENT)) != flags) continue; + + float ff_topleft; + float ff_topright; + float ff_bottomleft; + float ff_bottomright; + + GetPlanePos(&rover->top, ff_topleft, ff_topright); + + // we are completely below the bottom so unless there are some + // (unsupported) intersections there won't be any more floors that + // could clip this one. + if (ff_topleft < bottomleft && ff_topright < bottomright) goto done; + + GetPlanePos(&rover->bottom, ff_bottomleft, ff_bottomright); + // above top line? + if (ff_bottomleft > topleft && ff_bottomright > topright) continue; + + // overlapping the top line + if (ff_topleft >= topleft && ff_topright >= topright) + { + // overlapping with the entire range + if (ff_bottomleft <= bottomleft && ff_bottomright <= bottomright) return; + else if (ff_bottomleft > bottomleft && ff_bottomright > bottomright) + { + topleft = ff_bottomleft; + topright = ff_bottomright; + } + else + { + // an intersecting case. + // proper handling requires splitting but + // I don't need this right now. + } + } + else if (ff_topleft <= topleft && ff_topright <= topright) + { + BuildFFBlock(seg, ffloor, topleft, topright, ff_topleft, ff_topright); + if (ff_bottomleft <= bottomleft && ff_bottomright <= bottomright) return; + topleft = ff_bottomleft; + topright = ff_bottomright; + } + else + { + // an intersecting case. + // proper handling requires splitting but + // I don't need this right now. + } + } + +done: + // if the program reaches here there is one block left to draw + BuildFFBlock(seg, ffloor, topleft, topright, bottomleft, bottomright); +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::DoFFloorBlocks(seg_t * seg, sector_t * frontsector, sector_t * backsector, + float fch1, float fch2, float ffh1, float ffh2, + float bch1, float bch2, float bfh1, float bfh2) + +{ + TArray & backffloors = backsector->e->XFloor.ffloors; + float topleft, topright, bottomleft, bottomright; + bool renderedsomething = false; + + // if the ceilings intersect use the backsector's height because this sector's ceiling will + // obstruct the redundant parts. + + if (fch1 < bch1 && fch2 < bch2) + { + topleft = fch1; + topright = fch2; + } + else + { + topleft = bch1; + topright = bch2; + } + + if (ffh1 > bfh1 && ffh2 > bfh2) + { + bottomleft = ffh1; + bottomright = ffh2; + } + else + { + bottomleft = bfh1; + bottomright = bfh2; + } + + for (unsigned int i = 0; i < backffloors.Size(); i++) + { + F3DFloor * rover = backffloors[i]; + if (!(rover->flags&FF_EXISTS)) continue; + if (!(rover->flags&FF_RENDERSIDES) || (rover->flags&FF_INVERTSIDES)) continue; + + float ff_topleft; + float ff_topright; + float ff_bottomleft; + float ff_bottomright; + + GetPlanePos(&rover->top, ff_topleft, ff_topright); + GetPlanePos(&rover->bottom, ff_bottomleft, ff_bottomright); + + // completely above ceiling + if (ff_bottomleft > topleft && ff_bottomright > topright && !renderedsomething) continue; + + if (ff_topleft > topleft && ff_topright > topright) + { + // the new section overlaps with the previous one - clip it! + ff_topleft = topleft; + ff_topright = topright; + } + + // do all inverse floors above the current one it there is a gap between the + // last 3D floor and this one. + if (topleft > ff_topleft && topright > ff_topright) + InverseFloors(seg, frontsector, topleft, topright, ff_topleft, ff_topright); + + // if translucent or liquid clip away adjoining parts of the same type of FFloors on the other side + if (rover->flags&(FF_SWIMMABLE | FF_TRANSLUCENT)) + ClipFFloors(seg, rover, frontsector, ff_topleft, ff_topright, ff_bottomleft, ff_bottomright); + else + BuildFFBlock(seg, rover, ff_topleft, ff_topright, ff_bottomleft, ff_bottomright); + + topleft = ff_bottomleft; + topright = ff_bottomright; + renderedsomething = true; + if (topleft <= bottomleft && topright <= bottomright) return; + } + + // draw all inverse floors below the lowest one + if (frontsector->e->XFloor.ffloors.Size() > 0) + { + if (topleft > bottomleft || topright > bottomright) + InverseFloors(seg, frontsector, topleft, topright, bottomleft, bottomright); + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::Process(seg_t *seg, sector_t * frontsector, sector_t * backsector) +{ + vertex_t * v1, *v2; + float fch1; + float ffh1; + float fch2; + float ffh2; + float frefz, crefz; + sector_t * realfront; + sector_t * realback; + sector_t * segfront; + sector_t * segback; + +#ifdef _DEBUG + if (seg->linedef - lines < 4) + { + int a = 0; + } +#endif + + // note: we always have a valid sidedef and linedef reference when getting here. + + this->seg = seg; + vertindex = 0; + vertcount = 0; + + if ((seg->sidedef->Flags & WALLF_POLYOBJ) && seg->backsector) + { + // Textures on 2-sided polyobjects are aligned to the actual seg's sectors + segfront = realfront = seg->frontsector; + segback = realback = seg->backsector; + } + else + { + // Need these for aligning the textures + realfront = §ors[frontsector->sectornum]; + realback = backsector ? §ors[backsector->sectornum] : NULL; + segfront = frontsector; + segback = backsector; + } + frefz = realfront->GetPlaneTexZ(sector_t::floor); + crefz = realfront->GetPlaneTexZ(sector_t::ceiling); + + if (seg->sidedef == seg->linedef->sidedef[0]) + { + v1 = seg->linedef->v1; + v2 = seg->linedef->v2; + } + else + { + v1 = seg->linedef->v2; + v2 = seg->linedef->v1; + } + + if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + glseg.fracleft = 0; + glseg.fracright = 1; + if (gl_seamless) + { + if (v1->dirty) gl_RecalcVertexHeights(v1); + if (v2->dirty) gl_RecalcVertexHeights(v2); + } + } + else // polyobjects must be rendered per seg. + { + if (fabs(v1->fX() - v2->fX()) > fabs(v1->fY() - v2->fY())) + { + glseg.fracleft = (seg->v1->fX() - v1->fX()) / (v2->fX() - v1->fX()); + glseg.fracright = (seg->v2->fX() - v1->fX()) / float(v2->fX() - v1->fX()); + } + else + { + glseg.fracleft = (seg->v1->fY() - v1->fY()) / (v2->fY() - v1->fY()); + glseg.fracright = (seg->v2->fY() - v1->fY()) / (v2->fY() - v1->fY()); + } + v1 = seg->v1; + v2 = seg->v2; + } + + + vertexes[0] = v1; + vertexes[1] = v2; + + glseg.x1 = v1->fX(); + glseg.y1 = v1->fY(); + glseg.x2 = v2->fX(); + glseg.y2 = v2->fY(); + Colormap = frontsector->ColorMap; + flags = 0; + dynlightindex = -1; + lightlist = NULL; + + int rel = 0; + int orglightlevel = gl_ClampLight(frontsector->lightlevel); + bool foggy = (!gl_isBlack(Colormap.FadeColor) || level.flags&LEVEL_HASFADETABLE); // fog disables fake contrast + lightlevel = gl_ClampLight(seg->sidedef->GetLightLevel(foggy, orglightlevel, false, &rel)); + if (orglightlevel >= 253) // with the software renderer fake contrast won't be visible above this. + { + rellight = 0; + } + else if (lightlevel - rel > 256) // the brighter part of fake contrast will be clamped so also clamp the darker part by the same amount for better looks + { + rellight = 256 - lightlevel + rel; + } + else + { + rellight = rel; + } + + alpha = 1.0f; + RenderStyle = STYLE_Normal; + gltexture = NULL; + + topflat = frontsector->GetTexture(sector_t::ceiling); // for glowing textures. These must be saved because + bottomflat = frontsector->GetTexture(sector_t::floor); // the sector passed here might be a temporary copy. + topplane = frontsector->ceilingplane; + bottomplane = frontsector->floorplane; + + zfloor[0] = ffh1 = segfront->floorplane.ZatPoint(v1); + zfloor[1] = ffh2 = segfront->floorplane.ZatPoint(v2); + zceil[0] = fch1 = segfront->ceilingplane.ZatPoint(v1); + zceil[1] = fch2 = segfront->ceilingplane.ZatPoint(v2); + + if (seg->linedef->special == Line_Horizon) + { + SkyNormal(frontsector, v1, v2); + DoHorizon(seg, frontsector, v1, v2); + return; + } + + //return; + // [GZ] 3D middle textures are necessarily two-sided, even if they lack the explicit two-sided flag + if (!backsector || !(seg->linedef->flags&(ML_TWOSIDED | ML_3DMIDTEX))) // one sided + { + // sector's sky + SkyNormal(frontsector, v1, v2); + + if (seg->linedef->isVisualPortal()) + { + lineportal = linePortalToGL[seg->linedef->portalindex]; + ztop[0] = zceil[0]; + ztop[1] = zceil[1]; + zbottom[0] = zfloor[0]; + zbottom[1] = zfloor[1]; + PutPortal(PORTALTYPE_LINETOLINE); + } + else if (seg->linedef->portaltransferred > 0) + { + SkyLine(frontsector, seg->linedef); + } + else + { + // normal texture + gltexture = FMaterial::ValidateTexture(seg->sidedef->GetTexture(side_t::mid), false, true); + if (gltexture) + { + DoTexture(RENDERWALL_M1S, seg, (seg->linedef->flags & ML_DONTPEGBOTTOM) > 0, + crefz, frefz, // must come from the original! + fch1, fch2, ffh1, ffh2, 0); + } + } + } + else // two sided + { + float bfh1 = segback->floorplane.ZatPoint(v1); + float bfh2 = segback->floorplane.ZatPoint(v2); + float bch1 = segback->ceilingplane.ZatPoint(v1); + float bch2 = segback->ceilingplane.ZatPoint(v2); + + SkyTop(seg, frontsector, backsector, v1, v2); + SkyBottom(seg, frontsector, backsector, v1, v2); + + // upper texture + if (frontsector->GetTexture(sector_t::ceiling) != skyflatnum || backsector->GetTexture(sector_t::ceiling) != skyflatnum) + { + float bch1a = bch1, bch2a = bch2; + if (frontsector->GetTexture(sector_t::floor) != skyflatnum || backsector->GetTexture(sector_t::floor) != skyflatnum) + { + // the back sector's floor obstructs part of this wall + if (ffh1 > bch1 && ffh2 > bch2) + { + bch2a = ffh2; + bch1a = ffh1; + } + } + + if (bch1a < fch1 || bch2a < fch2) + { + gltexture = FMaterial::ValidateTexture(seg->sidedef->GetTexture(side_t::top), false, true); + if (gltexture) + { + DoTexture(RENDERWALL_TOP, seg, (seg->linedef->flags & (ML_DONTPEGTOP)) == 0, + crefz, realback->GetPlaneTexZ(sector_t::ceiling), + fch1, fch2, bch1a, bch2a, 0); + } + else if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + if ((frontsector->ceilingplane.isSlope() || backsector->ceilingplane.isSlope()) && + frontsector->GetTexture(sector_t::ceiling) != skyflatnum && + backsector->GetTexture(sector_t::ceiling) != skyflatnum) + { + gltexture = FMaterial::ValidateTexture(frontsector->GetTexture(sector_t::ceiling), false, true); + if (gltexture) + { + DoTexture(RENDERWALL_TOP, seg, (seg->linedef->flags & (ML_DONTPEGTOP)) == 0, + crefz, realback->GetPlaneTexZ(sector_t::ceiling), + fch1, fch2, bch1a, bch2a, 0); + } + } + else + { + // skip processing if the back is a malformed subsector + if (seg->PartnerSeg != NULL && !(seg->PartnerSeg->Subsector->hacked & 4)) + { + gl_drawinfo->AddUpperMissingTexture(seg->sidedef, sub, bch1a); + } + } + } + } + } + + + /* mid texture */ + bool isportal = seg->linedef->isVisualPortal() && seg->sidedef == seg->linedef->sidedef[0]; + sector_t *backsec = isportal? seg->linedef->getPortalDestination()->frontsector : backsector; + + bool drawfogboundary = gl_CheckFog(frontsector, backsec); + FTexture *tex = TexMan(seg->sidedef->GetTexture(side_t::mid)); + if (tex != NULL) + { + if (i_compatflags & COMPATF_MASKEDMIDTEX) + { + tex = tex->GetRawTexture(); + } + gltexture = FMaterial::ValidateTexture(tex, false); + } + else gltexture = NULL; + + if (gltexture || drawfogboundary) + { + DoMidTexture(seg, drawfogboundary, frontsector, backsector, realfront, realback, + fch1, fch2, ffh1, ffh2, bch1, bch2, bfh1, bfh2); + } + + if (isportal) + { + lineportal = linePortalToGL[seg->linedef->portalindex]; + ztop[0] = bch1; + ztop[1] = bch2; + zbottom[0] = bfh1; + zbottom[1] = bfh2; + PutPortal(PORTALTYPE_LINETOLINE); + } + else if (backsector->e->XFloor.ffloors.Size() || frontsector->e->XFloor.ffloors.Size()) + { + DoFFloorBlocks(seg, frontsector, backsector, fch1, fch2, ffh1, ffh2, bch1, bch2, bfh1, bfh2); + } + + /* bottom texture */ + // the back sector's ceiling obstructs part of this wall (specially important for sky sectors) + if (fch1 < bfh1 && fch2 < bfh2) + { + bfh1 = fch1; + bfh2 = fch2; + } + + if (bfh1 > ffh1 || bfh2 > ffh2) + { + gltexture = FMaterial::ValidateTexture(seg->sidedef->GetTexture(side_t::bottom), false, true); + if (gltexture) + { + DoTexture(RENDERWALL_BOTTOM, seg, (seg->linedef->flags & ML_DONTPEGBOTTOM) > 0, + realback->GetPlaneTexZ(sector_t::floor), frefz, + bfh1, bfh2, ffh1, ffh2, + frontsector->GetTexture(sector_t::ceiling) == skyflatnum && backsector->GetTexture(sector_t::ceiling) == skyflatnum ? + frefz - realback->GetPlaneTexZ(sector_t::ceiling) : + frefz - crefz); + } + else if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + if ((frontsector->floorplane.isSlope() || backsector->floorplane.isSlope()) && + frontsector->GetTexture(sector_t::floor) != skyflatnum && + backsector->GetTexture(sector_t::floor) != skyflatnum) + { + // render it anyway with the sector's floor texture. With a background sky + // there are ugly holes otherwise and slopes are simply not precise enough + // to mach in any case. + gltexture = FMaterial::ValidateTexture(frontsector->GetTexture(sector_t::floor), false, true); + if (gltexture) + { + DoTexture(RENDERWALL_BOTTOM, seg, (seg->linedef->flags & ML_DONTPEGBOTTOM) > 0, + realback->GetPlaneTexZ(sector_t::floor), frefz, + bfh1, bfh2, ffh1, ffh2, frefz - crefz); + } + } + else if (backsector->GetTexture(sector_t::floor) != skyflatnum) + { + // skip processing if the back is a malformed subsector + if (seg->PartnerSeg != NULL && !(seg->PartnerSeg->Subsector->hacked & 4)) + { + gl_drawinfo->AddLowerMissingTexture(seg->sidedef, sub, bfh1); + } + } + } + } + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::ProcessLowerMiniseg(seg_t *seg, sector_t * frontsector, sector_t * backsector) +{ + if (frontsector->GetTexture(sector_t::floor) == skyflatnum) return; + lightlist = NULL; + + float ffh = frontsector->GetPlaneTexZ(sector_t::floor); + float bfh = backsector->GetPlaneTexZ(sector_t::floor); + + vertindex = 0; + vertcount = 0; + if (bfh > ffh) + { + this->seg = seg; + this->sub = NULL; + + vertex_t * v1 = seg->v1; + vertex_t * v2 = seg->v2; + vertexes[0] = v1; + vertexes[1] = v2; + + glseg.x1 = v1->fX(); + glseg.y1 = v1->fY(); + glseg.x2 = v2->fX(); + glseg.y2 = v2->fY(); + glseg.fracleft = 0; + glseg.fracright = 1; + + flags = 0; + + // can't do fake contrast without a sidedef + lightlevel = gl_ClampLight(frontsector->lightlevel); + rellight = 0; + + alpha = 1.0f; + RenderStyle = STYLE_Normal; + Colormap = frontsector->ColorMap; + + topflat = frontsector->GetTexture(sector_t::ceiling); // for glowing textures + bottomflat = frontsector->GetTexture(sector_t::floor); + topplane = frontsector->ceilingplane; + bottomplane = frontsector->floorplane; + dynlightindex = -1; + + zfloor[0] = zfloor[1] = ffh; + + gltexture = FMaterial::ValidateTexture(frontsector->GetTexture(sector_t::floor), false, true); + + if (gltexture) + { + FTexCoordInfo tci; + type = RENDERWALL_BOTTOM; + gltexture->GetTexCoordInfo(&tci, 1.f, 1.f); + SetWallCoordinates(seg, &tci, bfh, bfh, bfh, ffh, ffh, 0); + PutWall(false); + } + } +} diff --git a/src/gl/scene/gl_walls_draw.cpp b/src/gl/scene/gl_walls_draw.cpp new file mode 100644 index 000000000..81164e434 --- /dev/null +++ b/src/gl/scene/gl_walls_draw.cpp @@ -0,0 +1,462 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "p_local.h" +#include "p_lnspec.h" +#include "a_sharedglobal.h" +#include "gl/gl_functions.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_dynlight.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/dynlights/gl_lightbuffer.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/scene/gl_portal.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/renderer/gl_quaddrawer.h" + +EXTERN_CVAR(Bool, gl_seamless) + +//========================================================================== +// +// Collect lights for shader +// +//========================================================================== +FDynLightData lightdata; + + +void GLWall::SetupLights() +{ + if (RenderStyle == STYLE_Add && !glset.lightadditivesurfaces) return; // no lights on additively blended surfaces. + + // check for wall types which cannot have dynamic lights on them (portal types never get here so they don't need to be checked.) + switch (type) + { + case RENDERWALL_FOGBOUNDARY: + case RENDERWALL_MIRRORSURFACE: + case RENDERWALL_COLOR: + return; + } + + float vtx[]={glseg.x1,zbottom[0],glseg.y1, glseg.x1,ztop[0],glseg.y1, glseg.x2,ztop[1],glseg.y2, glseg.x2,zbottom[1],glseg.y2}; + Plane p; + + lightdata.Clear(); + p.Init(vtx,4); + + if (!p.ValidNormal()) + { + return; + } + FLightNode *node; + if (seg->sidedef == NULL) + { + node = NULL; + } + else if (!(seg->sidedef->Flags & WALLF_POLYOBJ)) + { + node = seg->sidedef->lighthead; + } + else if (sub) + { + // Polobject segs cannot be checked per sidedef so use the subsector instead. + node = sub->lighthead; + } + else node = NULL; + + // Iterate through all dynamic lights which touch this wall and render them + while (node) + { + if (!(node->lightsource->flags2&MF2_DORMANT)) + { + iter_dlight++; + + Vector fn, pos; + + DVector3 posrel = node->lightsource->PosRelative(seg->frontsector); + float x = posrel.X; + float y = posrel.Y; + float z = posrel.Z; + float dist = fabsf(p.DistToPoint(x, z, y)); + float radius = node->lightsource->GetRadius(); + float scale = 1.0f / ((2.f * radius) - dist); + + if (radius > 0.f && dist < radius) + { + Vector nearPt, up, right; + + pos.Set(x,z,y); + fn=p.Normal(); + fn.GetRightUp(right, up); + + Vector tmpVec = fn * dist; + nearPt = pos + tmpVec; + + Vector t1; + int outcnt[4]={0,0,0,0}; + texcoord tcs[4]; + + // do a quick check whether the light touches this polygon + for(int i=0;i<4;i++) + { + t1.Set(&vtx[i*3]); + Vector nearToVert = t1 - nearPt; + tcs[i].u = (nearToVert.Dot(right) * scale) + 0.5f; + tcs[i].v = (nearToVert.Dot(up) * scale) + 0.5f; + + if (tcs[i].u<0) outcnt[0]++; + if (tcs[i].u>1) outcnt[1]++; + if (tcs[i].v<0) outcnt[2]++; + if (tcs[i].v>1) outcnt[3]++; + + } + if (outcnt[0]!=4 && outcnt[1]!=4 && outcnt[2]!=4 && outcnt[3]!=4) + { + gl_GetLight(seg->frontsector->PortalGroup, p, node->lightsource, true, lightdata); + } + } + } + node = node->nextLight; + } + + dynlightindex = GLRenderer->mLights->UploadLights(lightdata); +} + +//========================================================================== +// +// build the vertices for this wall +// +//========================================================================== + +void GLWall::MakeVertices(bool nosplit) +{ + if (vertcount == 0) + { + bool split = (gl_seamless && !nosplit && seg->sidedef != NULL && !(seg->sidedef->Flags & WALLF_POLYOBJ) && !(flags & GLWF_NOSPLIT)); + + FFlatVertex *ptr = GLRenderer->mVBO->GetBuffer(); + + ptr->Set(glseg.x1, zbottom[0], glseg.y1, tcs[LOLFT].u, tcs[LOLFT].v); + ptr++; + if (split && glseg.fracleft == 0) SplitLeftEdge(ptr); + ptr->Set(glseg.x1, ztop[0], glseg.y1, tcs[UPLFT].u, tcs[UPLFT].v); + ptr++; + if (split && !(flags & GLWF_NOSPLITUPPER)) SplitUpperEdge(ptr); + ptr->Set(glseg.x2, ztop[1], glseg.y2, tcs[UPRGT].u, tcs[UPRGT].v); + ptr++; + if (split && glseg.fracright == 1) SplitRightEdge(ptr); + ptr->Set(glseg.x2, zbottom[1], glseg.y2, tcs[LORGT].u, tcs[LORGT].v); + ptr++; + if (split && !(flags & GLWF_NOSPLITLOWER)) SplitLowerEdge(ptr); + vertcount = GLRenderer->mVBO->GetCount(ptr, &vertindex); + } +} + + +//========================================================================== +// +// General purpose wall rendering function +// everything goes through here +// +//========================================================================== + +void GLWall::RenderWall(int textured) +{ + gl_RenderState.Apply(); + gl_RenderState.ApplyLightIndex(dynlightindex); + if (gl.buffermethod != BM_DEFERRED) + { + MakeVertices(!(textured&RWF_NOSPLIT)); + } + else if (vertcount == 0) + { + // This should never happen but in case it actually does, use the quad drawer as fallback (without edge splitting.) + // This way it at least gets drawn. + FQuadDrawer qd; + qd.Set(0, glseg.x1, zbottom[0], glseg.y1, tcs[LOLFT].u, tcs[LOLFT].v); + qd.Set(1, glseg.x1, ztop[0], glseg.y1, tcs[UPLFT].u, tcs[UPLFT].v); + qd.Set(2, glseg.x2, ztop[1], glseg.y2, tcs[UPRGT].u, tcs[UPRGT].v); + qd.Set(3, glseg.x2, zbottom[1], glseg.y2, tcs[LORGT].u, tcs[LORGT].v); + qd.Render(GL_TRIANGLE_FAN); + vertexcount += 4; + return; + } + GLRenderer->mVBO->RenderArray(GL_TRIANGLE_FAN, vertindex, vertcount); + vertexcount += vertcount; +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLWall::RenderFogBoundary() +{ + if (gl_fogmode && gl_fixedcolormap == 0) + { + if (!gl.legacyMode) + { + int rel = rellight + getExtraLight(); + gl_SetFog(lightlevel, rel, &Colormap, false); + gl_RenderState.EnableDrawBuffers(1); + gl_RenderState.SetEffect(EFF_FOGBOUNDARY); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + RenderWall(RWF_BLANK); + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + gl_RenderState.SetEffect(EFF_NONE); + gl_RenderState.EnableDrawBuffers(gl_RenderState.GetPassDrawBufferCount()); + } + else + { + RenderFogBoundaryCompat(); + } + } +} + + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::RenderMirrorSurface() +{ + if (GLRenderer->mirrortexture == NULL) return; + + // For the sphere map effect we need a normal of the mirror surface, + FVector3 v = glseg.Normal(); + + if (!gl.legacyMode) + { + // we use texture coordinates and texture matrix to pass the normal stuff to the shader so that the default vertex buffer format can be used as is. + tcs[LOLFT].u = tcs[LORGT].u = tcs[UPLFT].u = tcs[UPRGT].u = v.X; + tcs[LOLFT].v = tcs[LORGT].v = tcs[UPLFT].v = tcs[UPRGT].v = v.Z; + + gl_RenderState.EnableTextureMatrix(true); + gl_RenderState.mTextureMatrix.computeNormalMatrix(gl_RenderState.mViewMatrix); + } + else + { + glNormal3fv(&v[0]); + } + + // Use sphere mapping for this + gl_RenderState.SetEffect(EFF_SPHEREMAP); + + gl_SetColor(lightlevel, 0, Colormap ,0.1f); + gl_SetFog(lightlevel, 0, &Colormap, true); + gl_RenderState.BlendFunc(GL_SRC_ALPHA,GL_ONE); + gl_RenderState.AlphaFunc(GL_GREATER,0); + glDepthFunc(GL_LEQUAL); + + FMaterial * pat=FMaterial::ValidateTexture(GLRenderer->mirrortexture, false); + gl_RenderState.SetMaterial(pat, CLAMP_NONE, 0, -1, false); + + flags &= ~GLWF_GLOW; + RenderWall(RWF_BLANK); + + gl_RenderState.EnableTextureMatrix(false); + gl_RenderState.SetEffect(EFF_NONE); + + // Restore the defaults for the translucent pass + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + glDepthFunc(GL_LESS); + + // This is drawn in the translucent pass which is done after the decal pass + // As a result the decals have to be drawn here. + if (seg->sidedef->AttachedDecals) + { + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-1.0f, -128.0f); + glDepthMask(false); + DoDrawDecals(); + glDepthMask(true); + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + gl_RenderState.SetTextureMode(TM_MODULATE); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLWall::RenderTextured(int rflags) +{ + int tmode = gl_RenderState.GetTextureMode(); + int rel = rellight + getExtraLight(); + + if (flags & GLWF_GLOW) + { + gl_RenderState.EnableGlow(true); + gl_RenderState.SetGlowPlanes(topplane, bottomplane); + gl_RenderState.SetGlowParams(topglowcolor, bottomglowcolor); + } + gl_RenderState.SetMaterial(gltexture, flags & 3, 0, -1, false); + + if (type == RENDERWALL_M2SNF) + { + if (flags & GLT_CLAMPY) + { + if (tmode == TM_MODULATE) gl_RenderState.SetTextureMode(TM_CLAMPY); + } + gl_SetFog(255, 0, NULL, false); + } + + float absalpha = fabsf(alpha); + if (lightlist == NULL) + { + gl_SetColor(lightlevel, rel, Colormap, absalpha); + if (type != RENDERWALL_M2SNF) gl_SetFog(lightlevel, rel, &Colormap, RenderStyle == STYLE_Add); + RenderWall(rflags); + } + else + { + gl_RenderState.EnableSplit(true); + + for (unsigned i = 0; i < lightlist->Size(); i++) + { + secplane_t &lowplane = i == (*lightlist).Size() - 1 ? bottomplane : (*lightlist)[i + 1].plane; + // this must use the exact same calculation method as GLWall::Process etc. + float low1 = lowplane.ZatPoint(vertexes[0]); + float low2 = lowplane.ZatPoint(vertexes[1]); + + if (low1 < ztop[0] || low2 < ztop[1]) + { + int thisll = (*lightlist)[i].caster != NULL ? gl_ClampLight(*(*lightlist)[i].p_lightlevel) : lightlevel; + FColormap thiscm; + thiscm.FadeColor = Colormap.FadeColor; + thiscm.CopyFrom3DLight(&(*lightlist)[i]); + gl_SetColor(thisll, rel, thiscm, absalpha); + if (type != RENDERWALL_M2SNF) gl_SetFog(thisll, rel, &thiscm, RenderStyle == STYLE_Add); + gl_RenderState.SetSplitPlanes((*lightlist)[i].plane, lowplane); + RenderWall(rflags); + } + if (low1 <= zbottom[0] && low2 <= zbottom[1]) break; + } + + gl_RenderState.EnableSplit(false); + } + gl_RenderState.SetTextureMode(tmode); + gl_RenderState.EnableGlow(false); +} + +//========================================================================== +// +// +// +//========================================================================== + +void GLWall::RenderTranslucentWall() +{ + if (gltexture) + { + if (gl_fixedcolormap == CM_DEFAULT && gl_lights && gl.lightmethod == LM_DIRECT) + { + SetupLights(); + } + if (!gltexture->GetTransparent()) gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_threshold); + else gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + if (RenderStyle == STYLE_Add) gl_RenderState.BlendFunc(GL_SRC_ALPHA,GL_ONE); + RenderTextured(RWF_TEXTURED | RWF_NOSPLIT); + if (RenderStyle == STYLE_Add) gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + else + { + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_SetColor(lightlevel, 0, Colormap, fabsf(alpha)); + gl_SetFog(lightlevel, 0, &Colormap, RenderStyle == STYLE_Add); + gl_RenderState.EnableTexture(false); + RenderWall(RWF_NOSPLIT); + gl_RenderState.EnableTexture(true); + } +} + +//========================================================================== +// +// +// +//========================================================================== +void GLWall::Draw(int pass) +{ + gl_RenderState.SetNormal(glseg.Normal()); + switch (pass) + { + case GLPASS_LIGHTSONLY: + SetupLights(); + break; + + case GLPASS_ALL: + SetupLights(); + // fall through + case GLPASS_PLAIN: + RenderTextured(RWF_TEXTURED); + break; + + case GLPASS_TRANSLUCENT: + + switch (type) + { + case RENDERWALL_MIRRORSURFACE: + RenderMirrorSurface(); + break; + + case RENDERWALL_FOGBOUNDARY: + RenderFogBoundary(); + break; + + default: + RenderTranslucentWall(); + break; + } + break; + + case GLPASS_LIGHTTEX: + case GLPASS_LIGHTTEX_ADDITIVE: + case GLPASS_LIGHTTEX_FOGGY: + RenderLightsCompat(pass); + break; + + case GLPASS_TEXONLY: + gl_RenderState.SetMaterial(gltexture, flags & 3, 0, -1, false); + RenderWall(RWF_TEXTURED); + break; + } +} diff --git a/src/gl/scene/gl_weapon.cpp b/src/gl/scene/gl_weapon.cpp new file mode 100644 index 000000000..7662c7876 --- /dev/null +++ b/src/gl/scene/gl_weapon.cpp @@ -0,0 +1,475 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2000-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_weapon.cpp +** Weapon sprite drawing +** +*/ + +#include "gl/system/gl_system.h" +#include "sbar.h" +#include "r_utility.h" +#include "v_video.h" +#include "doomstat.h" +#include "d_player.h" +#include "g_level.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/dynlights/gl_glow.h" +#include "gl/scene/gl_drawinfo.h" +#include "gl/models/gl_models.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_material.h" +#include "gl/renderer/gl_quaddrawer.h" +#include "gl/stereo3d/gl_stereo3d.h" + +EXTERN_CVAR (Bool, r_drawplayersprites) +EXTERN_CVAR(Float, transsouls) +EXTERN_CVAR (Bool, st_scale) +EXTERN_CVAR(Int, gl_fuzztype) +EXTERN_CVAR (Bool, r_deathcamera) + + +//========================================================================== +// +// R_DrawPSprite +// +//========================================================================== + +void FGLRenderer::DrawPSprite (player_t * player,DPSprite *psp, float sx, float sy, bool hudModelStep, int OverrideShader, bool alphatexture) +{ + float fU1,fV1; + float fU2,fV2; + float tx; + float x1,y1,x2,y2; + float scale; + float scalex; + float ftexturemid; + + // [BB] In the HUD model step we just render the model and break out. + if ( hudModelStep ) + { + gl_RenderHUDModel(psp, sx, sy); + return; + } + + // decide which patch to use + bool mirror; + FTextureID lump = gl_GetSpriteFrame(psp->GetSprite(), psp->GetFrame(), 0, 0, &mirror); + if (!lump.isValid()) return; + + FMaterial * tex = FMaterial::ValidateTexture(lump, true, false); + if (!tex) return; + + gl_RenderState.SetMaterial(tex, CLAMP_XY_NOMIP, 0, OverrideShader, alphatexture); + + float vw = (float)viewwidth; + float vh = (float)viewheight; + + FloatRect r; + tex->GetSpriteRect(&r); + + // calculate edges of the shape + scalex = (320.0f / (240.0f * WidescreenRatio)) * vw / 320; + + tx = sx - (160 - r.left); + x1 = tx * scalex + vw/2; + if (x1 > vw) return; // off the right side + x1 += viewwindowx; + + tx += r.width; + x2 = tx * scalex + vw / 2; + if (x2 < 0) return; // off the left side + x2 += viewwindowx; + + + // killough 12/98: fix psprite positioning problem + ftexturemid = 100.f - sy - r.top; + + AWeapon * wi=player->ReadyWeapon; + if (wi && wi->YAdjust != 0) + { + float fYAd = wi->YAdjust; + if (screenblocks >= 11) + { + ftexturemid -= fYAd; + } + else if (!st_scale) + { + ftexturemid -= StatusBar->GetDisplacement () * fYAd; + } + } + + scale = (SCREENHEIGHT*vw) / (SCREENWIDTH * 200.0f); + y1 = viewwindowy + vh / 2 - (ftexturemid * scale); + y2 = y1 + (r.height * scale) + 1; + + if (!(mirror) != !(psp->Flags & PSPF_FLIP)) + { + fU2 = tex->GetSpriteUL(); + fV1 = tex->GetSpriteVT(); + fU1 = tex->GetSpriteUR(); + fV2 = tex->GetSpriteVB(); + } + else + { + fU1 = tex->GetSpriteUL(); + fV1 = tex->GetSpriteVT(); + fU2 = tex->GetSpriteUR(); + fV2 = tex->GetSpriteVB(); + + } + + if (tex->GetTransparent() || OverrideShader != -1) + { + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + } + gl_RenderState.Apply(); + FQuadDrawer qd; + qd.Set(0, x1, y1, 0, fU1, fV1); + qd.Set(1, x1, y2, 0, fU1, fV2); + qd.Set(2, x2, y1, 0, fU2, fV1); + qd.Set(3, x2, y2, 0, fU2, fV2); + qd.Render(GL_TRIANGLE_STRIP); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.5f); +} + +//========================================================================== +// +// +// +//========================================================================== + +static bool isBright(DPSprite *psp) +{ + if (psp != nullptr && psp->GetState() != nullptr) + { + bool disablefullbright = false; + FTextureID lump = gl_GetSpriteFrame(psp->GetSprite(), psp->GetFrame(), 0, 0, NULL); + if (lump.isValid()) + { + FMaterial * tex = FMaterial::ValidateTexture(lump, false, false); + if (tex) + disablefullbright = tex->tex->gl_info.bDisableFullbright; + } + return psp->GetState()->GetFullbright() && !disablefullbright; + } + return false; +} + +//========================================================================== +// +// R_DrawPlayerSprites +// +//========================================================================== + +void FGLRenderer::DrawPlayerSprites(sector_t * viewsector, bool hudModelStep) +{ + bool brightflash = false; + unsigned int i; + int lightlevel=0; + FColormap cm; + sector_t * fakesec, fs; + AActor * playermo=players[consoleplayer].camera; + player_t * player=playermo->player; + + s3d::Stereo3DMode::getCurrentMode().AdjustPlayerSprites(); + + // this is the same as the software renderer + if (!player || + !r_drawplayersprites || + !camera->player || + (player->cheats & CF_CHASECAM) || + (r_deathcamera && camera->health <= 0)) + return; + + float bobx, boby, wx, wy; + DPSprite *weapon; + + P_BobWeapon(camera->player, &bobx, &boby, r_TicFracF); + + // Interpolate the main weapon layer once so as to be able to add it to other layers. + if ((weapon = camera->player->FindPSprite(PSP_WEAPON)) != nullptr) + { + if (weapon->firstTic) + { + wx = weapon->x; + wy = weapon->y; + } + else + { + wx = weapon->oldx + (weapon->x - weapon->oldx) * r_TicFracF; + wy = weapon->oldy + (weapon->y - weapon->oldy) * r_TicFracF; + } + } + else + { + wx = 0; + wy = 0; + } + + if (gl_fixedcolormap) + { + lightlevel=255; + cm.Clear(); + fakesec = viewsector; + } + else + { + fakesec = gl_FakeFlat(viewsector, &fs, false); + + // calculate light level for weapon sprites + lightlevel = gl_ClampLight(fakesec->lightlevel); + + // calculate colormap for weapon sprites + if (viewsector->e->XFloor.ffloors.Size() && !glset.nocoloredspritelighting) + { + TArray & lightlist = viewsector->e->XFloor.lightlist; + for(i=0;ifloorplane.ZatPoint(ViewPos); + } + + if (lightbottomviewz) + { + cm = lightlist[i].extra_colormap; + lightlevel = gl_ClampLight(*lightlist[i].p_lightlevel); + break; + } + } + } + else + { + cm=fakesec->ColorMap; + if (glset.nocoloredspritelighting) cm.ClearColor(); + } + + lightlevel = gl_CalcLightLevel(lightlevel, getExtraLight(), true); + + if (glset.lightmode == 8) + { + // Korshun: the way based on max possible light level for sector like in software renderer. + float min_L = 36.0 / 31.0 - ((lightlevel / 255.0) * (63.0 / 31.0)); // Lightlevel in range 0-63 + if (min_L < 0) + min_L = 0; + else if (min_L > 1.0) + min_L = 1.0; + + lightlevel = (1.0 - min_L) * 255; + } + else + { + lightlevel = (2 * lightlevel + 255) / 3; + } + lightlevel = gl_CheckSpriteGlow(viewsector, lightlevel, playermo->Pos()); + + } + + // Korshun: fullbright fog in opengl, render weapon sprites fullbright (but don't cancel out the light color!) + if (glset.brightfog && ((level.flags&LEVEL_HASFADETABLE) || cm.FadeColor != 0)) + { + lightlevel = 255; + } + + PalEntry ThingColor = (playermo->RenderStyle.Flags & STYLEF_ColorIsFixed) ? playermo->fillcolor : 0xffffff; + ThingColor.a = 255; + + visstyle_t vis; + + vis.RenderStyle=playermo->RenderStyle; + vis.Alpha=playermo->Alpha; + vis.colormap = NULL; + if (playermo->Inventory) + { + playermo->Inventory->AlterWeaponSprite(&vis); + if (vis.colormap >= SpecialColormaps[0].Colormap && + vis.colormap < SpecialColormaps[SpecialColormaps.Size()].Colormap && + gl_fixedcolormap == CM_DEFAULT) + { + // this only happens for Strife's inverted weapon sprite + vis.RenderStyle.Flags |= STYLEF_InvertSource; + } + } + if (vis.RenderStyle.AsDWORD == 0) + { + // This is RenderStyle None. + return; + } + + // Set the render parameters + + int OverrideShader = -1; + float trans = 0.f; + if (vis.RenderStyle.BlendOp >= STYLEOP_Fuzz && vis.RenderStyle.BlendOp <= STYLEOP_FuzzOrRevSub) + { + vis.RenderStyle.CheckFuzz(); + if (vis.RenderStyle.BlendOp == STYLEOP_Fuzz) + { + if (gl_fuzztype != 0) + { + // Todo: implement shader selection here + vis.RenderStyle = LegacyRenderStyles[STYLE_Translucent]; + OverrideShader = gl_fuzztype + 4; + trans = 0.99f; // trans may not be 1 here + } + else + { + vis.RenderStyle.BlendOp = STYLEOP_Shadow; + } + } + } + + gl_SetRenderStyle(vis.RenderStyle, false, false); + + if (vis.RenderStyle.Flags & STYLEF_TransSoulsAlpha) + { + trans = transsouls; + } + else if (vis.RenderStyle.Flags & STYLEF_Alpha1) + { + trans = 1.f; + } + else if (trans == 0.f) + { + trans = vis.Alpha; + } + + // now draw the different layers of the weapon + gl_RenderState.EnableBrightmap(true); + gl_RenderState.SetObjectColor(ThingColor); + gl_RenderState.AlphaFunc(GL_GEQUAL, gl_mask_sprite_threshold); + + // hack alert! Rather than changing everything in the underlying lighting code let's just temporarily change + // light mode here to draw the weapon sprite. + int oldlightmode = glset.lightmode; + if (glset.lightmode == 8) glset.lightmode = 2; + + for(DPSprite *psp = player->psprites; psp != nullptr && psp->GetID() < PSP_TARGETCENTER; psp = psp->GetNext()) + { + if (psp->GetState() != nullptr) + { + FColormap cmc = cm; + int ll = lightlevel; + if (isBright(psp)) + { + if (fakesec == viewsector || in_area != area_below) + { + cmc.LightColor.r= + cmc.LightColor.g= + cmc.LightColor.b=0xff; + } + else + { + // under water areas keep most of their color for fullbright objects + cmc.LightColor.r = (3 * cmc.LightColor.r + 0xff) / 4; + cmc.LightColor.g = (3*cmc.LightColor.g + 0xff)/4; + cmc.LightColor.b = (3*cmc.LightColor.b + 0xff)/4; + } + ll = 255; + } + // set the lighting parameters + if (vis.RenderStyle.BlendOp == STYLEOP_Shadow) + { + gl_RenderState.SetColor(0.2f, 0.2f, 0.2f, 0.33f, cmc.desaturation); + } + else + { + if (gl_lights && GLRenderer->mLightCount && !gl_fixedcolormap && gl_light_sprites) + { + gl_SetDynSpriteLight(playermo, NULL); + } + gl_SetColor(ll, 0, cmc, trans, true); + } + + if (psp->firstTic) + { // Can't interpolate the first tic. + psp->firstTic = false; + psp->oldx = psp->x; + psp->oldy = psp->y; + } + + float sx = psp->oldx + (psp->x - psp->oldx) * r_TicFracF; + float sy = psp->oldy + (psp->y - psp->oldy) * r_TicFracF; + + if (psp->Flags & PSPF_ADDBOB) + { + sx += bobx; + sy += boby; + } + + if (psp->Flags & PSPF_ADDWEAPON && psp->GetID() != PSP_WEAPON) + { + sx += wx; + sy += wy; + } + + + DrawPSprite(player, psp, sx, sy, hudModelStep, OverrideShader, !!(vis.RenderStyle.Flags & STYLEF_RedIsAlpha)); + } + } + gl_RenderState.SetObjectColor(0xffffffff); + gl_RenderState.SetDynLight(0, 0, 0); + gl_RenderState.EnableBrightmap(false); + glset.lightmode = oldlightmode; +} + +//========================================================================== +// +// R_DrawPlayerSprites +// +//========================================================================== + +void FGLRenderer::DrawTargeterSprites() +{ + AActor * playermo=players[consoleplayer].camera; + player_t * player=playermo->player; + + if(!player || playermo->renderflags&RF_INVISIBLE || !r_drawplayersprites || + mViewActor!=playermo) return; + + gl_RenderState.EnableBrightmap(false); + gl_RenderState.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + gl_RenderState.AlphaFunc(GL_GEQUAL,gl_mask_sprite_threshold); + gl_RenderState.BlendEquation(GL_FUNC_ADD); + gl_RenderState.ResetColor(); + gl_RenderState.SetTextureMode(TM_MODULATE); + + // The Targeter's sprites are always drawn normally. + for (DPSprite *psp = player->FindPSprite(PSP_TARGETCENTER); psp != nullptr; psp = psp->GetNext()) + { + if (psp->GetState() != nullptr) DrawPSprite(player, psp, psp->x, psp->y, false, 0, false); + } +} \ No newline at end of file diff --git a/src/gl/shaders/gl_ambientshader.cpp b/src/gl/shaders/gl_ambientshader.cpp new file mode 100644 index 000000000..effde2496 --- /dev/null +++ b/src/gl/shaders/gl_ambientshader.cpp @@ -0,0 +1,160 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_ambientshader.h" + +void FLinearDepthShader::Bind() +{ + bool multisample = (gl_multisample > 1); + if (mMultisample != multisample) + mShader.reset(); + + if (!mShader) + { + mShader = std::make_unique(); + mShader->Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader->Compile(FShaderProgram::Fragment, "shaders/glsl/lineardepth.fp", multisample ? "#define MULTISAMPLE\n" : "", 330); + mShader->SetFragDataLocation(0, "FragColor"); + mShader->Link("shaders/glsl/lineardepth"); + mShader->SetAttribLocation(0, "PositionInProjection"); + DepthTexture.Init(*mShader, "DepthTexture"); + ColorTexture.Init(*mShader, "ColorTexture"); + SampleIndex.Init(*mShader, "SampleIndex"); + LinearizeDepthA.Init(*mShader, "LinearizeDepthA"); + LinearizeDepthB.Init(*mShader, "LinearizeDepthB"); + InverseDepthRangeA.Init(*mShader, "InverseDepthRangeA"); + InverseDepthRangeB.Init(*mShader, "InverseDepthRangeB"); + Scale.Init(*mShader, "Scale"); + Offset.Init(*mShader, "Offset"); + mMultisample = multisample; + } + mShader->Bind(); +} + +void FSSAOShader::Bind() +{ + bool multisample = (gl_multisample > 1); + if (mCurrentQuality != gl_ssao || mMultisample != multisample) + mShader.reset(); + + if (!mShader) + { + mShader = std::make_unique(); + mShader->Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader->Compile(FShaderProgram::Fragment, "shaders/glsl/ssao.fp", GetDefines(gl_ssao, multisample), 330); + mShader->SetFragDataLocation(0, "FragColor"); + mShader->Link("shaders/glsl/ssao"); + mShader->SetAttribLocation(0, "PositionInProjection"); + DepthTexture.Init(*mShader, "DepthTexture"); + NormalTexture.Init(*mShader, "NormalTexture"); + RandomTexture.Init(*mShader, "RandomTexture"); + UVToViewA.Init(*mShader, "UVToViewA"); + UVToViewB.Init(*mShader, "UVToViewB"); + InvFullResolution.Init(*mShader, "InvFullResolution"); + NDotVBias.Init(*mShader, "NDotVBias"); + NegInvR2.Init(*mShader, "NegInvR2"); + RadiusToScreen.Init(*mShader, "RadiusToScreen"); + AOMultiplier.Init(*mShader, "AOMultiplier"); + AOStrength.Init(*mShader, "AOStrength"); + Scale.Init(*mShader, "Scale"); + Offset.Init(*mShader, "Offset"); + SampleIndex.Init(*mShader, "SampleIndex"); + mMultisample = multisample; + } + mShader->Bind(); +} + +FString FSSAOShader::GetDefines(int mode, bool multisample) +{ + // Must match quality values in FGLRenderBuffers::CreateAmbientOcclusion + int numDirections, numSteps; + switch (gl_ssao) + { + default: + case LowQuality: numDirections = 2; numSteps = 4; break; + case MediumQuality: numDirections = 4; numSteps = 4; break; + case HighQuality: numDirections = 8; numSteps = 4; break; + } + + FString defines; + defines.Format(R"( + #define USE_RANDOM_TEXTURE + #define RANDOM_TEXTURE_WIDTH 4.0 + #define NUM_DIRECTIONS %d.0 + #define NUM_STEPS %d.0 + )", numDirections, numSteps); + + if (multisample) + defines += "\n#define MULTISAMPLE\n"; + return defines; +} + +void FDepthBlurShader::Bind(bool vertical) +{ + auto &shader = mShader[vertical]; + if (!shader) + { + shader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + shader.Compile(FShaderProgram::Fragment, "shaders/glsl/depthblur.fp", vertical ? "#define BLUR_VERTICAL\n" : "#define BLUR_HORIZONTAL\n", 330); + shader.SetFragDataLocation(0, "FragColor"); + shader.Link("shaders/glsl/depthblur"); + shader.SetAttribLocation(0, "PositionInProjection"); + AODepthTexture[vertical].Init(shader, "AODepthTexture"); + BlurSharpness[vertical].Init(shader, "BlurSharpness"); + InvFullResolution[vertical].Init(shader, "InvFullResolution"); + PowExponent[vertical].Init(shader, "PowExponent"); + } + shader.Bind(); +} + +void FSSAOCombineShader::Bind() +{ + bool multisample = (gl_multisample > 1); + if (mMultisample != multisample) + mShader.reset(); + + if (!mShader) + { + mShader = std::make_unique(); + mShader->Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader->Compile(FShaderProgram::Fragment, "shaders/glsl/ssaocombine.fp", multisample ? "#define MULTISAMPLE\n" : "", 330); + mShader->SetFragDataLocation(0, "FragColor"); + mShader->Link("shaders/glsl/ssaocombine"); + mShader->SetAttribLocation(0, "PositionInProjection"); + AODepthTexture.Init(*mShader, "AODepthTexture"); + SceneFogTexture.Init(*mShader, "SceneFogTexture"); + SampleCount.Init(*mShader, "SampleCount"); + Scale.Init(*mShader, "Scale"); + Offset.Init(*mShader, "Offset"); + mMultisample = multisample; + } + mShader->Bind(); +} diff --git a/src/gl/shaders/gl_ambientshader.h b/src/gl/shaders/gl_ambientshader.h new file mode 100644 index 000000000..d3310c3d6 --- /dev/null +++ b/src/gl/shaders/gl_ambientshader.h @@ -0,0 +1,93 @@ +#ifndef __GL_AMBIENTSHADER_H +#define __GL_AMBIENTSHADER_H + +#include "gl_shaderprogram.h" + +class FLinearDepthShader +{ +public: + void Bind(); + + FBufferedUniformSampler DepthTexture; + FBufferedUniformSampler ColorTexture; + FBufferedUniform1i SampleIndex; + FBufferedUniform1f LinearizeDepthA; + FBufferedUniform1f LinearizeDepthB; + FBufferedUniform1f InverseDepthRangeA; + FBufferedUniform1f InverseDepthRangeB; + FBufferedUniform2f Scale; + FBufferedUniform2f Offset; + +private: + std::unique_ptr mShader; + bool mMultisample = false; +}; + +class FSSAOShader +{ +public: + void Bind(); + + FBufferedUniformSampler DepthTexture; + FBufferedUniformSampler NormalTexture; + FBufferedUniformSampler RandomTexture; + FBufferedUniform2f UVToViewA; + FBufferedUniform2f UVToViewB; + FBufferedUniform2f InvFullResolution; + FBufferedUniform1f NDotVBias; + FBufferedUniform1f NegInvR2; + FBufferedUniform1f RadiusToScreen; + FBufferedUniform1f AOMultiplier; + FBufferedUniform1f AOStrength; + FBufferedUniform2f Scale; + FBufferedUniform2f Offset; + FBufferedUniform1i SampleIndex; + +private: + enum Quality + { + Off, + LowQuality, + MediumQuality, + HighQuality, + NumQualityModes + }; + + FString GetDefines(int mode, bool multisample); + + std::unique_ptr mShader; + Quality mCurrentQuality = Off; + bool mMultisample = false; +}; + +class FDepthBlurShader +{ +public: + void Bind(bool vertical); + + FBufferedUniformSampler AODepthTexture[2]; + FBufferedUniform1f BlurSharpness[2]; + FBufferedUniform2f InvFullResolution[2]; + FBufferedUniform1f PowExponent[2]; + +private: + FShaderProgram mShader[2]; +}; + +class FSSAOCombineShader +{ +public: + void Bind(); + + FBufferedUniformSampler AODepthTexture; + FBufferedUniformSampler SceneFogTexture; + FBufferedUniform1i SampleCount; + FBufferedUniform2f Scale; + FBufferedUniform2f Offset; + +private: + std::unique_ptr mShader; + bool mMultisample = false; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_bloomshader.cpp b/src/gl/shaders/gl_bloomshader.cpp new file mode 100644 index 000000000..44253ae79 --- /dev/null +++ b/src/gl/shaders/gl_bloomshader.cpp @@ -0,0 +1,68 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_bloomshader.cpp +** Shaders used to do bloom +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_bloomshader.h" + +void FBloomExtractShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/bloomextract.fp", "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/bloomextract"); + mShader.SetAttribLocation(0, "PositionInProjection"); + SceneTexture.Init(mShader, "SceneTexture"); + ExposureTexture.Init(mShader, "ExposureTexture"); + Scale.Init(mShader, "Scale"); + Offset.Init(mShader, "Offset"); + } + mShader.Bind(); +} + +void FBloomCombineShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/bloomcombine.fp", "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/bloomcombine"); + mShader.SetAttribLocation(0, "PositionInProjection"); + BloomTexture.Init(mShader, "Bloom"); + } + mShader.Bind(); +} diff --git a/src/gl/shaders/gl_bloomshader.h b/src/gl/shaders/gl_bloomshader.h new file mode 100644 index 000000000..8b34bb479 --- /dev/null +++ b/src/gl/shaders/gl_bloomshader.h @@ -0,0 +1,31 @@ +#ifndef __GL_BLOOMSHADER_H +#define __GL_BLOOMSHADER_H + +#include "gl_shaderprogram.h" + +class FBloomExtractShader +{ +public: + void Bind(); + + FBufferedUniformSampler SceneTexture; + FBufferedUniformSampler ExposureTexture; + FBufferedUniform2f Scale; + FBufferedUniform2f Offset; + +private: + FShaderProgram mShader; +}; + +class FBloomCombineShader +{ +public: + void Bind(); + + FBufferedUniformSampler BloomTexture; + +private: + FShaderProgram mShader; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_blurshader.cpp b/src/gl/shaders/gl_blurshader.cpp new file mode 100644 index 000000000..cd4532cc4 --- /dev/null +++ b/src/gl/shaders/gl_blurshader.cpp @@ -0,0 +1,248 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_blurshader.cpp +** Gaussian blur shader +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_blurshader.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_renderer.h" + +//========================================================================== +// +// Performs a vertical gaussian blur pass +// +//========================================================================== + +void FBlurShader::BlurVertical(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height) +{ + Blur(renderer, blurAmount, sampleCount, inputTexture, outputFrameBuffer, width, height, true); +} + +//========================================================================== +// +// Performs a horizontal gaussian blur pass +// +//========================================================================== + +void FBlurShader::BlurHorizontal(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height) +{ + Blur(renderer, blurAmount, sampleCount, inputTexture, outputFrameBuffer, width, height, false); +} + +//========================================================================== +// +// Helper for BlurVertical and BlurHorizontal. Executes the actual pass +// +//========================================================================== + +void FBlurShader::Blur(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height, bool vertical) +{ + BlurSetup *setup = GetSetup(blurAmount, sampleCount); + if (vertical) + setup->VerticalShader->Bind(); + else + setup->HorizontalShader->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, inputTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindFramebuffer(GL_FRAMEBUFFER, outputFrameBuffer); + glViewport(0, 0, width, height); + glDisable(GL_BLEND); + + renderer->RenderScreenQuad(); +} + +//========================================================================== +// +// Compiles the blur shaders needed for the specified blur amount and +// kernel size +// +//========================================================================== + +FBlurShader::BlurSetup *FBlurShader::GetSetup(float blurAmount, int sampleCount) +{ + for (size_t mBlurSetupIndex = 0; mBlurSetupIndex < mBlurSetups.Size(); mBlurSetupIndex++) + { + if (mBlurSetups[mBlurSetupIndex].blurAmount == blurAmount && mBlurSetups[mBlurSetupIndex].sampleCount == sampleCount) + { + return &mBlurSetups[mBlurSetupIndex]; + } + } + + BlurSetup blurSetup(blurAmount, sampleCount); + + FString vertexCode = VertexShaderCode(); + FString horizontalCode = FragmentShaderCode(blurAmount, sampleCount, false); + FString verticalCode = FragmentShaderCode(blurAmount, sampleCount, true); + + blurSetup.VerticalShader = std::make_shared(); + blurSetup.VerticalShader->Compile(FShaderProgram::Vertex, "vertical blur vertex shader", vertexCode, "", 330); + blurSetup.VerticalShader->Compile(FShaderProgram::Fragment, "vertical blur fragment shader", verticalCode, "", 330); + blurSetup.VerticalShader->SetFragDataLocation(0, "FragColor"); + blurSetup.VerticalShader->SetAttribLocation(0, "PositionInProjection"); + blurSetup.VerticalShader->Link("vertical blur"); + blurSetup.VerticalShader->Bind(); + glUniform1i(glGetUniformLocation(*blurSetup.VerticalShader.get(), "SourceTexture"), 0); + + blurSetup.HorizontalShader = std::make_shared(); + blurSetup.HorizontalShader->Compile(FShaderProgram::Vertex, "horizontal blur vertex shader", vertexCode, "", 330); + blurSetup.HorizontalShader->Compile(FShaderProgram::Fragment, "horizontal blur fragment shader", horizontalCode, "", 330); + blurSetup.HorizontalShader->SetFragDataLocation(0, "FragColor"); + blurSetup.HorizontalShader->SetAttribLocation(0, "PositionInProjection"); + blurSetup.HorizontalShader->Link("horizontal blur"); + blurSetup.HorizontalShader->Bind(); + glUniform1i(glGetUniformLocation(*blurSetup.HorizontalShader.get(), "SourceTexture"), 0); + + mBlurSetups.Push(blurSetup); + + return &mBlurSetups[mBlurSetups.Size() - 1]; +} + +//========================================================================== +// +// The vertex shader GLSL code +// +//========================================================================== + +FString FBlurShader::VertexShaderCode() +{ + return R"( + in vec4 PositionInProjection; + out vec2 TexCoord; + + void main() + { + gl_Position = PositionInProjection; + TexCoord = (gl_Position.xy + 1.0) * 0.5; + } + )"; +} + +//========================================================================== +// +// Generates the fragment shader GLSL code for a specific blur setup +// +//========================================================================== + +FString FBlurShader::FragmentShaderCode(float blurAmount, int sampleCount, bool vertical) +{ + TArray sampleWeights; + TArray sampleOffsets; + ComputeBlurSamples(sampleCount, blurAmount, sampleWeights, sampleOffsets); + + const char *fragmentShader = + R"( + in vec2 TexCoord; + uniform sampler2D SourceTexture; + out vec4 FragColor; + #if __VERSION__ < 130 + uniform float ScaleX; + uniform float ScaleY; + vec4 textureOffset(sampler2D s, vec2 texCoord, ivec2 offset) + { + return texture2D(s, texCoord + vec2(ScaleX * float(offset.x), ScaleY * float(offset.y))); + } + #endif + void main() + { + FragColor = %s; + } + )"; + + FString loopCode; + for (int i = 0; i < sampleCount; i++) + { + if (i > 0) + loopCode += " + "; + + if (vertical) + loopCode.AppendFormat("\r\n\t\t\ttextureOffset(SourceTexture, TexCoord, ivec2(0, %d)) * %f", sampleOffsets[i], (double)sampleWeights[i]); + else + loopCode.AppendFormat("\r\n\t\t\ttextureOffset(SourceTexture, TexCoord, ivec2(%d, 0)) * %f", sampleOffsets[i], (double)sampleWeights[i]); + } + + FString code; + code.Format(fragmentShader, loopCode.GetChars()); + return code; +} + +//========================================================================== +// +// Calculates the sample weight for a specific offset in the kernel +// +//========================================================================== + +float FBlurShader::ComputeGaussian(float n, float theta) // theta = Blur Amount +{ + return (float)((1.0f / sqrtf(2 * (float)M_PI * theta)) * expf(-(n * n) / (2.0f * theta * theta))); +} + +//========================================================================== +// +// Calculates the sample weights and offsets +// +//========================================================================== + +void FBlurShader::ComputeBlurSamples(int sampleCount, float blurAmount, TArray &sampleWeights, TArray &sampleOffsets) +{ + sampleWeights.Resize(sampleCount); + sampleOffsets.Resize(sampleCount); + + sampleWeights[0] = ComputeGaussian(0, blurAmount); + sampleOffsets[0] = 0; + + float totalWeights = sampleWeights[0]; + + for (int i = 0; i < sampleCount / 2; i++) + { + float weight = ComputeGaussian(i + 1.0f, blurAmount); + + sampleWeights[i * 2 + 1] = weight; + sampleWeights[i * 2 + 2] = weight; + sampleOffsets[i * 2 + 1] = i + 1; + sampleOffsets[i * 2 + 2] = -i - 1; + + totalWeights += weight * 2; + } + + for (int i = 0; i < sampleCount; i++) + { + sampleWeights[i] /= totalWeights; + } +} diff --git a/src/gl/shaders/gl_blurshader.h b/src/gl/shaders/gl_blurshader.h new file mode 100644 index 000000000..92ef5f115 --- /dev/null +++ b/src/gl/shaders/gl_blurshader.h @@ -0,0 +1,41 @@ +#ifndef __GL_BLURSHADER_H +#define __GL_BLURSHADER_H + +#include "gl_shaderprogram.h" +#include + +class FGLRenderer; + +class FBlurShader +{ +public: + void BlurVertical(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height); + void BlurHorizontal(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height); + +private: + void Blur(FGLRenderer *renderer, float blurAmount, int sampleCount, GLuint inputTexture, GLuint outputFrameBuffer, int width, int height, bool vertical); + + struct BlurSetup + { + BlurSetup(float blurAmount, int sampleCount) : blurAmount(blurAmount), sampleCount(sampleCount) { } + + float blurAmount; + int sampleCount; + std::shared_ptr VerticalShader; + std::shared_ptr HorizontalShader; + FBufferedUniform1f VerticalScaleX, VerticalScaleY; + FBufferedUniform1f HorizontalScaleX, HorizontalScaleY; + }; + + BlurSetup *GetSetup(float blurAmount, int sampleCount); + + FString VertexShaderCode(); + FString FragmentShaderCode(float blurAmount, int sampleCount, bool vertical); + + float ComputeGaussian(float n, float theta); + void ComputeBlurSamples(int sampleCount, float blurAmount, TArray &sample_weights, TArray &sample_offsets); + + TArray mBlurSetups; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_colormapshader.cpp b/src/gl/shaders/gl_colormapshader.cpp new file mode 100644 index 000000000..06c72160a --- /dev/null +++ b/src/gl/shaders/gl_colormapshader.cpp @@ -0,0 +1,54 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_colormapshader.cpp +** Applies a fullscreen colormap to the scene +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_colormapshader.h" + +void FColormapShader::Bind() +{ + auto &shader = mShader; + if (!shader) + { + shader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + shader.Compile(FShaderProgram::Fragment, "shaders/glsl/colormap.fp", "", 330); + shader.SetFragDataLocation(0, "FragColor"); + shader.Link("shaders/glsl/colormap"); + shader.SetAttribLocation(0, "PositionInProjection"); + MapStart.Init(shader, "uFixedColormapStart"); + MapRange.Init(shader, "uFixedColormapRange"); + } + shader.Bind(); +} + diff --git a/src/gl/shaders/gl_colormapshader.h b/src/gl/shaders/gl_colormapshader.h new file mode 100644 index 000000000..b20c23a4c --- /dev/null +++ b/src/gl/shaders/gl_colormapshader.h @@ -0,0 +1,20 @@ +#ifndef __GL_COLORMAPSHADER_H +#define __GL_COLORMAPSHADER_H + +#include "gl_shaderprogram.h" + +class FColormapShader +{ +public: + void Bind(); + + FBufferedUniformSampler SceneTexture; + FUniform4f MapStart; + FUniform4f MapRange; + +private: + + FShaderProgram mShader; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_fxaashader.cpp b/src/gl/shaders/gl_fxaashader.cpp new file mode 100644 index 000000000..277c7fbb3 --- /dev/null +++ b/src/gl/shaders/gl_fxaashader.cpp @@ -0,0 +1,99 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Alexey Lysiuk +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +// +// Fast approXimate Anti-Aliasing (FXAA) post-processing +// + +#include "gl/system/gl_system.h" +#include "gl/shaders/gl_fxaashader.h" + +EXTERN_CVAR(Int, gl_fxaa) + +void FFXAALumaShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/fxaa.fp", "#define FXAA_LUMA_PASS\n", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/fxaa"); + mShader.SetAttribLocation(0, "PositionInProjection"); + InputTexture.Init(mShader, "InputTexture"); + } + + mShader.Bind(); +} + +static int GetMaxVersion() +{ + return gl.glslversion >= 4.f ? 400 : 330; +} + +static FString GetDefines() +{ + int quality; + + switch (gl_fxaa) + { + default: + case FFXAAShader::Low: quality = 10; break; + case FFXAAShader::Medium: quality = 12; break; + case FFXAAShader::High: quality = 29; break; + case FFXAAShader::Extreme: quality = 39; break; + } + + const int gatherAlpha = GetMaxVersion() >= 400 ? 1 : 0; + + // TODO: enable FXAA_GATHER4_ALPHA on OpenGL earlier than 4.0 + // when GL_ARB_gpu_shader5/GL_NV_gpu_shader5 extensions are supported + + FString result; + result.Format( + "#define FXAA_QUALITY__PRESET %i\n" + "#define FXAA_GATHER4_ALPHA %i\n", + quality, gatherAlpha); + + return result; +} + +void FFXAAShader::Bind() +{ + assert(gl_fxaa > 0 && gl_fxaa < Count); + FShaderProgram &shader = mShaders[gl_fxaa]; + + if (!shader) + { + const FString defines = GetDefines(); + const int maxVersion = GetMaxVersion(); + + shader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + shader.Compile(FShaderProgram::Fragment, "shaders/glsl/fxaa.fp", defines, maxVersion); + shader.SetFragDataLocation(0, "FragColor"); + shader.Link("shaders/glsl/fxaa"); + shader.SetAttribLocation(0, "PositionInProjection"); + InputTexture.Init(shader, "InputTexture"); + ReciprocalResolution.Init(shader, "ReciprocalResolution"); + } + + shader.Bind(); +} diff --git a/src/gl/shaders/gl_fxaashader.h b/src/gl/shaders/gl_fxaashader.h new file mode 100644 index 000000000..5ebcd232e --- /dev/null +++ b/src/gl/shaders/gl_fxaashader.h @@ -0,0 +1,66 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Alexey Lysiuk +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +// +// Fast approXimate Anti-Aliasing (FXAA) post-processing +// + +#ifndef __GL_FXAASHADER_H__ +#define __GL_FXAASHADER_H__ + +#include "gl_shaderprogram.h" + +class FFXAALumaShader +{ +public: + void Bind(); + + FBufferedUniform1i InputTexture; + +private: + FShaderProgram mShader; +}; + + +class FFXAAShader +{ +public: + enum Quality + { + None, + Low, + Medium, + High, + Extreme, + Count + }; + + void Bind(); + + FBufferedUniform1i InputTexture; + FBufferedUniform2f ReciprocalResolution; + +private: + FShaderProgram mShaders[Count]; +}; + +#endif // __GL_FXAASHADER_H__ diff --git a/src/gl/shaders/gl_lensshader.cpp b/src/gl/shaders/gl_lensshader.cpp new file mode 100644 index 000000000..9d242aa87 --- /dev/null +++ b/src/gl/shaders/gl_lensshader.cpp @@ -0,0 +1,55 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_lensshader.cpp +** Lens distortion with chromatic aberration shader +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_lensshader.h" + +void FLensShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/lensdistortion.fp", "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/lensdistortion"); + mShader.SetAttribLocation(0, "PositionInProjection"); + InputTexture.Init(mShader, "InputTexture"); + AspectRatio.Init(mShader, "Aspect"); + Scale.Init(mShader, "Scale"); + LensDistortionCoefficient.Init(mShader, "k"); + CubicDistortionValue.Init(mShader, "kcube"); + } + mShader.Bind(); +} diff --git a/src/gl/shaders/gl_lensshader.h b/src/gl/shaders/gl_lensshader.h new file mode 100644 index 000000000..7e9ef6392 --- /dev/null +++ b/src/gl/shaders/gl_lensshader.h @@ -0,0 +1,21 @@ +#ifndef __GL_LENSSHADER_H +#define __GL_LENSSHADER_H + +#include "gl_shaderprogram.h" + +class FLensShader +{ +public: + void Bind(); + + FBufferedUniformSampler InputTexture; + FBufferedUniform1f AspectRatio; + FBufferedUniform1f Scale; + FBufferedUniform4f LensDistortionCoefficient; + FBufferedUniform4f CubicDistortionValue; + +private: + FShaderProgram mShader; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_present3dRowshader.cpp b/src/gl/shaders/gl_present3dRowshader.cpp new file mode 100644 index 000000000..d8369a3b6 --- /dev/null +++ b/src/gl/shaders/gl_present3dRowshader.cpp @@ -0,0 +1,74 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_3dRowshader.cpp +** Copy rendered texture to back buffer, possibly with gamma correction +** while interleaving rows from two independent viewpoint textures, +** representing the left-eye and right-eye views. +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_present3dRowshader.h" + +void FPresentStereoShaderBase::Init(const char * vtx_shader_name, const char * program_name) +{ + FPresentShaderBase::Init(vtx_shader_name, program_name); + LeftEyeTexture.Init(mShader, "LeftEyeTexture"); + RightEyeTexture.Init(mShader, "RightEyeTexture"); + WindowPositionParity.Init(mShader, "WindowPositionParity"); +} + +void FPresent3DCheckerShader::Bind() +{ + if (!mShader) + { + Init("shaders/glsl/present_checker3d.fp", "shaders/glsl/presentChecker3d"); + } + mShader.Bind(); +} + +void FPresent3DColumnShader::Bind() +{ + if (!mShader) + { + Init("shaders/glsl/present_column3d.fp", "shaders/glsl/presentColumn3d"); + } + mShader.Bind(); +} + +void FPresent3DRowShader::Bind() +{ + if (!mShader) + { + Init("shaders/glsl/present_row3d.fp", "shaders/glsl/presentRow3d"); + } + mShader.Bind(); +} diff --git a/src/gl/shaders/gl_present3dRowshader.h b/src/gl/shaders/gl_present3dRowshader.h new file mode 100644 index 000000000..10419d7f5 --- /dev/null +++ b/src/gl/shaders/gl_present3dRowshader.h @@ -0,0 +1,64 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_present3dRowshader.h +** Final composition and present shader for row-interleaved stereoscopic 3D mode +** +*/ + +#ifndef GL_PRESENT3DROWSHADER_H_ +#define GL_PRESENT3DROWSHADER_H_ + +#include "gl_shaderprogram.h" +#include "gl_presentshader.h" + +class FPresentStereoShaderBase : public FPresentShaderBase +{ +public: + FBufferedUniformSampler LeftEyeTexture; + FBufferedUniformSampler RightEyeTexture; + FBufferedUniform1i WindowPositionParity; + +protected: + void Init(const char * vtx_shader_name, const char * program_name) override; +}; + +class FPresent3DCheckerShader : public FPresentStereoShaderBase +{ +public: + void Bind() override; +}; + +class FPresent3DColumnShader : public FPresentStereoShaderBase +{ +public: + void Bind() override; +}; + +class FPresent3DRowShader : public FPresentStereoShaderBase +{ +public: + void Bind() override; +}; + +// GL_PRESENT3DROWSHADER_H_ +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_presentshader.cpp b/src/gl/shaders/gl_presentshader.cpp new file mode 100644 index 000000000..15acc74fb --- /dev/null +++ b/src/gl/shaders/gl_presentshader.cpp @@ -0,0 +1,61 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_presentshader.cpp +** Copy rendered texture to back buffer, possibly with gamma correction +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_presentshader.h" + +void FPresentShaderBase::Init(const char * vtx_shader_name, const char * program_name) +{ + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquadscale.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, vtx_shader_name, "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link(program_name); + mShader.SetAttribLocation(0, "PositionInProjection"); + mShader.SetAttribLocation(1, "UV"); + InvGamma.Init(mShader, "InvGamma"); + Contrast.Init(mShader, "Contrast"); + Brightness.Init(mShader, "Brightness"); + Scale.Init(mShader, "UVScale"); +} + +void FPresentShader::Bind() +{ + if (!mShader) + { + Init("shaders/glsl/present.fp", "shaders/glsl/present"); + InputTexture.Init(mShader, "InputTexture"); + } + mShader.Bind(); +} diff --git a/src/gl/shaders/gl_presentshader.h b/src/gl/shaders/gl_presentshader.h new file mode 100644 index 000000000..6f9e1bfd7 --- /dev/null +++ b/src/gl/shaders/gl_presentshader.h @@ -0,0 +1,29 @@ +#ifndef __GL_PRESENTSHADER_H +#define __GL_PRESENTSHADER_H + +#include "gl_shaderprogram.h" + +class FPresentShaderBase +{ +public: + virtual void Bind() = 0; + + FBufferedUniform1f InvGamma; + FBufferedUniform1f Contrast; + FBufferedUniform1f Brightness; + FBufferedUniform2f Scale; + +protected: + virtual void Init(const char * vtx_shader_name, const char * program_name); + FShaderProgram mShader; +}; + +class FPresentShader : public FPresentShaderBase +{ +public: + void Bind() override; + + FBufferedUniformSampler InputTexture; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_shader.cpp b/src/gl/shaders/gl_shader.cpp new file mode 100644 index 000000000..b7d8335f8 --- /dev/null +++ b/src/gl/shaders/gl_shader.cpp @@ -0,0 +1,707 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_shader.cpp +** +** GLSL shader handling +** +*/ + +#include "gl/system/gl_system.h" +#include "c_cvars.h" +#include "v_video.h" +#include "name.h" +#include "w_wad.h" +#include "i_system.h" +#include "doomerrors.h" +#include "v_palette.h" +#include "sc_man.h" +#include "cmdlib.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_debug.h" +#include "gl/data/gl_data.h" +#include "gl/data/gl_matrix.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_shader.h" +#include "gl/shaders/gl_shaderprogram.h" +#include "gl/textures/gl_material.h" +#include "gl/dynlights/gl_lightbuffer.h" + +//========================================================================== +// +// +// +//========================================================================== + +bool FShader::Load(const char * name, const char * vert_prog_lump, const char * frag_prog_lump, const char * proc_prog_lump, const char * defines) +{ + static char buffer[10000]; + FString error; + + int i_lump = Wads.CheckNumForFullName("shaders/glsl/shaderdefs.i"); + if (i_lump == -1) I_Error("Unable to load 'shaders/glsl/shaderdefs.i'"); + FMemLump i_data = Wads.ReadLump(i_lump); + + int vp_lump = Wads.CheckNumForFullName(vert_prog_lump); + if (vp_lump == -1) I_Error("Unable to load '%s'", vert_prog_lump); + FMemLump vp_data = Wads.ReadLump(vp_lump); + + int fp_lump = Wads.CheckNumForFullName(frag_prog_lump); + if (fp_lump == -1) I_Error("Unable to load '%s'", frag_prog_lump); + FMemLump fp_data = Wads.ReadLump(fp_lump); + + + +// +// The following code uses GetChars on the strings to get rid of terminating 0 characters. Do not remove or the code may break! +// + FString vp_comb; + + assert(GLRenderer->mLights != NULL); + // On the shader side there is no difference between LM_DEFERRED and LM_DIRECT, it only decides how the buffer is initialized. + unsigned int lightbuffertype = GLRenderer->mLights->GetBufferType(); + unsigned int lightbuffersize = GLRenderer->mLights->GetBlockSize(); + if (lightbuffertype == GL_UNIFORM_BUFFER) + { + // This differentiation is for some Intel drivers which fail on #extension, so use of #version 140 is necessary + if (gl.glslversion < 1.4f) + { + vp_comb.Format("#version 130\n#extension GL_ARB_uniform_buffer_object : require\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize); + } + else + { + vp_comb.Format("#version 140\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize); + } + } + else + { + vp_comb = "#version 400 core\n#extension GL_ARB_shader_storage_buffer_object : require\n#define SHADER_STORAGE_LIGHTS\n"; + } + + if (gl.buffermethod == BM_DEFERRED) + { + vp_comb << "#define USE_QUAD_DRAWER\n"; + } + + vp_comb << defines << i_data.GetString().GetChars(); + FString fp_comb = vp_comb; + + vp_comb << vp_data.GetString().GetChars() << "\n"; + fp_comb << fp_data.GetString().GetChars() << "\n"; + + if (proc_prog_lump != NULL) + { + if (*proc_prog_lump != '#') + { + int pp_lump = Wads.CheckNumForFullName(proc_prog_lump); + if (pp_lump == -1) I_Error("Unable to load '%s'", proc_prog_lump); + FMemLump pp_data = Wads.ReadLump(pp_lump); + + if (pp_data.GetString().IndexOf("ProcessTexel") < 0) + { + // this looks like an old custom hardware shader. + // We need to replace the ProcessTexel call to make it work. + + fp_comb.Substitute("vec4 frag = ProcessTexel();", "vec4 frag = Process(vec4(1.0));"); + } + fp_comb << pp_data.GetString().GetChars(); + fp_comb.Substitute("gl_TexCoord[0]", "vTexCoord"); // fix old custom shaders. + + if (pp_data.GetString().IndexOf("ProcessLight") < 0) + { + int pl_lump = Wads.CheckNumForFullName("shaders/glsl/func_defaultlight.fp"); + if (pl_lump == -1) I_Error("Unable to load '%s'", "shaders/glsl/func_defaultlight.fp"); + FMemLump pl_data = Wads.ReadLump(pl_lump); + fp_comb << "\n" << pl_data.GetString().GetChars(); + } + } + else + { + // Proc_prog_lump is not a lump name but the source itself (from generated shaders) + fp_comb << proc_prog_lump + 1; + } + } + + if (gl.flags & RFL_NO_CLIP_PLANES) + { + // On ATI's GL3 drivers we have to disable gl_ClipDistance because it's hopelessly broken. + // This will cause some glitches and regressions but is the only way to avoid total display garbage. + vp_comb.Substitute("gl_ClipDistance", "//"); + } + + hVertProg = glCreateShader(GL_VERTEX_SHADER); + hFragProg = glCreateShader(GL_FRAGMENT_SHADER); + + FGLDebug::LabelObject(GL_SHADER, hVertProg, vert_prog_lump); + FGLDebug::LabelObject(GL_SHADER, hFragProg, frag_prog_lump); + + int vp_size = (int)vp_comb.Len(); + int fp_size = (int)fp_comb.Len(); + + const char *vp_ptr = vp_comb.GetChars(); + const char *fp_ptr = fp_comb.GetChars(); + + glShaderSource(hVertProg, 1, &vp_ptr, &vp_size); + glShaderSource(hFragProg, 1, &fp_ptr, &fp_size); + + glCompileShader(hVertProg); + glCompileShader(hFragProg); + + hShader = glCreateProgram(); + FGLDebug::LabelObject(GL_PROGRAM, hShader, name); + + glAttachShader(hShader, hVertProg); + glAttachShader(hShader, hFragProg); + + glBindAttribLocation(hShader, VATTR_VERTEX, "aPosition"); + glBindAttribLocation(hShader, VATTR_TEXCOORD, "aTexCoord"); + glBindAttribLocation(hShader, VATTR_COLOR, "aColor"); + glBindAttribLocation(hShader, VATTR_VERTEX2, "aVertex2"); + glBindAttribLocation(hShader, VATTR_NORMAL, "aNormal"); + + glBindFragDataLocation(hShader, 0, "FragColor"); + glBindFragDataLocation(hShader, 1, "FragFog"); + glBindFragDataLocation(hShader, 2, "FragNormal"); + + glLinkProgram(hShader); + + glGetShaderInfoLog(hVertProg, 10000, NULL, buffer); + if (*buffer) + { + error << "Vertex shader:\n" << buffer << "\n"; + } + glGetShaderInfoLog(hFragProg, 10000, NULL, buffer); + if (*buffer) + { + error << "Fragment shader:\n" << buffer << "\n"; + } + + glGetProgramInfoLog(hShader, 10000, NULL, buffer); + if (*buffer) + { + error << "Linking:\n" << buffer << "\n"; + } + int linked; + glGetProgramiv(hShader, GL_LINK_STATUS, &linked); + if (linked == 0) + { + // only print message if there's an error. + I_Error("Init Shader '%s':\n%s\n", name, error.GetChars()); + } + + + muDesaturation.Init(hShader, "uDesaturationFactor"); + muFogEnabled.Init(hShader, "uFogEnabled"); + muTextureMode.Init(hShader, "uTextureMode"); + muCameraPos.Init(hShader, "uCameraPos"); + muLightParms.Init(hShader, "uLightAttr"); + muClipSplit.Init(hShader, "uClipSplit"); + muColormapStart.Init(hShader, "uFixedColormapStart"); + muColormapRange.Init(hShader, "uFixedColormapRange"); + muLightIndex.Init(hShader, "uLightIndex"); + muFogColor.Init(hShader, "uFogColor"); + muDynLightColor.Init(hShader, "uDynLightColor"); + muObjectColor.Init(hShader, "uObjectColor"); + muGlowBottomColor.Init(hShader, "uGlowBottomColor"); + muGlowTopColor.Init(hShader, "uGlowTopColor"); + muGlowBottomPlane.Init(hShader, "uGlowBottomPlane"); + muGlowTopPlane.Init(hShader, "uGlowTopPlane"); + muSplitBottomPlane.Init(hShader, "uSplitBottomPlane"); + muSplitTopPlane.Init(hShader, "uSplitTopPlane"); + muClipLine.Init(hShader, "uClipLine"); + muFixedColormap.Init(hShader, "uFixedColormap"); + muInterpolationFactor.Init(hShader, "uInterpolationFactor"); + muClipHeight.Init(hShader, "uClipHeight"); + muClipHeightDirection.Init(hShader, "uClipHeightDirection"); + muAlphaThreshold.Init(hShader, "uAlphaThreshold"); + muTimer.Init(hShader, "timer"); + + lights_index = glGetUniformLocation(hShader, "lights"); + fakevb_index = glGetUniformLocation(hShader, "fakeVB"); + projectionmatrix_index = glGetUniformLocation(hShader, "ProjectionMatrix"); + viewmatrix_index = glGetUniformLocation(hShader, "ViewMatrix"); + modelmatrix_index = glGetUniformLocation(hShader, "ModelMatrix"); + texturematrix_index = glGetUniformLocation(hShader, "TextureMatrix"); + vertexmatrix_index = glGetUniformLocation(hShader, "uQuadVertices"); + texcoordmatrix_index = glGetUniformLocation(hShader, "uQuadTexCoords"); + normalviewmatrix_index = glGetUniformLocation(hShader, "NormalViewMatrix"); + normalmodelmatrix_index = glGetUniformLocation(hShader, "NormalModelMatrix"); + quadmode_index = glGetUniformLocation(hShader, "uQuadMode"); + + if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER)) + { + int tempindex = glGetUniformBlockIndex(hShader, "LightBufferUBO"); + if (tempindex != -1) glUniformBlockBinding(hShader, tempindex, LIGHTBUF_BINDINGPOINT); + } + + glUseProgram(hShader); + if (quadmode_index > 0) glUniform1i(quadmode_index, 0); + + // set up other texture units (if needed by the shader) + for (int i = 2; i<16; i++) + { + char stringbuf[20]; + mysnprintf(stringbuf, 20, "texture%d", i); + int tempindex = glGetUniformLocation(hShader, stringbuf); + if (tempindex > 0) glUniform1i(tempindex, i - 1); + } + + glUseProgram(0); + return !!linked; +} + +//========================================================================== +// +// +// +//========================================================================== + +FShader::~FShader() +{ + glDeleteProgram(hShader); + glDeleteShader(hVertProg); + glDeleteShader(hFragProg); +} + + +//========================================================================== +// +// +// +//========================================================================== + +bool FShader::Bind() +{ + GLRenderer->mShaderManager->SetActiveShader(this); + return true; +} + +//========================================================================== +// +// Since all shaders are REQUIRED, any error here needs to be fatal +// +//========================================================================== + +FShader *FShaderCollection::Compile (const char *ShaderName, const char *ShaderPath, bool usediscard, EPassType passType) +{ + FString defines; + // this can't be in the shader code due to ATI strangeness. + if (gl.MaxLights() == 128) defines += "#define MAXLIGHTS128\n"; + if (!usediscard) defines += "#define NO_ALPHATEST\n"; + if (passType == GBUFFER_PASS) defines += "#define GBUFFER_PASS\n"; + + FShader *shader = NULL; + try + { + shader = new FShader(ShaderName); + if (!shader->Load(ShaderName, "shaders/glsl/main.vp", "shaders/glsl/main.fp", ShaderPath, defines.GetChars())) + { + I_FatalError("Unable to load shader %s\n", ShaderName); + } + } + catch(CRecoverableError &err) + { + if (shader != NULL) delete shader; + shader = NULL; + I_FatalError("Unable to load shader %s:\n%s\n", ShaderName, err.GetMessage()); + } + return shader; +} + +//========================================================================== +// +// +// +//========================================================================== + +void FShader::ApplyMatrices(VSMatrix *proj, VSMatrix *view, VSMatrix *norm) +{ + Bind(); + glUniformMatrix4fv(projectionmatrix_index, 1, false, proj->get()); + glUniformMatrix4fv(viewmatrix_index, 1, false, view->get()); + glUniformMatrix4fv(normalviewmatrix_index, 1, false, norm->get()); +} + +//========================================================================== +// +// +// +//========================================================================== +struct FDefaultShader +{ + const char * ShaderName; + const char * gettexelfunc; +}; + +// Note: the FIRST_USER_SHADER constant in gl_shader.h needs +// to be updated whenever the size of this array is modified. +static const FDefaultShader defaultshaders[]= +{ + {"Default", "shaders/glsl/func_normal.fp"}, + {"Warp 1", "shaders/glsl/func_warp1.fp"}, + {"Warp 2", "shaders/glsl/func_warp2.fp"}, + {"Brightmap","shaders/glsl/func_brightmap.fp"}, + {"No Texture", "shaders/glsl/func_notexture.fp"}, + {"Basic Fuzz", "shaders/glsl/fuzz_standard.fp"}, + {"Smooth Fuzz", "shaders/glsl/fuzz_smooth.fp"}, + {"Swirly Fuzz", "shaders/glsl/fuzz_swirly.fp"}, + {"Translucent Fuzz", "shaders/glsl/fuzz_smoothtranslucent.fp"}, + {"Jagged Fuzz", "shaders/glsl/fuzz_jagged.fp"}, + {"Noise Fuzz", "shaders/glsl/fuzz_noise.fp"}, + {"Smooth Noise Fuzz", "shaders/glsl/fuzz_smoothnoise.fp"}, + {NULL,NULL} +}; + +static TArray usershaders; + +struct FEffectShader +{ + const char *ShaderName; + const char *vp; + const char *fp1; + const char *fp2; + const char *defines; +}; + +static const FEffectShader effectshaders[]= +{ + { "fogboundary", "shaders/glsl/main.vp", "shaders/glsl/fogboundary.fp", NULL, "#define NO_ALPHATEST\n" }, + { "spheremap", "shaders/glsl/main.vp", "shaders/glsl/main.fp", "shaders/glsl/func_normal.fp", "#define SPHEREMAP\n#define NO_ALPHATEST\n" }, + { "burn", "shaders/glsl/main.vp", "shaders/glsl/burn.fp", NULL, "#define SIMPLE\n#define NO_ALPHATEST\n" }, + { "stencil", "shaders/glsl/main.vp", "shaders/glsl/stencil.fp", NULL, "#define SIMPLE\n#define NO_ALPHATEST\n" }, +}; + +FShaderManager::FShaderManager() +{ + if (!gl.legacyMode) + { + for (int passType = 0; passType < MAX_PASS_TYPES; passType++) + mPassShaders.Push(new FShaderCollection((EPassType)passType)); + } +} + +FShaderManager::~FShaderManager() +{ + if (!gl.legacyMode) + { + glUseProgram(0); + mActiveShader = NULL; + + for (auto collection : mPassShaders) + delete collection; + } +} + +void FShaderManager::SetActiveShader(FShader *sh) +{ + if (mActiveShader != sh) + { + glUseProgram(sh!= NULL? sh->GetHandle() : 0); + mActiveShader = sh; + } +} + +FShader *FShaderManager::BindEffect(int effect, EPassType passType) +{ + if (passType < mPassShaders.Size()) + return mPassShaders[passType]->BindEffect(effect); + else + return nullptr; +} + +FShader *FShaderManager::Get(unsigned int eff, bool alphateston, EPassType passType) +{ + if (passType < mPassShaders.Size()) + return mPassShaders[passType]->Get(eff, alphateston); + else + return nullptr; +} + +void FShaderManager::ApplyMatrices(VSMatrix *proj, VSMatrix *view, EPassType passType) +{ + if (gl.legacyMode) + { + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(proj->get()); + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(view->get()); + } + else + { + if (passType < mPassShaders.Size()) + mPassShaders[passType]->ApplyMatrices(proj, view); + + if (mActiveShader) + mActiveShader->Bind(); + } +} + +void FShaderManager::ResetFixedColormap() +{ + for (auto &collection : mPassShaders) + collection->ResetFixedColormap(); +} + +//========================================================================== +// +// +// +//========================================================================== + +FShaderCollection::FShaderCollection(EPassType passType) +{ + CompileShaders(passType); +} + +//========================================================================== +// +// +// +//========================================================================== + +FShaderCollection::~FShaderCollection() +{ + Clean(); +} + +//========================================================================== +// +// +// +//========================================================================== + +void FShaderCollection::CompileShaders(EPassType passType) +{ + mTextureEffects.Clear(); + mTextureEffectsNAT.Clear(); + for (int i = 0; i < MAX_EFFECTS; i++) + { + mEffectShaders[i] = NULL; + } + + for(int i=0;defaultshaders[i].ShaderName != NULL;i++) + { + FShader *shc = Compile(defaultshaders[i].ShaderName, defaultshaders[i].gettexelfunc, true, passType); + mTextureEffects.Push(shc); + if (i <= 3) + { + FShader *shc = Compile(defaultshaders[i].ShaderName, defaultshaders[i].gettexelfunc, false, passType); + mTextureEffectsNAT.Push(shc); + } + } + + for(unsigned i = 0; i < usershaders.Size(); i++) + { + FString name = ExtractFileBase(usershaders[i]); + FName sfn = name; + + FShader *shc = Compile(sfn, usershaders[i], true, passType); + mTextureEffects.Push(shc); + } + + for(int i=0;iLoad(effectshaders[i].ShaderName, effectshaders[i].vp, effectshaders[i].fp1, + effectshaders[i].fp2, effectshaders[i].defines)) + { + delete eff; + } + else mEffectShaders[i] = eff; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FShaderCollection::Clean() +{ + for (unsigned int i = 0; i < mTextureEffectsNAT.Size(); i++) + { + if (mTextureEffectsNAT[i] != NULL) delete mTextureEffectsNAT[i]; + } + for (unsigned int i = 0; i < mTextureEffects.Size(); i++) + { + if (mTextureEffects[i] != NULL) delete mTextureEffects[i]; + } + for (int i = 0; i < MAX_EFFECTS; i++) + { + if (mEffectShaders[i] != NULL) delete mEffectShaders[i]; + mEffectShaders[i] = NULL; + } + mTextureEffects.Clear(); + mTextureEffectsNAT.Clear(); +} + +//========================================================================== +// +// +// +//========================================================================== + +int FShaderCollection::Find(const char * shn) +{ + FName sfn = shn; + + for(unsigned int i=0;imName == sfn) + { + return i; + } + } + return -1; +} + + +//========================================================================== +// +// +// +//========================================================================== + +FShader *FShaderCollection::BindEffect(int effect) +{ + if (effect >= 0 && effect < MAX_EFFECTS && mEffectShaders[effect] != NULL) + { + mEffectShaders[effect]->Bind(); + return mEffectShaders[effect]; + } + return NULL; +} + + +//========================================================================== +// +// +// +//========================================================================== +EXTERN_CVAR(Int, gl_fuzztype) + +void FShaderCollection::ApplyMatrices(VSMatrix *proj, VSMatrix *view) +{ + VSMatrix norm; + norm.computeNormalMatrix(*view); + + for (int i = 0; i < 4; i++) + { + mTextureEffects[i]->ApplyMatrices(proj, view, &norm); + mTextureEffectsNAT[i]->ApplyMatrices(proj, view, &norm); + } + mTextureEffects[4]->ApplyMatrices(proj, view, &norm); + if (gl_fuzztype != 0) + { + mTextureEffects[4 + gl_fuzztype]->ApplyMatrices(proj, view, &norm); + } + for (unsigned i = 12; i < mTextureEffects.Size(); i++) + { + mTextureEffects[i]->ApplyMatrices(proj, view, &norm); + } + for (int i = 0; i < MAX_EFFECTS; i++) + { + mEffectShaders[i]->ApplyMatrices(proj, view, &norm); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_DestroyUserShaders() +{ + // todo +} + +//========================================================================== +// +// Parses a shader definition +// +//========================================================================== + +void gl_ParseHardwareShader(FScanner &sc, int deflump) +{ + int type = FTexture::TEX_Any; + bool disable_fullbright=false; + bool thiswad = false; + bool iwad = false; + int maplump = -1; + FString maplumpname; + float speed = 1.f; + + sc.MustGetString(); + if (sc.Compare("texture")) type = FTexture::TEX_Wall; + else if (sc.Compare("flat")) type = FTexture::TEX_Flat; + else if (sc.Compare("sprite")) type = FTexture::TEX_Sprite; + else sc.UnGet(); + + sc.MustGetString(); + FTextureID no = TexMan.CheckForTexture(sc.String, type); + FTexture *tex = TexMan[no]; + + sc.MustGetToken('{'); + while (!sc.CheckToken('}')) + { + sc.MustGetString(); + if (sc.Compare("shader")) + { + sc.MustGetString(); + maplumpname = sc.String; + } + else if (sc.Compare("speed")) + { + sc.MustGetFloat(); + speed = float(sc.Float); + } + } + if (!tex) + { + return; + } + + if (maplumpname.IsNotEmpty()) + { + if (tex->bWarped != 0) + { + Printf("Cannot combine warping with hardware shader on texture '%s'\n", tex->Name.GetChars()); + return; + } + tex->gl_info.shaderspeed = speed; + for(unsigned i=0;igl_info.shaderindex = i + FIRST_USER_SHADER; + return; + } + } + tex->gl_info.shaderindex = usershaders.Push(maplumpname) + FIRST_USER_SHADER; + } +} + diff --git a/src/gl/shaders/gl_shader.h b/src/gl/shaders/gl_shader.h new file mode 100644 index 000000000..acdd530aa --- /dev/null +++ b/src/gl/shaders/gl_shader.h @@ -0,0 +1,405 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#ifndef __GL_SHADERS_H__ +#define __GL_SHADERS_H__ + +#include "gl/renderer/gl_renderstate.h" +#include "name.h" + +extern bool gl_shaderactive; + +enum +{ + VATTR_VERTEX = 0, + VATTR_TEXCOORD = 1, + VATTR_COLOR = 2, + VATTR_VERTEX2 = 3, + VATTR_NORMAL = 4 +}; + +class FShaderCollection; + +//========================================================================== +// +// +//========================================================================== + +class FUniform1i +{ + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + } + + void Set(int newvalue) + { + glUniform1i(mIndex, newvalue); + } +}; + +class FBufferedUniform1i +{ + int mBuffer; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + mBuffer = 0; + } + + void Set(int newvalue) + { + if (newvalue != mBuffer) + { + mBuffer = newvalue; + glUniform1i(mIndex, newvalue); + } + } +}; + +class FBufferedUniform4i +{ + int mBuffer[4]; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + memset(mBuffer, 0, sizeof(mBuffer)); + } + + void Set(const int *newvalue) + { + if (memcmp(newvalue, mBuffer, sizeof(mBuffer))) + { + memcpy(mBuffer, newvalue, sizeof(mBuffer)); + glUniform4iv(mIndex, 1, newvalue); + } + } +}; + +class FBufferedUniform1f +{ + float mBuffer; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + mBuffer = 0; + } + + void Set(float newvalue) + { + if (newvalue != mBuffer) + { + mBuffer = newvalue; + glUniform1f(mIndex, newvalue); + } + } +}; + +class FBufferedUniform2f +{ + float mBuffer[2]; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + memset(mBuffer, 0, sizeof(mBuffer)); + } + + void Set(const float *newvalue) + { + if (memcmp(newvalue, mBuffer, sizeof(mBuffer))) + { + memcpy(mBuffer, newvalue, sizeof(mBuffer)); + glUniform2fv(mIndex, 1, newvalue); + } + } + + void Set(float f1, float f2) + { + if (mBuffer[0] != f1 || mBuffer[1] != f2) + { + mBuffer[0] = f1; + mBuffer[1] = f2; + glUniform2fv(mIndex, 1, mBuffer); + } + } + +}; + +class FBufferedUniform4f +{ + float mBuffer[4]; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + memset(mBuffer, 0, sizeof(mBuffer)); + } + + void Set(const float *newvalue) + { + if (memcmp(newvalue, mBuffer, sizeof(mBuffer))) + { + memcpy(mBuffer, newvalue, sizeof(mBuffer)); + glUniform4fv(mIndex, 1, newvalue); + } + } +}; + +class FUniform4f +{ + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + } + + void Set(const float *newvalue) + { + glUniform4fv(mIndex, 1, newvalue); + } + + void Set(float a, float b, float c, float d) + { + glUniform4f(mIndex, a, b, c, d); + } +}; + +class FBufferedUniformPE +{ + PalEntry mBuffer; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + mBuffer = 0; + } + + void Set(PalEntry newvalue) + { + if (newvalue != mBuffer) + { + mBuffer = newvalue; + glUniform4f(mIndex, newvalue.r/255.f, newvalue.g/255.f, newvalue.b/255.f, newvalue.a/255.f); + } + } +}; + +class FBufferedUniformSampler +{ + int mBuffer; + int mIndex; + +public: + void Init(GLuint hShader, const GLchar *name) + { + mIndex = glGetUniformLocation(hShader, name); + mBuffer = -1; + } + + void Set(int newvalue) + { + if (newvalue != mBuffer) + { + mBuffer = newvalue; + glUniform1i(mIndex, newvalue); + } + } +}; + + +class FShader +{ + friend class FShaderCollection; + friend class FRenderState; + + unsigned int hShader; + unsigned int hVertProg; + unsigned int hFragProg; + FName mName; + + FBufferedUniform1f muDesaturation; + FBufferedUniform1i muFogEnabled; + FBufferedUniform1i muTextureMode; + FBufferedUniform4f muCameraPos; + FBufferedUniform4f muLightParms; + FBufferedUniform2f muClipSplit; + FUniform1i muFixedColormap; + FUniform4f muColormapStart; + FUniform4f muColormapRange; + FBufferedUniform1i muLightIndex; + FBufferedUniformPE muFogColor; + FBufferedUniform4f muDynLightColor; + FBufferedUniformPE muObjectColor; + FUniform4f muGlowBottomColor; + FUniform4f muGlowTopColor; + FUniform4f muGlowBottomPlane; + FUniform4f muGlowTopPlane; + FUniform4f muSplitBottomPlane; + FUniform4f muSplitTopPlane; + FUniform4f muClipLine; + FBufferedUniform1f muInterpolationFactor; + FBufferedUniform1f muClipHeight; + FBufferedUniform1f muClipHeightDirection; + FBufferedUniform1f muAlphaThreshold; + FBufferedUniform1f muTimer; + + int lights_index; + int projectionmatrix_index; + int viewmatrix_index; + int normalviewmatrix_index; + int modelmatrix_index; + int normalmodelmatrix_index; + int texturematrix_index; +public: + int vertexmatrix_index; + int texcoordmatrix_index; + int quadmode_index; + int fakevb_index; +private: + int currentglowstate = 0; + int currentsplitstate = 0; + int currentcliplinestate = 0; + int currentfixedcolormap = 0; + bool currentTextureMatrixState = true;// by setting the matrix state to 'true' it is guaranteed to be set the first time the render state gets applied. + bool currentModelMatrixState = true; + +public: + FShader(const char *name) + : mName(name) + { + hShader = hVertProg = hFragProg = 0; + } + + ~FShader(); + + bool Load(const char * name, const char * vert_prog_lump, const char * fragprog, const char * fragprog2, const char *defines); + + void SetColormapColor(float r, float g, float b, float r1, float g1, float b1); + void SetGlowParams(float *topcolors, float topheight, float *bottomcolors, float bottomheight); + void SetLightRange(int start, int end, int forceadd); + + bool Bind(); + unsigned int GetHandle() const { return hShader; } + + void ApplyMatrices(VSMatrix *proj, VSMatrix *view, VSMatrix *norm); + +}; + +//========================================================================== +// +// The global shader manager +// +//========================================================================== +class FShaderManager +{ +public: + FShaderManager(); + ~FShaderManager(); + + void SetActiveShader(FShader *sh); + FShader *GetActiveShader() const { return mActiveShader; } + + FShader *BindEffect(int effect, EPassType passType); + FShader *Get(unsigned int eff, bool alphateston, EPassType passType); + void ApplyMatrices(VSMatrix *proj, VSMatrix *view, EPassType passType); + + void ResetFixedColormap(); + +private: + FShader *mActiveShader = nullptr; + TArray mPassShaders; +}; + +class FShaderCollection +{ + TArray mTextureEffects; + TArray mTextureEffectsNAT; + FShader *mEffectShaders[MAX_EFFECTS]; + + void Clean(); + void CompileShaders(EPassType passType); + +public: + FShaderCollection(EPassType passType); + ~FShaderCollection(); + FShader *Compile(const char *ShaderName, const char *ShaderPath, bool usediscard, EPassType passType); + int Find(const char *mame); + FShader *BindEffect(int effect); + void ApplyMatrices(VSMatrix *proj, VSMatrix *view); + + void ResetFixedColormap() + { + for (unsigned i = 0; i < mTextureEffects.Size(); i++) + { + mTextureEffects[i]->currentfixedcolormap = -1; + } + for (unsigned i = 0; i < mTextureEffectsNAT.Size(); i++) + { + mTextureEffectsNAT[i]->currentfixedcolormap = -1; + } + } + + FShader *Get(unsigned int eff, bool alphateston) + { + // indices 0-2 match the warping modes, 3 is brightmap, 4 no texture, the following are custom + if (!alphateston && eff <= 3) + { + return mTextureEffectsNAT[eff]; // Non-alphatest shaders are only created for default, warp1+2 and brightmap. The rest won't get used anyway + } + if (eff < mTextureEffects.Size()) + { + return mTextureEffects[eff]; + } + return NULL; + } +}; + +#define FIRST_USER_SHADER 12 + +enum +{ + LIGHTBUF_BINDINGPOINT = 1 +}; + +#endif + diff --git a/src/gl/shaders/gl_shaderprogram.cpp b/src/gl/shaders/gl_shaderprogram.cpp new file mode 100644 index 000000000..1ed19913a --- /dev/null +++ b/src/gl/shaders/gl_shaderprogram.cpp @@ -0,0 +1,246 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_shaderprogram.cpp +** GLSL shader program compile and link +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/shaders/gl_shaderprogram.h" +#include "w_wad.h" +#include "i_system.h" +#include "doomerrors.h" + +FShaderProgram::FShaderProgram() +{ + for (int i = 0; i < NumShaderTypes; i++) + mShaders[i] = 0; +} + +//========================================================================== +// +// Free shader program resources +// +//========================================================================== + +FShaderProgram::~FShaderProgram() +{ + if (mProgram != 0) + glDeleteProgram(mProgram); + + for (int i = 0; i < NumShaderTypes; i++) + { + if (mShaders[i] != 0) + glDeleteShader(mShaders[i]); + } +} + +//========================================================================== +// +// Creates an OpenGL shader object for the specified type of shader +// +//========================================================================== + +void FShaderProgram::CreateShader(ShaderType type) +{ + GLenum gltype = 0; + switch (type) + { + default: + case Vertex: gltype = GL_VERTEX_SHADER; break; + case Fragment: gltype = GL_FRAGMENT_SHADER; break; + } + mShaders[type] = glCreateShader(gltype); +} + +//========================================================================== +// +// Compiles a shader and attaches it the program object +// +//========================================================================== + +void FShaderProgram::Compile(ShaderType type, const char *lumpName, const char *defines, int maxGlslVersion) +{ + int lump = Wads.CheckNumForFullName(lumpName); + if (lump == -1) I_FatalError("Unable to load '%s'", lumpName); + FString code = Wads.ReadLump(lump).GetString().GetChars(); + Compile(type, lumpName, code, defines, maxGlslVersion); +} + +void FShaderProgram::Compile(ShaderType type, const char *name, const FString &code, const char *defines, int maxGlslVersion) +{ + CreateShader(type); + + const auto &handle = mShaders[type]; + + FGLDebug::LabelObject(GL_SHADER, handle, name); + + FString patchedCode = PatchShader(type, code, defines, maxGlslVersion); + int lengths[1] = { (int)patchedCode.Len() }; + const char *sources[1] = { patchedCode.GetChars() }; + glShaderSource(handle, 1, sources, lengths); + + glCompileShader(handle); + + GLint status = 0; + glGetShaderiv(handle, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) + { + I_FatalError("Compile Shader '%s':\n%s\n", name, GetShaderInfoLog(handle).GetChars()); + } + else + { + if (mProgram == 0) + mProgram = glCreateProgram(); + glAttachShader(mProgram, handle); + } +} + +//========================================================================== +// +// Binds a fragment output variable to a frame buffer render target +// +//========================================================================== + +void FShaderProgram::SetFragDataLocation(int index, const char *name) +{ + glBindFragDataLocation(mProgram, index, name); +} + +//========================================================================== +// +// Links a program with the compiled shaders +// +//========================================================================== + +void FShaderProgram::Link(const char *name) +{ + FGLDebug::LabelObject(GL_PROGRAM, mProgram, name); + glLinkProgram(mProgram); + + GLint status = 0; + glGetProgramiv(mProgram, GL_LINK_STATUS, &status); + if (status == GL_FALSE) + { + I_FatalError("Link Shader '%s':\n%s\n", name, GetProgramInfoLog(mProgram).GetChars()); + } +} + +//========================================================================== +// +// Set vertex attribute location +// +//========================================================================== + +void FShaderProgram::SetAttribLocation(int index, const char *name) +{ + glBindAttribLocation(mProgram, index, name); +} + +//========================================================================== +// +// Makes the shader the active program +// +//========================================================================== + +void FShaderProgram::Bind() +{ + glUseProgram(mProgram); +} + +//========================================================================== +// +// Returns the shader info log (warnings and compile errors) +// +//========================================================================== + +FString FShaderProgram::GetShaderInfoLog(GLuint handle) +{ + static char buffer[10000]; + GLsizei length = 0; + buffer[0] = 0; + glGetShaderInfoLog(handle, 10000, &length, buffer); + return FString(buffer); +} + +//========================================================================== +// +// Returns the program info log (warnings and compile errors) +// +//========================================================================== + +FString FShaderProgram::GetProgramInfoLog(GLuint handle) +{ + static char buffer[10000]; + GLsizei length = 0; + buffer[0] = 0; + glGetProgramInfoLog(handle, 10000, &length, buffer); + return FString(buffer); +} + +//========================================================================== +// +// Patches a shader to be compatible with the version of OpenGL in use +// +//========================================================================== + +FString FShaderProgram::PatchShader(ShaderType type, const FString &code, const char *defines, int maxGlslVersion) +{ + FString patchedCode; + + int shaderVersion = MIN((int)round(gl.glslversion * 10) * 10, maxGlslVersion); + patchedCode.AppendFormat("#version %d\n", shaderVersion); + + // TODO: Find some way to add extension requirements to the patching + // + // #extension GL_ARB_uniform_buffer_object : require + // #extension GL_ARB_shader_storage_buffer_object : require + + if (defines) + patchedCode << defines; + + // these settings are actually pointless but there seem to be some old ATI drivers that fail to compile the shader without setting the precision here. + patchedCode << "precision highp int;\n"; + patchedCode << "precision highp float;\n"; + + patchedCode << "#line 1\n"; + patchedCode << code; + + return patchedCode; +} + +//========================================================================== +// +// patch the shader source to work with +// GLSL 1.2 keywords and identifiers +// +//========================================================================== + diff --git a/src/gl/shaders/gl_shaderprogram.h b/src/gl/shaders/gl_shaderprogram.h new file mode 100644 index 000000000..aabfb1f6f --- /dev/null +++ b/src/gl/shaders/gl_shaderprogram.h @@ -0,0 +1,43 @@ +#ifndef __GL_SHADERPROGRAM_H +#define __GL_SHADERPROGRAM_H + +#include "gl_shader.h" + +class FShaderProgram +{ +public: + FShaderProgram(); + ~FShaderProgram(); + + enum ShaderType + { + Vertex, + Fragment, + NumShaderTypes + }; + + void Compile(ShaderType type, const char *lumpName, const char *defines, int maxGlslVersion); + void Compile(ShaderType type, const char *name, const FString &code, const char *defines, int maxGlslVersion); + void SetFragDataLocation(int index, const char *name); + void Link(const char *name); + void SetAttribLocation(int index, const char *name); + void Bind(); + + operator GLuint() const { return mProgram; } + explicit operator bool() const { return mProgram != 0; } + +private: + FShaderProgram(const FShaderProgram &) = delete; + FShaderProgram &operator=(const FShaderProgram &) = delete; + + static FString PatchShader(ShaderType type, const FString &code, const char *defines, int maxGlslVersion); + + void CreateShader(ShaderType type); + FString GetShaderInfoLog(GLuint handle); + FString GetProgramInfoLog(GLuint handle); + + GLuint mProgram = 0; + GLuint mShaders[NumShaderTypes]; +}; + +#endif \ No newline at end of file diff --git a/src/gl/shaders/gl_texshader.cpp b/src/gl/shaders/gl_texshader.cpp new file mode 100644 index 000000000..f91529909 --- /dev/null +++ b/src/gl/shaders/gl_texshader.cpp @@ -0,0 +1,698 @@ +/* +** gl_shaders.cpp +** Routines parsing/managing texture shaders. +** +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** Copyright 2009 Christoph Oelckers +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "gl/system/gl_system.h" +#include "doomtype.h" +#include "c_cvars.h" +#include "sc_man.h" +#include "textures/textures.h" +#include "gl/shaders/gl_texshader.h" + +CVAR(Bool, gl_texture_useshaders, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + + +//========================================================================== +// +// +// +//========================================================================== + +FShaderLayer::FShaderLayer() +{ + animate = false; + emissive = false; + blendFuncSrc = GL_SRC_ALPHA; + blendFuncDst = GL_ONE_MINUS_SRC_ALPHA; + offsetX = 0.f; + offsetY = 0.f; + centerX = 0.0f; + centerY = 0.0f; + rotate = 0.f; + rotation = 0.f; + adjustX.SetParams(0.f, 0.f, 0.f); + adjustY.SetParams(0.f, 0.f, 0.f); + scaleX.SetParams(1.f, 1.f, 0.f); + scaleY.SetParams(1.f, 1.f, 0.f); + alpha.SetParams(1.f, 1.f, 0.f); + r.SetParams(1.f, 1.f, 0.f); + g.SetParams(1.f, 1.f, 0.f); + b.SetParams(1.f, 1.f, 0.f); + flags = 0; + layerMask = NULL; + texgen = SHADER_TexGen_None; + warp = false; + warpspeed = 0; +} + +//========================================================================== +// +// +// +//========================================================================== + +FShaderLayer::FShaderLayer(const FShaderLayer &layer) +{ + texture = layer.texture; + animate = layer.animate; + emissive = layer.emissive; + adjustX = layer.adjustX; + adjustY = layer.adjustY; + blendFuncSrc = layer.blendFuncSrc; + blendFuncDst = layer.blendFuncDst; + offsetX = layer.offsetX; + offsetY = layer.offsetY; + centerX = layer.centerX; + centerY = layer.centerX; + rotate = layer.rotate; + rotation = layer.rotation; + scaleX = layer.scaleX; + scaleY = layer.scaleY; + vectorX = layer.vectorX; + vectorY = layer.vectorY; + alpha = layer.alpha; + r = layer.r; + g = layer.g; + b = layer.b; + flags = layer.flags; + if (layer.layerMask) + { + layerMask = new FShaderLayer(*(layer.layerMask)); + } + else + { + layerMask = NULL; + } + texgen = layer.texgen; + warp = layer.warp; + warpspeed = layer.warpspeed; +} + +//========================================================================== +// +// +// +//========================================================================== + +FShaderLayer::~FShaderLayer() +{ + if (layerMask) + { + delete layerMask; + layerMask = NULL; + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void FShaderLayer::Update(float diff) +{ + r.Update(diff); + g.Update(diff); + b.Update(diff); + alpha.Update(diff); + vectorY.Update(diff); + vectorX.Update(diff); + scaleX.Update(diff); + scaleY.Update(diff); + adjustX.Update(diff); + adjustY.Update(diff); + srcFactor.Update(diff); + dstFactor.Update(diff); + + offsetX += vectorX * diff; + if (offsetX >= 1.f) offsetX -= 1.f; + if (offsetX < 0.f) offsetX += 1.f; + + offsetY += vectorY * diff; + if (offsetY >= 1.f) offsetY -= 1.f; + if (offsetY < 0.f) offsetY += 1.f; + + rotation += rotate * diff; + if (rotation > 360.f) rotation -= 360.f; + if (rotation < 0.f) rotation += 360.f; + + if (layerMask != NULL) layerMask->Update(diff); +} + +//========================================================================== +// +// +// +//========================================================================== + +struct FParseKey +{ + const char *name; + int value; +}; + +static const FParseKey CycleTags[]= +{ + {"linear", CYCLE_Linear}, + {"sin", CYCLE_Sin}, + {"cos", CYCLE_Cos}, + {"sawtooth", CYCLE_SawTooth}, + {"square", CYCLE_Square}, + {NULL} +}; + +static const FParseKey BlendTags[]= +{ + {"GL_ZERO", GL_ZERO}, + {"GL_ONE", GL_ONE}, + + {"GL_DST_COLOR", GL_DST_COLOR}, + {"GL_ONE_MINUS_DST_COLOR", GL_ONE_MINUS_DST_COLOR}, + {"GL_DST_ALPHA", GL_DST_ALPHA}, + {"GL_ONE_MINUS_DST_ALPHA", GL_ONE_MINUS_DST_ALPHA}, + + {"GL_SRC_COLOR", GL_SRC_COLOR}, + {"GL_ONE_MINUS_SRC_COLOR", GL_ONE_MINUS_SRC_COLOR}, + {"GL_SRC_ALPHA", GL_SRC_ALPHA}, + {"GL_ONE_MINUS_SRC_ALPHA", GL_ONE_MINUS_SRC_ALPHA}, + + {"GL_SRC_ALPHA_SATURATE", GL_SRC_ALPHA_SATURATE}, + {NULL} +}; + + +//========================================================================== +// +// +// +//========================================================================== + +CycleType FShaderLayer::ParseCycleType(FScanner &sc) +{ + if (sc.GetString()) + { + int t = sc.MatchString(&CycleTags[0].name, sizeof(CycleTags[0])); + if (t > -1) return CycleType(CycleTags[t].value); + sc.UnGet(); + } + return CYCLE_Linear; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool FShaderLayer::ParseLayer(FScanner &sc) +{ + bool retval = true; + float start, end, cycle, r1, r2, g1, g2, b1, b2; + int type; + + if (sc.GetString()) + { + texture = TexMan.CheckForTexture(sc.String, FTexture::TEX_Wall); + if (!texture.isValid()) + { + sc.ScriptMessage("Unknown texture '%s'", sc.String); + retval = false; + } + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + if (sc.End) + { + sc.ScriptError("Unexpected end of file encountered"); + return false; + } + + if (sc.Compare("alpha")) + { + if (sc.CheckString("cycle")) + { + alpha.ShouldCycle(true); + alpha.SetCycleType(ParseCycleType(sc)); + + sc.GetFloat(); + start = sc.Float; + sc.GetFloat(); + end = sc.Float; + sc.GetFloat(); + cycle = sc.Float; + + alpha.SetParams(start, end, cycle); + } + else + { + sc.MustGetFloat(); + alpha.SetParams(float(sc.Float), float(sc.Float), 0.f); + } + } + else if (sc.Compare("srcfactor")) + { + if (sc.CheckString("cycle")) + { + srcFactor.ShouldCycle(true); + srcFactor.SetCycleType(ParseCycleType(sc)); + + sc.GetFloat(); + start = sc.Float; + sc.GetFloat(); + end = sc.Float; + sc.GetFloat(); + cycle = sc.Float; + + srcFactor.SetParams(start, end, cycle); + } + else + { + sc.MustGetFloat(); + srcFactor.SetParams(float(sc.Float), float(sc.Float), 0.f); + } + } + if (sc.Compare("destfactor")) + { + if (sc.CheckString("cycle")) + { + dstFactor.ShouldCycle(true); + dstFactor.SetCycleType(ParseCycleType(sc)); + + sc.GetFloat(); + start = sc.Float; + sc.GetFloat(); + end = sc.Float; + sc.GetFloat(); + cycle = sc.Float; + + dstFactor.SetParams(start, end, cycle); + } + else + { + sc.MustGetFloat(); + dstFactor.SetParams(float(sc.Float), float(sc.Float), 0.f); + } + } + else if (sc.Compare("animate")) + { + sc.GetString(); + animate = sc.Compare("true"); + } + else if (sc.Compare("blendfunc")) + { + sc.GetString(); + type = sc.MustMatchString(&BlendTags[0].name, sizeof(BlendTags[0])); + blendFuncSrc = type;// BlendTags[type].value; + + sc.GetString(); + type = sc.MustMatchString(&BlendTags[0].name, sizeof(BlendTags[0])); + blendFuncDst = type; //BlendTags[type].value; + } + else if (sc.Compare("color")) + { + if (sc.CheckString("cycle")) + { + CycleType type = ParseCycleType(sc); + r.ShouldCycle(true); + g.ShouldCycle(true); + b.ShouldCycle(true); + r.SetCycleType(type); + g.SetCycleType(type); + b.SetCycleType(type); + + sc.GetFloat(); + r1 = float(sc.Float); + sc.GetFloat(); + g1 = float(sc.Float); + sc.GetFloat(); + b1 = float(sc.Float); + + // get color2 + sc.GetFloat(); + r2 = float(sc.Float); + sc.GetFloat(); + g2 = float(sc.Float); + sc.GetFloat(); + b2 = float(sc.Float); + + // get cycle time + sc.GetFloat(); + cycle = sc.Float; + + r.SetParams(r1, r2, cycle); + g.SetParams(g1, g2, cycle); + b.SetParams(b1, b2, cycle); + } + else + { + sc.GetFloat(); + r1 = float(sc.Float); + sc.GetFloat(); + g1 = sc.Float; + sc.GetFloat(); + b1 = sc.Float; + + r.SetParams(r1, r1, 0.f); + g.SetParams(g1, g1, 0.f); + b.SetParams(b1, b1, 0.f); + } + } + else if (sc.Compare("center")) + { + sc.GetFloat(); + centerX = sc.Float; + sc.GetFloat(); + centerY = sc.Float; + } + else if (sc.Compare("emissive")) + { + sc.GetString(); + emissive = sc.Compare("true"); + } + else if (sc.Compare("offset")) + { + if (sc.CheckString("cycle")) + { + adjustX.ShouldCycle(true); + adjustY.ShouldCycle(true); + + sc.GetFloat(); + r1 = sc.Float; + sc.GetFloat(); + r2 = sc.Float; + + sc.GetFloat(); + g1 = sc.Float; + sc.GetFloat(); + g2 = sc.Float; + + sc.GetFloat(); + cycle = sc.Float; + + offsetX = r1; + offsetY = r2; + + adjustX.SetParams(0.f, g1 - r1, cycle); + adjustY.SetParams(0.f, g2 - r2, cycle); + } + else + { + sc.GetFloat(); + offsetX = sc.Float; + sc.GetFloat(); + offsetY = sc.Float; + } + } + else if (sc.Compare("offsetfunc")) + { + adjustX.SetCycleType(ParseCycleType(sc)); + adjustY.SetCycleType(ParseCycleType(sc)); + } + else if (sc.Compare("mask")) + { + if (layerMask != NULL) delete layerMask; + layerMask = new FShaderLayer; + layerMask->ParseLayer(sc); + } + else if (sc.Compare("rotate")) + { + sc.GetFloat(); + rotate = sc.Float; + } + else if (sc.Compare("rotation")) + { + sc.GetFloat(); + rotation = sc.Float; + } + else if (sc.Compare("scale")) + { + if (sc.CheckString("cycle")) + { + scaleX.ShouldCycle(true); + scaleY.ShouldCycle(true); + + sc.GetFloat(); + r1 = sc.Float; + sc.GetFloat(); + r2 = sc.Float; + + sc.GetFloat(); + g1 = sc.Float; + sc.GetFloat(); + g2 = sc.Float; + + sc.GetFloat(); + cycle = sc.Float; + + scaleX.SetParams(r1, g1, cycle); + scaleY.SetParams(r2, g2, cycle); + } + else + { + sc.GetFloat(); + scaleX.SetParams(sc.Float, sc.Float, 0.f); + sc.GetFloat(); + scaleY.SetParams(sc.Float, sc.Float, 0.f); + } + } + else if (sc.Compare("scalefunc")) + { + scaleX.SetCycleType(ParseCycleType(sc)); + scaleY.SetCycleType(ParseCycleType(sc)); + } + else if (sc.Compare("texgen")) + { + sc.MustGetString(); + if (sc.Compare("sphere")) + { + texgen = SHADER_TexGen_Sphere; + } + else + { + texgen = SHADER_TexGen_None; + } + } + else if (sc.Compare("vector")) + { + if (sc.CheckString("cycle")) + { + vectorX.ShouldCycle(true); + vectorY.ShouldCycle(true); + + sc.GetFloat(); + r1 = sc.Float; + sc.GetFloat(); + g1 = sc.Float; + sc.GetFloat(); + r2 = sc.Float; + sc.GetFloat(); + g2 = sc.Float; + sc.GetFloat(); + cycle = sc.Float; + + vectorX.SetParams(r1, r2, cycle); + vectorY.SetParams(g1, g2, cycle); + } + else + { + sc.GetFloat(); + vectorX.SetParams(sc.Float, sc.Float, 0.f); + sc.GetFloat(); + vectorY.SetParams(sc.Float, sc.Float, 0.f); + } + } + else if (sc.Compare("vectorfunc")) + { + vectorX.SetCycleType(ParseCycleType(sc)); + vectorY.SetCycleType(ParseCycleType(sc)); + } + else if (sc.Compare("warp")) + { + if (sc.CheckNumber()) + { + warp = sc.Number >= 0 && sc.Number <= 2? sc.Number : 0; + } + else + { + // compatibility with ZDoomGL + sc.MustGetString(); + warp = sc.Compare("true"); + } + } + else + { + sc.ScriptError("Unknown keyword '%s' in shader layer", sc.String); + } + } + } + return retval; +} + +//========================================================================== +// +// +// +//========================================================================== + +FTextureShader::FTextureShader() +{ + layers.Clear(); + lastUpdate = 0; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool FTextureShader::ParseShader(FScanner &sc, TArray &names) +{ + bool retval = true; + + if (sc.GetString()) + { + name = sc.String; + + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + if (sc.End) + { + sc.ScriptError("Unexpected end of file encountered"); + return false; + } + else if (sc.Compare("layer")) + { + FShaderLayer *lay = new FShaderLayer; + if (lay->ParseLayer(sc)) + { + if (layers.Size() < 8) + { + layers.Push(lay); + } + else + { + delete lay; + sc.ScriptMessage("Only 8 layers per texture allowed."); + } + } + else + { + delete lay; + retval = false; + } + } + else + { + sc.ScriptError("Unknown keyword '%s' in shader", sc.String); + } + } + } + return retval; +} + +//========================================================================== +// +// +// +//========================================================================== + +void FTextureShader::Update(int framems) +{ + float diff = (framems - lastUpdate) / 1000.f; + + if (lastUpdate != 0) // && !paused && !bglobal.freeze) + { + for (unsigned int i = 0; i < layers.Size(); i++) + { + layers[i]->Update(diff); + } + } + lastUpdate = framems; +} + +//========================================================================== +// +// +// +//========================================================================== + +void FTextureShader::FakeUpdate(int framems) +{ + lastUpdate = framems; +} + +//========================================================================== +// +// +// +//========================================================================== + +FString FTextureShader::CreateName() +{ + FString compose = "custom"; + for(unsigned i=0; iemissive, + layers[i]->blendFuncSrc, layers[i]->blendFuncDst, layers[i]->texgen, layers[i]->warp); + } + return compose; +} + +//========================================================================== +// +// +// +//========================================================================== + +FString FTextureShader::GenerateCode() +{ + static const char *funcnames[] = {"gettexel", "getwarp1", "getwarp2" }; + static const char *srcblend[] = { "vec4(0.0)", "src", "src*dest", "1.0-src*dest", "src*dest.a", "1.0-src*dest.a", + "src*src", "1.0-src*src", "src*src.a", "1.0-src*src", "vec4(src.rgb*src.a, 1)" }; + static const char *dstblend[] = { "vec4(0.0)", "dest", "dest*dest", "1.0-dest*dest", "dest*dest.a", "1.0-dest*dest.a", + "dest*src", "1.0-dest*src", "dest*src.a", "1.0-dest*src", "vec4(dest.rgb*src.a, 1)" }; + FString compose; + for(unsigned i=0; iwarp], i+1, i, i); + if (!layers[i]->emissive) compose.AppendFormat("src.rgb *= gl_Color.rgb;\n"); + compose.AppendFormat("dest = (%s)*srcfactor + (%s)*dstfactor;\n", + srcblend[layers[i]->blendFuncSrc], dstblend[layers[i]->blendFuncDst]); + } + return compose; +} + diff --git a/src/gl/shaders/gl_texshader.h b/src/gl/shaders/gl_texshader.h new file mode 100644 index 000000000..b3e90bf56 --- /dev/null +++ b/src/gl/shaders/gl_texshader.h @@ -0,0 +1,96 @@ + +#ifndef __GL_TEXSHADERS_H__ +#define __GL_TEXSHADERS_H__ + + +#include "tarray.h" +#include "zstring.h" +#include "gl/utility/gl_cycler.h" + + +enum +{ + SHADER_TexGen_None = 0, + SHADER_TexGen_Sphere, + NUM_TexGenTypes +}; + + +//========================================================================== +// +// +// +//========================================================================== + +class FShaderLayer +{ +public: + FShaderLayer(); + FShaderLayer(const FShaderLayer &layer); + ~FShaderLayer(); + void Update(float diff); + CycleType ParseCycleType(FScanner &sc); + bool ParseLayer(FScanner &sc); + + FTextureID texture; + int warpspeed; + unsigned char warp; + bool animate; + bool emissive; + unsigned char texgen; + float centerX, centerY; + float rotation; + float rotate; + float offsetX, offsetY; + FCycler adjustX, adjustY; + FCycler vectorX, vectorY; + FCycler scaleX, scaleY; + FCycler alpha; + FCycler r, g, b; + FCycler srcFactor, dstFactor; + unsigned int flags; + unsigned int blendFuncSrc, blendFuncDst; + FShaderLayer *layerMask; +}; + +//========================================================================== +// +// +// +//========================================================================== + +class FTextureShader +{ +public: + FTextureShader(); + bool ParseShader(FScanner &sc, TArray &names); + bool Available(); + bool Setup(float time); + void Update(int framems); + void FakeUpdate(int framems); + FString CreateName(); + FString GenerateCode(); + + FName name; + TDeletingArray layers; // layers for shader + unsigned int lastUpdate; +}; + + +/* +//extern TArray Shaders[NUM_ShaderClasses]; +//extern TArray ShaderLookup[NUM_ShaderClasses]; + +void GL_InitShaders(); +void GL_ReleaseShaders(); +void GL_UpdateShaders(); +void GL_FakeUpdateShaders(); +//void GL_UpdateShader(FShader *shader); +void GL_DrawShaders(); +//FShader *GL_ShaderForTexture(FTexture *tex); + +bool GL_ParseShader(); +*/ + + +#endif // __GL_TEXSHADERS_H__ diff --git a/src/gl/shaders/gl_tonemapshader.cpp b/src/gl/shaders/gl_tonemapshader.cpp new file mode 100644 index 000000000..3db6db8ba --- /dev/null +++ b/src/gl/shaders/gl_tonemapshader.cpp @@ -0,0 +1,120 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_tonemapshader.cpp +** Converts a HDR texture to 0-1 range by applying a tonemap operator +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "gl/gl_functions.h" +#include "vectors.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_tonemapshader.h" + +void FTonemapShader::Bind() +{ + auto &shader = mShader[gl_tonemap]; + if (!shader) + { + shader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + shader.Compile(FShaderProgram::Fragment, "shaders/glsl/tonemap.fp", GetDefines(gl_tonemap), 330); + shader.SetFragDataLocation(0, "FragColor"); + shader.Link("shaders/glsl/tonemap"); + shader.SetAttribLocation(0, "PositionInProjection"); + SceneTexture.Init(shader, "InputTexture"); + ExposureTexture.Init(shader, "ExposureTexture"); + PaletteLUT.Init(shader, "PaletteLUT"); + } + shader.Bind(); +} + +bool FTonemapShader::IsPaletteMode() +{ + return gl_tonemap == Palette; +} + +const char *FTonemapShader::GetDefines(int mode) +{ + switch (mode) + { + default: + case Linear: return "#define LINEAR\n"; + case Reinhard: return "#define REINHARD\n"; + case HejlDawson: return "#define HEJLDAWSON\n"; + case Uncharted2: return "#define UNCHARTED2\n"; + case Palette: return "#define PALETTE\n"; + } +} + +void FExposureExtractShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/exposureextract.fp", "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/exposureextract"); + mShader.SetAttribLocation(0, "PositionInProjection"); + SceneTexture.Init(mShader, "SceneTexture"); + Scale.Init(mShader, "Scale"); + Offset.Init(mShader, "Offset"); + } + mShader.Bind(); +} + +void FExposureAverageShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 400); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/exposureaverage.fp", "", 400); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/exposureaverage"); + mShader.SetAttribLocation(0, "PositionInProjection"); + ExposureTexture.Init(mShader, "ExposureTexture"); + } + mShader.Bind(); +} + +void FExposureCombineShader::Bind() +{ + if (!mShader) + { + mShader.Compile(FShaderProgram::Vertex, "shaders/glsl/screenquad.vp", "", 330); + mShader.Compile(FShaderProgram::Fragment, "shaders/glsl/exposurecombine.fp", "", 330); + mShader.SetFragDataLocation(0, "FragColor"); + mShader.Link("shaders/glsl/exposurecombine"); + mShader.SetAttribLocation(0, "PositionInProjection"); + ExposureTexture.Init(mShader, "ExposureTexture"); + ExposureBase.Init(mShader, "ExposureBase"); + ExposureMin.Init(mShader, "ExposureMin"); + ExposureScale.Init(mShader, "ExposureScale"); + ExposureSpeed.Init(mShader, "ExposureSpeed"); + } + mShader.Bind(); +} \ No newline at end of file diff --git a/src/gl/shaders/gl_tonemapshader.h b/src/gl/shaders/gl_tonemapshader.h new file mode 100644 index 000000000..b4cd102de --- /dev/null +++ b/src/gl/shaders/gl_tonemapshader.h @@ -0,0 +1,73 @@ +#ifndef __GL_TONEMAPSHADER_H +#define __GL_TONEMAPSHADER_H + +#include "gl_shaderprogram.h" + +class FTonemapShader +{ +public: + void Bind(); + + FBufferedUniformSampler SceneTexture; + FBufferedUniformSampler ExposureTexture; + FBufferedUniformSampler PaletteLUT; + + static bool IsPaletteMode(); + +private: + enum TonemapMode + { + None, + Uncharted2, + HejlDawson, + Reinhard, + Linear, + Palette, + NumTonemapModes + }; + + static const char *GetDefines(int mode); + + FShaderProgram mShader[NumTonemapModes]; +}; + +class FExposureExtractShader +{ +public: + void Bind(); + + FBufferedUniformSampler SceneTexture; + FBufferedUniform2f Scale; + FBufferedUniform2f Offset; + +private: + FShaderProgram mShader; +}; + +class FExposureAverageShader +{ +public: + void Bind(); + + FBufferedUniformSampler ExposureTexture; + +private: + FShaderProgram mShader; +}; + +class FExposureCombineShader +{ +public: + void Bind(); + + FBufferedUniformSampler ExposureTexture; + FBufferedUniform1f ExposureBase; + FBufferedUniform1f ExposureMin; + FBufferedUniform1f ExposureScale; + FBufferedUniform1f ExposureSpeed; + +private: + FShaderProgram mShader; +}; + +#endif \ No newline at end of file diff --git a/src/gl/stereo3d/gl_anaglyph.cpp b/src/gl/stereo3d/gl_anaglyph.cpp new file mode 100644 index 000000000..0eb994baf --- /dev/null +++ b/src/gl/stereo3d/gl_anaglyph.cpp @@ -0,0 +1,85 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_anaglyph.cpp +** Color mask based stereoscopic 3D modes for GZDoom +** +*/ + +#include "gl_anaglyph.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" + +namespace s3d { + +MaskAnaglyph::MaskAnaglyph(const ColorMask& leftColorMask, double ipdMeters) + : leftEye(leftColorMask, ipdMeters), rightEye(leftColorMask.inverse(), ipdMeters) +{ + eye_ptrs.Push(&leftEye); + eye_ptrs.Push(&rightEye); +} + +void MaskAnaglyph::Present() const +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + + gl_RenderState.SetColorMask(leftEye.GetColorMask().r, leftEye.GetColorMask().g, leftEye.GetColorMask().b, true); + gl_RenderState.ApplyColorMask(); + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); + + gl_RenderState.SetColorMask(rightEye.GetColorMask().r, rightEye.GetColorMask().g, rightEye.GetColorMask().b, true); + gl_RenderState.ApplyColorMask(); + GLRenderer->mBuffers->BindEyeTexture(1, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); + + gl_RenderState.ResetColorMask(); + gl_RenderState.ApplyColorMask(); +} + + +/* static */ +const GreenMagenta& GreenMagenta::getInstance(float ipd) +{ + static GreenMagenta instance(ipd); + return instance; +} + + +/* static */ +const RedCyan& RedCyan::getInstance(float ipd) +{ + static RedCyan instance(ipd); + return instance; +} + + +/* static */ +const AmberBlue& AmberBlue::getInstance(float ipd) +{ + static AmberBlue instance(ipd); + return instance; +} + + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_anaglyph.h b/src/gl/stereo3d/gl_anaglyph.h new file mode 100644 index 000000000..c05174e35 --- /dev/null +++ b/src/gl/stereo3d/gl_anaglyph.h @@ -0,0 +1,113 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_anaglyph.h +** Color mask based stereoscopic 3D modes for GZDoom +** +*/ + +#ifndef GL_ANAGLYPH_H_ +#define GL_ANAGLYPH_H_ + +#include "gl_stereo3d.h" +#include "gl_stereo_leftright.h" +#include "gl/system/gl_system.h" +#include "gl/renderer/gl_renderstate.h" + + +namespace s3d { + + +class ColorMask +{ +public: + ColorMask(bool r, bool g, bool b) : r(r), g(g), b(b) {} + ColorMask inverse() const { return ColorMask(!r, !g, !b); } + + bool r; + bool g; + bool b; +}; + + +class AnaglyphLeftPose : public LeftEyePose +{ +public: + AnaglyphLeftPose(const ColorMask& colorMask, float ipd) : LeftEyePose(ipd), colorMask(colorMask) {} + ColorMask GetColorMask() const { return colorMask; } + +private: + ColorMask colorMask; +}; + +class AnaglyphRightPose : public RightEyePose +{ +public: + AnaglyphRightPose(const ColorMask& colorMask, float ipd) : RightEyePose(ipd), colorMask(colorMask) {} + ColorMask GetColorMask() const { return colorMask; } + +private: + ColorMask colorMask; +}; + +class MaskAnaglyph : public Stereo3DMode +{ +public: + MaskAnaglyph(const ColorMask& leftColorMask, double ipdMeters); + void Present() const override; +private: + AnaglyphLeftPose leftEye; + AnaglyphRightPose rightEye; +}; + + +class RedCyan : public MaskAnaglyph +{ +public: + static const RedCyan& getInstance(float ipd); + + RedCyan(float ipd) : MaskAnaglyph(ColorMask(true, false, false), ipd) {} +}; + +class GreenMagenta : public MaskAnaglyph +{ +public: + static const GreenMagenta& getInstance(float ipd); + + GreenMagenta(float ipd) : MaskAnaglyph(ColorMask(false, true, false), ipd) {} +}; + +class AmberBlue : public MaskAnaglyph +{ +public: + static const AmberBlue& getInstance(float ipd); + + AmberBlue(float ipd) : MaskAnaglyph(ColorMask(true, true, false), ipd) {} +}; + +// TODO matrix anaglyph + + +} /* namespace s3d */ + + +#endif /* GL_ANAGLYPH_H_ */ diff --git a/src/gl/stereo3d/gl_interleaved3d.cpp b/src/gl/stereo3d/gl_interleaved3d.cpp new file mode 100644 index 000000000..029d233e4 --- /dev/null +++ b/src/gl/stereo3d/gl_interleaved3d.cpp @@ -0,0 +1,211 @@ +/* +** gl_interleaved3d.cpp +** Interleaved image stereoscopic 3D modes for GZDoom +** +**--------------------------------------------------------------------------- +** Copyright 2016 Christopher Bruns +** 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 author 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. +**--------------------------------------------------------------------------- +** +** +*/ + +#include "gl_interleaved3d.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/shaders/gl_present3dRowshader.h" + +EXTERN_CVAR(Float, vid_brightness) +EXTERN_CVAR(Float, vid_contrast) +EXTERN_CVAR(Bool, fullscreen) +EXTERN_CVAR(Int, win_x) // screen pixel position of left of display window +EXTERN_CVAR(Int, win_y) // screen pixel position of top of display window + +namespace s3d { + +/* static */ +const CheckerInterleaved3D& CheckerInterleaved3D::getInstance(float ipd) +{ + static CheckerInterleaved3D instance(ipd); + return instance; +} + +/* static */ +const ColumnInterleaved3D& ColumnInterleaved3D::getInstance(float ipd) +{ + static ColumnInterleaved3D instance(ipd); + return instance; +} + +/* static */ +const RowInterleaved3D& RowInterleaved3D::getInstance(float ipd) +{ + static RowInterleaved3D instance(ipd); + return instance; +} + +static void prepareInterleavedPresent(FPresentStereoShaderBase& shader) +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + + + // Bind each eye texture, for composition in the shader + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->mBuffers->BindEyeTexture(1, 1); + + glActiveTexture(GL_TEXTURE0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + glActiveTexture(GL_TEXTURE1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + const GL_IRECT& box = GLRenderer->mOutputLetterbox; + glViewport(box.left, box.top, box.width, box.height); + + shader.Bind(); + shader.LeftEyeTexture.Set(0); + shader.RightEyeTexture.Set(1); + + if ( GLRenderer->framebuffer->IsHWGammaActive() ) + { + shader.InvGamma.Set(1.0f); + shader.Contrast.Set(1.0f); + shader.Brightness.Set(0.0f); + } + else + { + shader.InvGamma.Set(1.0f / clamp(Gamma, 0.1f, 4.f)); + shader.Contrast.Set(clamp(vid_contrast, 0.1f, 3.f)); + shader.Brightness.Set(clamp(vid_brightness, -0.8f, 0.8f)); + } + shader.Scale.Set( + GLRenderer->mScreenViewport.width / (float)GLRenderer->mBuffers->GetWidth(), + GLRenderer->mScreenViewport.height / (float)GLRenderer->mBuffers->GetHeight()); +} + +// fixme: I don't know how to get absolute window position on Mac and Linux +// fixme: I don't know how to get window border decoration size anywhere +// So for now I'll hard code the border effect on my test machine. +// Workaround for others is to fuss with vr_swap_eyes CVAR until it looks right. +// Presumably the top/left window border on my test machine has an odd number of pixels +// in the horizontal direction, and an even number in the vertical direction. +#define WINDOW_BORDER_HORIZONTAL_PARITY 1 +#define WINDOW_BORDER_VERTICAL_PARITY 0 + +void CheckerInterleaved3D::Present() const +{ + prepareInterleavedPresent(*GLRenderer->mPresent3dCheckerShader); + + // Compute absolute offset from top of screen to top of current display window + // because we need screen-relative, not window-relative, scan line parity + int windowVOffset = 0; + int windowHOffset = 0; + +#ifdef _WIN32 + if (!fullscreen) { + I_SaveWindowedPos(); // update win_y CVAR + windowHOffset = (win_x + WINDOW_BORDER_HORIZONTAL_PARITY) % 2; + windowVOffset = (win_y + WINDOW_BORDER_VERTICAL_PARITY) % 2; + } +#endif // _WIN32 + + GLRenderer->mPresent3dCheckerShader->WindowPositionParity.Set( + (windowVOffset + + windowHOffset + + GLRenderer->mOutputLetterbox.height + 1 // +1 because of origin at bottom + ) % 2 // because we want the top pixel offset, but gl_FragCoord.y is the bottom pixel offset + ); + + GLRenderer->RenderScreenQuad(); +} + +void s3d::CheckerInterleaved3D::AdjustViewports() const +{ + // decrease the total pixel count by 2, but keep the same aspect ratio + const float sqrt2 = 1.41421356237f; + // Change size of renderbuffer, and align to screen + GLRenderer->mSceneViewport.height /= sqrt2; + GLRenderer->mSceneViewport.top /= sqrt2; + GLRenderer->mSceneViewport.width /= sqrt2; + GLRenderer->mSceneViewport.left /= sqrt2; + + GLRenderer->mScreenViewport.height /= sqrt2; + GLRenderer->mScreenViewport.top /= sqrt2; + GLRenderer->mScreenViewport.width /= sqrt2; + GLRenderer->mScreenViewport.left /= sqrt2; +} + +void ColumnInterleaved3D::Present() const +{ + prepareInterleavedPresent(*GLRenderer->mPresent3dColumnShader); + + // Compute absolute offset from top of screen to top of current display window + // because we need screen-relative, not window-relative, scan line parity + int windowHOffset = 0; + +#ifdef _WIN32 + if (!fullscreen) { + I_SaveWindowedPos(); // update win_y CVAR + windowHOffset = (win_x + WINDOW_BORDER_HORIZONTAL_PARITY) % 2; + } +#endif // _WIN32 + + GLRenderer->mPresent3dColumnShader->WindowPositionParity.Set(windowHOffset); + + GLRenderer->RenderScreenQuad(); +} + +void RowInterleaved3D::Present() const +{ + prepareInterleavedPresent(*GLRenderer->mPresent3dRowShader); + + // Compute absolute offset from top of screen to top of current display window + // because we need screen-relative, not window-relative, scan line parity + int windowVOffset = 0; + +#ifdef _WIN32 + if (! fullscreen) { + I_SaveWindowedPos(); // update win_y CVAR + windowVOffset = (win_y + WINDOW_BORDER_VERTICAL_PARITY) % 2; + } +#endif // _WIN32 + + GLRenderer->mPresent3dRowShader->WindowPositionParity.Set( + (windowVOffset + + GLRenderer->mOutputLetterbox.height + 1 // +1 because of origin at bottom + ) % 2 + ); + + GLRenderer->RenderScreenQuad(); +} + + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_interleaved3d.h b/src/gl/stereo3d/gl_interleaved3d.h new file mode 100644 index 000000000..78bd19483 --- /dev/null +++ b/src/gl/stereo3d/gl_interleaved3d.h @@ -0,0 +1,75 @@ +/* +** gl_interleaved3d.h +** Interleaved stereoscopic 3D modes for GZDoom +** +**--------------------------------------------------------------------------- +** Copyright 2016 Christopher Bruns +** 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 author 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. +**--------------------------------------------------------------------------- +** +** +*/ + +#ifndef GL_INTERLEAVED3D_H_ +#define GL_INTERLEAVED3D_H_ + +#include "gl_stereo3d.h" +#include "gl_stereo_leftright.h" +#include "gl_sidebyside3d.h" +#include "gl/system/gl_system.h" +#include "gl/renderer/gl_renderstate.h" + +namespace s3d { + +class CheckerInterleaved3D : public SideBySideSquished +{ +public: + static const CheckerInterleaved3D& getInstance(float ipd); + CheckerInterleaved3D(double ipdMeters) : SideBySideSquished(ipdMeters) {} + void Present() const override; + void AdjustViewports() const override; +}; + +class ColumnInterleaved3D : public SideBySideSquished +{ +public: + static const ColumnInterleaved3D& getInstance(float ipd); + ColumnInterleaved3D(double ipdMeters) : SideBySideSquished(ipdMeters) {} + void Present() const override; +}; + +class RowInterleaved3D : public TopBottom3D +{ +public: + static const RowInterleaved3D& getInstance(float ipd); + RowInterleaved3D(double ipdMeters) : TopBottom3D(ipdMeters) {} + void Present() const override; +}; + +} /* namespace s3d */ + + +#endif /* GL_INTERLEAVED3D_H_ */ diff --git a/src/gl/stereo3d/gl_quadstereo.cpp b/src/gl/stereo3d/gl_quadstereo.cpp new file mode 100644 index 000000000..b65c109c8 --- /dev/null +++ b/src/gl/stereo3d/gl_quadstereo.cpp @@ -0,0 +1,116 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_quadstereo.cpp +** Quad-buffered OpenGL stereoscopic 3D mode for GZDoom +** +*/ + +#include "gl_quadstereo.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" + +namespace s3d { + +QuadStereo::QuadStereo(double ipdMeters) + : leftEye(ipdMeters), rightEye(ipdMeters) +{ + // Check whether quad-buffered stereo is supported in the current context + // We are assuming the OpenGL context is already current at this point, + // i.e. this constructor is called "just in time". + + // First initialize to mono-ish initial state + bQuadStereoSupported = leftEye.bQuadStereoSupported = rightEye.bQuadStereoSupported = false; + eye_ptrs.Push(&leftEye); // We ALWAYS want to show at least this one view... + // We will possibly advance to true stereo mode in the Setup() method... +} + +// Sometimes the stereo render context is not ready immediately at start up +/* private */ +void QuadStereo::checkInitialRenderContextState() +{ + // Keep trying until we see at least one good OpenGL context to render to + static bool bDecentContextWasFound = false; + if (!bDecentContextWasFound) { + // I'm using a "random" OpenGL call (glGetFramebufferAttachmentParameteriv) + // that appears to correlate with whether the context is ready + GLint attachmentType = GL_NONE; + glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &attachmentType); + if (attachmentType != GL_NONE) // Finally, a useful OpenGL context + { + // This block will be executed exactly ONCE during a game run + bDecentContextWasFound = true; // now we can stop checking every frame... + // Now check whether this context supports hardware stereo + GLboolean supportsStereo, supportsBuffered; + glGetBooleanv(GL_STEREO, &supportsStereo); + glGetBooleanv(GL_DOUBLEBUFFER, &supportsBuffered); + bQuadStereoSupported = supportsStereo && supportsBuffered; + leftEye.bQuadStereoSupported = bQuadStereoSupported; + rightEye.bQuadStereoSupported = bQuadStereoSupported; + if (bQuadStereoSupported) + eye_ptrs.Push(&rightEye); // Use the other eye too, if we can do stereo + } + } +} + +void QuadStereo::Present() const +{ + if (bQuadStereoSupported) + { + GLRenderer->mBuffers->BindOutputFB(); + + glDrawBuffer(GL_BACK_LEFT); + GLRenderer->ClearBorders(); + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); + + glDrawBuffer(GL_BACK_RIGHT); + GLRenderer->ClearBorders(); + GLRenderer->mBuffers->BindEyeTexture(1, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); + + glDrawBuffer(GL_BACK); + } + else + { + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); + } +} + +void QuadStereo::SetUp() const +{ + Stereo3DMode::SetUp(); + // Maybe advance to true stereo mode (ONCE), after the stereo context is finally ready + const_cast(this)->checkInitialRenderContextState(); +} + +/* static */ +const QuadStereo& QuadStereo::getInstance(float ipd) +{ + static QuadStereo instance(ipd); + return instance; +} + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_quadstereo.h b/src/gl/stereo3d/gl_quadstereo.h new file mode 100644 index 000000000..377d846b3 --- /dev/null +++ b/src/gl/stereo3d/gl_quadstereo.h @@ -0,0 +1,77 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_quadstereo.h +** Quad-buffered OpenGL stereoscopic 3D mode for GZDoom +** +*/ + +#ifndef GL_QUADSTEREO_H_ +#define GL_QUADSTEREO_H_ + +#include "gl_stereo3d.h" +#include "gl_stereo_leftright.h" +#include "gl/system/gl_system.h" + +namespace s3d { + + +class QuadStereoLeftPose : public LeftEyePose +{ +public: + QuadStereoLeftPose(float ipd) : LeftEyePose(ipd), bQuadStereoSupported(false) {} + bool bQuadStereoSupported; +}; + +class QuadStereoRightPose : public RightEyePose +{ +public: + QuadStereoRightPose(float ipd) : RightEyePose(ipd), bQuadStereoSupported(false){} + bool bQuadStereoSupported; +}; + +// To use Quad-buffered stereo mode with nvidia 3d vision glasses, +// you must either: +// A) be using a Quadro series video card, OR +// +// B) be using nvidia driver version 314.07 or later +// AND have your monitor set to 120 Hz refresh rate +// AND have gzdoom in true full screen mode +class QuadStereo : public Stereo3DMode +{ +public: + QuadStereo(double ipdMeters); + void Present() const override; + void SetUp() const override; + static const QuadStereo& getInstance(float ipd); +private: + QuadStereoLeftPose leftEye; + QuadStereoRightPose rightEye; + bool bQuadStereoSupported; + void checkInitialRenderContextState(); +}; + + +} /* namespace s3d */ + + +#endif /* GL_QUADSTEREO_H_ */ diff --git a/src/gl/stereo3d/gl_sidebyside3d.cpp b/src/gl/stereo3d/gl_sidebyside3d.cpp new file mode 100644 index 000000000..ecb3ec1cc --- /dev/null +++ b/src/gl/stereo3d/gl_sidebyside3d.cpp @@ -0,0 +1,150 @@ +/* +** gl_sidebyside3d.cpp +** Mosaic image stereoscopic 3D modes for GZDoom +** +**--------------------------------------------------------------------------- +** Copyright 2016 Christopher Bruns +** 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 author 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. +**--------------------------------------------------------------------------- +** +** +*/ + +#include "gl_sidebyside3d.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" + +namespace s3d { + +void SideBySideBase::Present() const +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + + // Compute screen regions to use for left and right eye views + int leftWidth = GLRenderer->mOutputLetterbox.width / 2; + int rightWidth = GLRenderer->mOutputLetterbox.width - leftWidth; + GL_IRECT leftHalfScreen = GLRenderer->mOutputLetterbox; + leftHalfScreen.width = leftWidth; + GL_IRECT rightHalfScreen = GLRenderer->mOutputLetterbox; + rightHalfScreen.width = rightWidth; + rightHalfScreen.left += leftWidth; + + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(leftHalfScreen, true); + + GLRenderer->mBuffers->BindEyeTexture(1, 0); + GLRenderer->DrawPresentTexture(rightHalfScreen, true); +} + +// AdjustViewports() is called from within FLGRenderer::SetOutputViewport(...) +void SideBySideBase::AdjustViewports() const +{ + // Change size of renderbuffer, and align to screen + GLRenderer->mSceneViewport.width /= 2; + GLRenderer->mSceneViewport.left /= 2; + GLRenderer->mScreenViewport.width /= 2; + GLRenderer->mScreenViewport.left /= 2; +} + +/* static */ +const SideBySideSquished& SideBySideSquished::getInstance(float ipd) +{ + static SideBySideSquished instance(ipd); + return instance; +} + +SideBySideSquished::SideBySideSquished(double ipdMeters) + : leftEye(ipdMeters), rightEye(ipdMeters) +{ + eye_ptrs.Push(&leftEye); + eye_ptrs.Push(&rightEye); +} + +/* static */ +const SideBySideFull& SideBySideFull::getInstance(float ipd) +{ + static SideBySideFull instance(ipd); + return instance; +} + +SideBySideFull::SideBySideFull(double ipdMeters) + : leftEye(ipdMeters), rightEye(ipdMeters) +{ + eye_ptrs.Push(&leftEye); + eye_ptrs.Push(&rightEye); +} + +/* virtual */ +void SideBySideFull::AdjustPlayerSprites() const /* override */ +{ + // Show weapon at double width, so it would appear normal width after rescaling + int w = GLRenderer->mScreenViewport.width; + int h = GLRenderer->mScreenViewport.height; + gl_RenderState.mProjectionMatrix.ortho(w/2, w + w/2, h, 0, -1.0f, 1.0f); + gl_RenderState.ApplyMatrices(); +} + +/* static */ +const TopBottom3D& TopBottom3D::getInstance(float ipd) +{ + static TopBottom3D instance(ipd); + return instance; +} + +void TopBottom3D::Present() const +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + + // Compute screen regions to use for left and right eye views + int topHeight = GLRenderer->mOutputLetterbox.height / 2; + int bottomHeight = GLRenderer->mOutputLetterbox.height - topHeight; + GL_IRECT topHalfScreen = GLRenderer->mOutputLetterbox; + topHalfScreen.height = topHeight; + topHalfScreen.top = topHeight; + GL_IRECT bottomHalfScreen = GLRenderer->mOutputLetterbox; + bottomHalfScreen.height = bottomHeight; + bottomHalfScreen.top = 0; + + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(topHalfScreen, true); + + GLRenderer->mBuffers->BindEyeTexture(1, 0); + GLRenderer->DrawPresentTexture(bottomHalfScreen, true); +} + +// AdjustViewports() is called from within FLGRenderer::SetOutputViewport(...) +void TopBottom3D::AdjustViewports() const +{ + // Change size of renderbuffer, and align to screen + GLRenderer->mSceneViewport.height /= 2; + GLRenderer->mSceneViewport.top /= 2; + GLRenderer->mScreenViewport.height /= 2; + GLRenderer->mScreenViewport.top /= 2; +} + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_sidebyside3d.h b/src/gl/stereo3d/gl_sidebyside3d.h new file mode 100644 index 000000000..c98f748a0 --- /dev/null +++ b/src/gl/stereo3d/gl_sidebyside3d.h @@ -0,0 +1,103 @@ +/* +** gl_sidebyside3d.h +** Mosaic image stereoscopic 3D modes for GZDoom +** +**--------------------------------------------------------------------------- +** Copyright 2016 Christopher Bruns +** 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 author 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. +**--------------------------------------------------------------------------- +** +** +*/ + +#ifndef GL_SIDEBYSIDE3D_H_ +#define GL_SIDEBYSIDE3D_H_ + +#include "gl_stereo3d.h" +#include "gl_stereo_leftright.h" +#include "gl/system/gl_system.h" +#include "gl/renderer/gl_renderstate.h" + + +namespace s3d { + +class SideBySideBase : public Stereo3DMode +{ +public: + void Present() const override; + virtual void AdjustViewports() const override; +}; + +class SideBySideSquished : public SideBySideBase +{ +public: + static const SideBySideSquished& getInstance(float ipd); + SideBySideSquished(double ipdMeters); +private: + LeftEyePose leftEye; + RightEyePose rightEye; +}; + +class SBSFLeftEyePose : public LeftEyePose { +public: + SBSFLeftEyePose(double ipdMeters) : LeftEyePose(ipdMeters) {} + virtual VSMatrix GetProjection(float fov, float aspectRatio, float fovRatio) const override { + return LeftEyePose::GetProjection(fov, 0.5f * aspectRatio, fovRatio); + } +}; + +class SBSFRightEyePose : public RightEyePose { +public: + SBSFRightEyePose(double ipdMeters) : RightEyePose(ipdMeters) {} + virtual VSMatrix GetProjection(float fov, float aspectRatio, float fovRatio) const override { + return RightEyePose::GetProjection(fov, 0.5f * aspectRatio, fovRatio); + } +}; + +class SideBySideFull : public SideBySideBase +{ +public: + static const SideBySideFull& getInstance(float ipd); + SideBySideFull(double ipdMeters); + virtual void AdjustPlayerSprites() const override; +private: + SBSFLeftEyePose leftEye; + SBSFRightEyePose rightEye; +}; + +class TopBottom3D : public SideBySideSquished +{ +public: + static const TopBottom3D& getInstance(float ipd); + TopBottom3D(double ipdMeters) : SideBySideSquished(ipdMeters) {} + void Present() const override; + virtual void AdjustViewports() const override; +}; + +} /* namespace s3d */ + + +#endif /* GL_SIDEBYSIDE3D_H_ */ diff --git a/src/gl/stereo3d/gl_stereo3d.cpp b/src/gl/stereo3d/gl_stereo3d.cpp new file mode 100644 index 000000000..6b1623ba6 --- /dev/null +++ b/src/gl/stereo3d/gl_stereo3d.cpp @@ -0,0 +1,85 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_stereo3d.cpp +** Stereoscopic 3D API +** +*/ + +#include "gl/system/gl_system.h" +#include "gl/stereo3d/gl_stereo3d.h" +#include "gl/renderer/gl_renderer.h" +#include "vectors.h" // RAD2DEG +#include "doomtype.h" // M_PI + +namespace s3d { + + +/* virtual */ +VSMatrix EyePose::GetProjection(float fov, float aspectRatio, float fovRatio) const +{ + VSMatrix result; + + // Lifted from gl_scene.cpp FGLRenderer::SetProjection() + float fovy = (float)(2 * RAD2DEG(atan(tan(DEG2RAD(fov) / 2) / fovRatio))); + result.perspective(fovy, aspectRatio, FGLRenderer::GetZNear(), FGLRenderer::GetZFar()); + + return result; +} + +/* virtual */ +Viewport EyePose::GetViewport(const Viewport& fullViewport) const +{ + return fullViewport; +} + + +/* virtual */ +void EyePose::GetViewShift(float yaw, float outViewShift[3]) const +{ + // pass-through for Mono view + outViewShift[0] = 0; + outViewShift[1] = 0; + outViewShift[2] = 0; +} + + +Stereo3DMode::Stereo3DMode() +{ +} + +Stereo3DMode::~Stereo3DMode() +{ +} + +// Avoid static initialization order fiasco by declaring first Mode type (Mono) here in the +// same source file as Stereo3DMode::getCurrentMode() +// https://isocpp.org/wiki/faq/ctors#static-init-order + +/* static */ +const MonoView& MonoView::getInstance() +{ + static MonoView instance; + return instance; +} + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_stereo3d.h b/src/gl/stereo3d/gl_stereo3d.h new file mode 100644 index 000000000..81a72874f --- /dev/null +++ b/src/gl/stereo3d/gl_stereo3d.h @@ -0,0 +1,115 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_stereo3d.h +** Stereoscopic 3D API +** +*/ + +#ifndef GL_STEREO3D_H_ +#define GL_STEREO3D_H_ + +#include // needed for memcpy on linux, which is needed by VSMatrix copy ctor +#include "tarray.h" +#include "gl/data/gl_matrix.h" +#include "gl/renderer/gl_renderer.h" + + +/* stereoscopic 3D API */ +namespace s3d { + + +/* Subregion of current display window */ +class Viewport +{ +public: + int x, y; + int width, height; +}; + + +/* Viewpoint of one eye */ +class EyePose +{ +public: + EyePose() {} + virtual ~EyePose() {} + virtual VSMatrix GetProjection(float fov, float aspectRatio, float fovRatio) const; + virtual Viewport GetViewport(const Viewport& fullViewport) const; + virtual void GetViewShift(float yaw, float outViewShift[3]) const; + virtual void SetUp() const {}; + virtual void TearDown() const {}; +}; + + +/* Base class for stereoscopic 3D rendering modes */ +class Stereo3DMode +{ +public: + /* static methods for managing the selected stereoscopic view state */ + static const Stereo3DMode& getCurrentMode(); + static const Stereo3DMode& getMonoMode(); + + Stereo3DMode(); + virtual ~Stereo3DMode(); + virtual int eye_count() const { return eye_ptrs.Size(); } + virtual const EyePose * getEyePose(int ix) const { return eye_ptrs(ix); } + + /* hooks for setup and cleanup operations for each stereo mode */ + virtual void SetUp() const {}; + virtual void TearDown() const {}; + + virtual bool IsMono() const { return false; } + virtual void AdjustViewports() const {}; + virtual void AdjustPlayerSprites() const {}; + virtual void Present() const = 0; + +protected: + TArray eye_ptrs; + +private: + static Stereo3DMode const * currentStereo3DMode; + static void setCurrentMode(const Stereo3DMode& mode); +}; + + +/** +* Ordinary non-3D rendering +*/ +class MonoView : public Stereo3DMode +{ +public: + static const MonoView& getInstance(); + + bool IsMono() const override { return true; } + void Present() const override { } + +protected: + MonoView() { eye_ptrs.Push(¢ralEye); } + EyePose centralEye; +}; + + +} /* namespace st3d */ + + +#endif /* GL_STEREO3D_H_ */ diff --git a/src/gl/stereo3d/gl_stereo_cvars.cpp b/src/gl/stereo3d/gl_stereo_cvars.cpp new file mode 100644 index 000000000..fe5ae3261 --- /dev/null +++ b/src/gl/stereo3d/gl_stereo_cvars.cpp @@ -0,0 +1,132 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_stereo_cvars.cpp +** Console variables related to stereoscopic 3D in GZDoom +** +*/ + +#include "gl/stereo3d/gl_stereo3d.h" +#include "gl/stereo3d/gl_stereo_leftright.h" +#include "gl/stereo3d/gl_anaglyph.h" +#include "gl/stereo3d/gl_quadstereo.h" +#include "gl/stereo3d/gl_sidebyside3d.h" +#include "gl/stereo3d/gl_interleaved3d.h" +#include "gl/system/gl_cvars.h" + +// Set up 3D-specific console variables: +CVAR(Int, vr_mode, 0, CVAR_GLOBALCONFIG) + +// switch left and right eye views +CVAR(Bool, vr_swap_eyes, false, CVAR_GLOBALCONFIG) + +// For broadest GL compatibility, require user to explicitly enable quad-buffered stereo mode. +// Setting vr_enable_quadbuffered_stereo does not automatically invoke quad-buffered stereo, +// but makes it possible for subsequent "vr_mode 7" to invoke quad-buffered stereo +CVAR(Bool, vr_enable_quadbuffered, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + +// intraocular distance in meters +CVAR(Float, vr_ipd, 0.062f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) // METERS + +// distance between viewer and the display screen +CVAR(Float, vr_screendist, 0.80f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) // METERS + +// default conversion between (vertical) DOOM units and meters +CVAR(Float, vr_hunits_per_meter, 41.0f, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) // METERS + +// Manage changing of 3D modes: +namespace s3d { + +// Initialize static member +Stereo3DMode const * Stereo3DMode::currentStereo3DMode = 0; // "nullptr" not resolved on linux (presumably not C++11) + +/* static */ +void Stereo3DMode::setCurrentMode(const Stereo3DMode& mode) { + Stereo3DMode::currentStereo3DMode = &mode; +} + +/* static */ +const Stereo3DMode& Stereo3DMode::getCurrentMode() +{ + // NOTE: Ensure that these vr_mode values correspond to the ones in wadsrc/static/menudef.z + switch (vr_mode) + { + case 1: + setCurrentMode(GreenMagenta::getInstance(vr_ipd)); + break; + case 2: + setCurrentMode(RedCyan::getInstance(vr_ipd)); + break; + case 3: + setCurrentMode(SideBySideFull::getInstance(vr_ipd)); + break; + case 4: + setCurrentMode(SideBySideSquished::getInstance(vr_ipd)); + break; + case 5: + setCurrentMode(LeftEyeView::getInstance(vr_ipd)); + break; + case 6: + setCurrentMode(RightEyeView::getInstance(vr_ipd)); + break; + case 7: + if (vr_enable_quadbuffered) { + setCurrentMode(QuadStereo::getInstance(vr_ipd)); + } + else { + setCurrentMode(MonoView::getInstance()); + } + break; + // TODO: 8: Oculus Rift + case 9: + setCurrentMode(AmberBlue::getInstance(vr_ipd)); + break; + // TODO: 10: HTC Vive/OpenVR + case 11: + setCurrentMode(TopBottom3D::getInstance(vr_ipd)); + break; + case 12: + setCurrentMode(RowInterleaved3D::getInstance(vr_ipd)); + break; + case 13: + setCurrentMode(ColumnInterleaved3D::getInstance(vr_ipd)); + break; + case 14: + setCurrentMode(CheckerInterleaved3D::getInstance(vr_ipd)); + break; + case 0: + default: + setCurrentMode(MonoView::getInstance()); + break; + } + return *currentStereo3DMode; +} + +const Stereo3DMode& Stereo3DMode::getMonoMode() +{ + setCurrentMode(MonoView::getInstance()); + return *currentStereo3DMode; +} + + +} /* namespace s3d */ + diff --git a/src/gl/stereo3d/gl_stereo_leftright.cpp b/src/gl/stereo3d/gl_stereo_leftright.cpp new file mode 100644 index 000000000..f2b1ba3fc --- /dev/null +++ b/src/gl/stereo3d/gl_stereo_leftright.cpp @@ -0,0 +1,117 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_stereo_leftright.cpp +** Offsets for left and right eye views +** +*/ + +#include "gl_stereo_leftright.h" +#include "vectors.h" // RAD2DEG +#include "doomtype.h" // M_PI +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_system.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderbuffers.h" +#include + +EXTERN_CVAR(Float, vr_screendist) +EXTERN_CVAR(Float, vr_hunits_per_meter) +EXTERN_CVAR(Bool, vr_swap_eyes) + +namespace s3d { + + +/* virtual */ +VSMatrix ShiftedEyePose::GetProjection(float fov, float aspectRatio, float fovRatio) const +{ + double zNear = 5.0; + double zFar = 65536.0; + + // For stereo 3D, use asymmetric frustum shift in projection matrix + // Q: shouldn't shift vary with roll angle, at least for desktop display? + // A: No. (lab) roll is not measured on desktop display (yet) + double frustumShift = zNear * getShift() / vr_screendist; // meters cancel, leaving doom units + // double frustumShift = 0; // Turning off shift for debugging + double fH = zNear * tan(DEG2RAD(fov) / 2) / fovRatio; + double fW = fH * aspectRatio; + double left = -fW - frustumShift; + double right = fW - frustumShift; + double bottom = -fH; + double top = fH; + + VSMatrix result(1); + result.frustum(left, right, bottom, top, zNear, zFar); + return result; +} + + +/* virtual */ +void ShiftedEyePose::GetViewShift(float yaw, float outViewShift[3]) const +{ + float dx = -cos(DEG2RAD(yaw)) * vr_hunits_per_meter * getShift(); + float dy = sin(DEG2RAD(yaw)) * vr_hunits_per_meter * getShift(); + outViewShift[0] = dx; + outViewShift[1] = dy; + outViewShift[2] = 0; +} + +float ShiftedEyePose::getShift() const +{ + return vr_swap_eyes ? -shift : shift; +} + +/* static */ +const LeftEyeView& LeftEyeView::getInstance(float ipd) +{ + static LeftEyeView instance(ipd); + instance.setIpd(ipd); + return instance; +} + +void LeftEyeView::Present() const +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); +} + +/* static */ +const RightEyeView& RightEyeView::getInstance(float ipd) +{ + static RightEyeView instance(ipd); + instance.setIpd(ipd); + return instance; +} + +void RightEyeView::Present() const +{ + GLRenderer->mBuffers->BindOutputFB(); + GLRenderer->ClearBorders(); + GLRenderer->mBuffers->BindEyeTexture(0, 0); + GLRenderer->DrawPresentTexture(GLRenderer->mOutputLetterbox, true); +} + + +} /* namespace s3d */ diff --git a/src/gl/stereo3d/gl_stereo_leftright.h b/src/gl/stereo3d/gl_stereo_leftright.h new file mode 100644 index 000000000..9fa7b40bc --- /dev/null +++ b/src/gl/stereo3d/gl_stereo_leftright.h @@ -0,0 +1,103 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_stereo_leftright.h +** Offsets for left and right eye views +** +*/ + +#ifndef GL_STEREO_LEFTRIGHT_H_ +#define GL_STEREO_LEFTRIGHT_H_ + +#include "gl_stereo3d.h" + +namespace s3d { + + +class ShiftedEyePose : public EyePose +{ +public: + ShiftedEyePose(float shift) : shift(shift) {}; + float getShift() const; + virtual VSMatrix GetProjection(float fov, float aspectRatio, float fovRatio) const; + virtual void GetViewShift(float yaw, float outViewShift[3]) const; + +protected: + void setShift(float shift) { this->shift = shift; } + +private: + float shift; +}; + + +class LeftEyePose : public ShiftedEyePose +{ +public: + LeftEyePose(float ipd) : ShiftedEyePose( float(-0.5) * ipd) {} + float getIpd() const { return float(fabs(2.0f*getShift())); } + void setIpd(float ipd) { setShift(float(-0.5)*ipd); } +}; + + +class RightEyePose : public ShiftedEyePose +{ +public: + RightEyePose(float ipd) : ShiftedEyePose(float(+0.5)*ipd) {} + float getIpd() const { return float(fabs(2.0f*getShift())); } + void setIpd(float ipd) { setShift(float(+0.5)*ipd); } +}; + + +/** + * As if viewed through the left eye only + */ +class LeftEyeView : public Stereo3DMode +{ +public: + static const LeftEyeView& getInstance(float ipd); + + LeftEyeView(float ipd) : eye(ipd) { eye_ptrs.Push(&eye); } + float getIpd() const { return eye.getIpd(); } + void setIpd(float ipd) { eye.setIpd(ipd); } + void Present() const override; +protected: + LeftEyePose eye; +}; + + +class RightEyeView : public Stereo3DMode +{ +public: + static const RightEyeView& getInstance(float ipd); + + RightEyeView(float ipd) : eye(ipd) { eye_ptrs.Push(&eye); } + float getIpd() const { return eye.getIpd(); } + void setIpd(float ipd) { eye.setIpd(ipd); } + void Present() const override; +protected: + RightEyePose eye; +}; + + +} /* namespace s3d */ + +#endif /* GL_STEREO_LEFTRIGHT_H_ */ diff --git a/src/gl/stereo3d/scoped_color_mask.h b/src/gl/stereo3d/scoped_color_mask.h new file mode 100644 index 000000000..e55772092 --- /dev/null +++ b/src/gl/stereo3d/scoped_color_mask.h @@ -0,0 +1,56 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** scoped_color_mask.h +** Stack-scoped class for temporarily changing the OpenGL color mask setting. +** +*/ + +#ifndef GL_STEREO3D_SCOPED_COLOR_MASK_H_ +#define GL_STEREO3D_SCOPED_COLOR_MASK_H_ + +#include "gl/system/gl_system.h" + +/** +* Temporarily change color mask +*/ +class ScopedColorMask +{ +public: + ScopedColorMask(bool r, bool g, bool b, bool a) + { + gl_RenderState.GetColorMask(saved[0], saved[1], saved[2], saved[3]); + gl_RenderState.SetColorMask(r, g, b, a); + gl_RenderState.ApplyColorMask(); + gl_RenderState.EnableDrawBuffers(1); + } + ~ScopedColorMask() { + gl_RenderState.EnableDrawBuffers(gl_RenderState.GetPassDrawBufferCount()); + gl_RenderState.SetColorMask(saved[0], saved[1], saved[2], saved[3]); + gl_RenderState.ApplyColorMask(); + } +private: + bool saved[4]; +}; + + +#endif // GL_STEREO3D_SCOPED_COLOR_MASK_H_ diff --git a/src/gl/stereo3d/scoped_view_shifter.cpp b/src/gl/stereo3d/scoped_view_shifter.cpp new file mode 100644 index 000000000..b0eb13ef9 --- /dev/null +++ b/src/gl/stereo3d/scoped_view_shifter.cpp @@ -0,0 +1,48 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** scoped_view_shifter.cpp +** Stack-scoped class for temporarily changing camera viewpoint +** Used for stereoscopic 3D. +** +*/ + +#include "scoped_view_shifter.h" +#include "r_utility.h" + +namespace s3d { + +ScopedViewShifter::ScopedViewShifter(float dxyz[3]) // in meters +{ + // save original values + cachedView = ViewPos; + // modify values + ViewPos += DVector3(dxyz[0], dxyz[1], dxyz[2]); +} + +ScopedViewShifter::~ScopedViewShifter() +{ + // restore original values + ViewPos = cachedView; +} + +} \ No newline at end of file diff --git a/src/gl/stereo3d/scoped_view_shifter.h b/src/gl/stereo3d/scoped_view_shifter.h new file mode 100644 index 000000000..bac7f2dac --- /dev/null +++ b/src/gl/stereo3d/scoped_view_shifter.h @@ -0,0 +1,52 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2015 Christopher Bruns +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** scoped_view_shifter.h +** Stack-scoped class for temporarily changing camera viewpoint +** Used for stereoscopic 3D. +** +*/ + +#ifndef GL_STEREO3D_SCOPED_VIEW_SHIFTER_H_ +#define GL_STEREO3D_SCOPED_VIEW_SHIFTER_H_ + +#include "basictypes.h" +#include "vectors.h" + +namespace s3d { + + /** + * Temporarily shift + */ + class ScopedViewShifter + { + public: + ScopedViewShifter(float dxyz[3]); // in meters + ~ScopedViewShifter(); + + private: + DVector3 cachedView; + }; + +} /* namespace s3d */ + +#endif // GL_STEREO3D_SCOPED_VIEW_SHIFTER_H_ diff --git a/src/gl/system/gl_cvars.h b/src/gl/system/gl_cvars.h new file mode 100644 index 000000000..3b425d261 --- /dev/null +++ b/src/gl/system/gl_cvars.h @@ -0,0 +1,64 @@ + + +#ifndef _GL_INTERN_H +#define _GL_INTERN_H + +#include "r_defs.h" +#include "c_cvars.h" + +#ifdef _MSC_VER +#pragma warning(disable:4244) +#endif + +EXTERN_CVAR(Bool,gl_enhanced_nightvision) +EXTERN_CVAR(Int, screenblocks); +EXTERN_CVAR(Bool, gl_texture) +EXTERN_CVAR(Int, gl_texture_filter) +EXTERN_CVAR(Float, gl_texture_filter_anisotropic) +EXTERN_CVAR(Int, gl_texture_format) +EXTERN_CVAR(Bool, gl_texture_usehires) +EXTERN_CVAR(Bool, gl_usefb) + +EXTERN_CVAR(Int, gl_weaponlight) + +EXTERN_CVAR (Bool, gl_lights); +EXTERN_CVAR (Bool, gl_attachedlights); +EXTERN_CVAR (Bool, gl_lights_checkside); +EXTERN_CVAR (Bool, gl_light_sprites); +EXTERN_CVAR (Bool, gl_light_particles); + +EXTERN_CVAR(Int, gl_fogmode) +EXTERN_CVAR(Int, gl_lightmode) +EXTERN_CVAR(Bool,gl_mirror_envmap) + +EXTERN_CVAR(Bool,gl_mirrors) +EXTERN_CVAR(Bool,gl_mirror_envmap) +EXTERN_CVAR(Bool, gl_seamless) + +EXTERN_CVAR(Float, gl_mask_threshold) +EXTERN_CVAR(Float, gl_mask_sprite_threshold) + +EXTERN_CVAR(Bool, gl_renderbuffers) +EXTERN_CVAR(Int, gl_multisample) + +EXTERN_CVAR(Bool, gl_bloom) +EXTERN_CVAR(Float, gl_bloom_amount) +EXTERN_CVAR(Int, gl_bloom_kernel_size) +EXTERN_CVAR(Int, gl_tonemap) +EXTERN_CVAR(Float, gl_exposure) +EXTERN_CVAR(Bool, gl_lens) +EXTERN_CVAR(Float, gl_lens_k) +EXTERN_CVAR(Float, gl_lens_kcube) +EXTERN_CVAR(Float, gl_lens_chromatic) +EXTERN_CVAR(Int, gl_ssao) +EXTERN_CVAR(Int, gl_ssao_portals) +EXTERN_CVAR(Float, gl_ssao_strength) +EXTERN_CVAR(Int, gl_ssao_debug) +EXTERN_CVAR(Float, gl_ssao_bias) +EXTERN_CVAR(Float, gl_ssao_radius) +EXTERN_CVAR(Float, gl_ssao_blur_amount) + +EXTERN_CVAR(Int, gl_debug_level) +EXTERN_CVAR(Bool, gl_debug_breakpoint) + +#endif // _GL_INTERN_H diff --git a/src/gl/system/gl_debug.cpp b/src/gl/system/gl_debug.cpp new file mode 100644 index 000000000..a8b1bab5d --- /dev/null +++ b/src/gl/system/gl_debug.cpp @@ -0,0 +1,338 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2016 Magnus Norddahl +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_debig.cpp +** OpenGL debugging support functions +** +*/ + +#include "templates.h" +#include "gl/system/gl_system.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_debug.h" +#include +#include + +#ifndef _MSC_VER +#include +#endif + +CUSTOM_CVAR(Int, gl_debug_level, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (!FGLDebug::HasDebugApi()) + { + Printf("No OpenGL debug support detected.\n"); + } +} + +CVAR(Bool, gl_debug_breakpoint, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +//----------------------------------------------------------------------------- +// +// Updates OpenGL debugging state +// +//----------------------------------------------------------------------------- + +void FGLDebug::Update() +{ + if (!HasDebugApi()) + return; + + SetupBreakpointMode(); + UpdateLoggingLevel(); + OutputMessageLog(); +} + +//----------------------------------------------------------------------------- +// +// Label objects so they are referenced by name in debug messages and in +// OpenGL debuggers (renderdoc) +// +//----------------------------------------------------------------------------- + +void FGLDebug::LabelObject(GLenum type, GLuint handle, const FString &name) +{ + if (HasDebugApi() && gl_debug_level != 0) + { + glObjectLabel(type, handle, (GLsizei)name.Len(), name.GetChars()); + } +} + +void FGLDebug::LabelObjectPtr(void *ptr, const FString &name) +{ + if (HasDebugApi() && gl_debug_level != 0) + { + glObjectPtrLabel(ptr, (GLsizei)name.Len(), name.GetChars()); + } +} + +//----------------------------------------------------------------------------- +// +// Marks which render pass/group is executing commands so that debuggers can +// display this information +// +//----------------------------------------------------------------------------- + +void FGLDebug::PushGroup(const FString &name) +{ + if (HasDebugApi() && gl_debug_level != 0) + { + glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, (GLsizei)name.Len(), name.GetChars()); + } +} + +void FGLDebug::PopGroup() +{ + if (HasDebugApi() && gl_debug_level != 0) + { + glPopDebugGroup(); + } +} + +//----------------------------------------------------------------------------- +// +// Turns on synchronous debugging on and off based on gl_debug_breakpoint +// +// Allows getting the debugger to break exactly at the OpenGL function emitting +// a message. +// +//----------------------------------------------------------------------------- + +void FGLDebug::SetupBreakpointMode() +{ + if (mBreakpointMode != gl_debug_breakpoint) + { + if (gl_debug_breakpoint) + { + glDebugMessageCallback(&FGLDebug::DebugCallback, this); + glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); + } + else + { + glDebugMessageCallback(nullptr, nullptr); + glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); + } + mBreakpointMode = gl_debug_breakpoint; + } +} + +//----------------------------------------------------------------------------- +// +// Tells OpenGL which debug messages we are interested in +// +//----------------------------------------------------------------------------- + +void FGLDebug::UpdateLoggingLevel() +{ + int level = gl_debug_level; + if (level != mCurrentLevel) + { + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, level > 0); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, level > 1); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW, 0, nullptr, level > 2); + glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, level > 3); + mCurrentLevel = level; + } +} + +//----------------------------------------------------------------------------- +// +// The log may already contain entries for a debug level we are no longer +// interested in.. +// +//----------------------------------------------------------------------------- + +bool FGLDebug::IsFilteredByDebugLevel(GLenum severity) +{ + int severityLevel = 0; + switch (severity) + { + case GL_DEBUG_SEVERITY_HIGH: severityLevel = 1; break; + case GL_DEBUG_SEVERITY_MEDIUM: severityLevel = 2; break; + case GL_DEBUG_SEVERITY_LOW: severityLevel = 3; break; + case GL_DEBUG_SEVERITY_NOTIFICATION: severityLevel = 4; break; + } + return severityLevel > (int)gl_debug_level; +} + +//----------------------------------------------------------------------------- +// +// Prints all logged messages to the console +// +//----------------------------------------------------------------------------- + +void FGLDebug::OutputMessageLog() +{ + if (mCurrentLevel <= 0) + return; + + GLint maxDebugMessageLength = 0; + glGetIntegerv(GL_MAX_DEBUG_MESSAGE_LENGTH, &maxDebugMessageLength); + + const int maxMessages = 50; + const int messageLogSize = maxMessages * maxDebugMessageLength; + + TArray sources, types, severities; + TArray ids; + TArray lengths; + TArray messageLog; + + sources.Resize(maxMessages); + types.Resize(maxMessages); + severities.Resize(maxMessages); + ids.Resize(maxMessages); + lengths.Resize(maxMessages); + messageLog.Resize(messageLogSize); + + while (true) + { + GLuint numMessages = glGetDebugMessageLog(maxMessages, messageLogSize, &sources[0], &types[0], &ids[0], &severities[0], &lengths[0], &messageLog[0]); + if (numMessages <= 0) break; + + GLsizei offset = 0; + for (GLuint i = 0; i < numMessages; i++) + { + if (!IsFilteredByDebugLevel(severities[i])) + PrintMessage(sources[i], types[i], ids[i], severities[i], lengths[i], &messageLog[offset]); + offset += lengths[i]; + } + } +} + +//----------------------------------------------------------------------------- +// +// Print a single message to the console +// +//----------------------------------------------------------------------------- + +void FGLDebug::PrintMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message) +{ + if (type == GL_DEBUG_TYPE_PUSH_GROUP || type == GL_DEBUG_TYPE_POP_GROUP) + return; + + const int maxMessages = 50; + + static int messagesPrinted = 0; + if (messagesPrinted > maxMessages) + return; + + FString msg(message, length); + + static std::set seenMessages; + bool alreadySeen = !seenMessages.insert(msg.GetChars()).second; + if (alreadySeen) + return; + + messagesPrinted++; + if (messagesPrinted == maxMessages) + { + Printf("Max OpenGL debug messages reached. Suppressing further output.\n"); + } + else if (messagesPrinted < maxMessages) + { + FString sourceStr = SourceToString(source); + FString typeStr = TypeToString(type); + FString severityStr = SeverityToString(severity); + if (type != GL_DEBUG_TYPE_OTHER) + Printf("[%s] %s, %s: %s\n", sourceStr.GetChars(), severityStr.GetChars(), typeStr.GetChars(), msg.GetChars()); + else + Printf("[%s] %s: %s\n", sourceStr.GetChars(), severityStr.GetChars(), msg.GetChars()); + } +} + +//----------------------------------------------------------------------------- +// +// OpenGL callback function used when synchronous debugging is enabled +// +//----------------------------------------------------------------------------- + +void FGLDebug::DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) +{ + if (IsFilteredByDebugLevel(severity)) + return; + + PrintMessage(source, type, id, severity, length, message); + + if (severity != GL_DEBUG_SEVERITY_NOTIFICATION) + { +#ifdef _MSC_VER + DebugBreak(); +#else + raise(SIGTRAP); +#endif + } +} + +//----------------------------------------------------------------------------- +// +// Enum to string helpers +// +//----------------------------------------------------------------------------- + +FString FGLDebug::SourceToString(GLenum source) +{ + FString s; + switch (source) + { + case GL_DEBUG_SOURCE_API: s = "api"; break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM: s = "window system"; break; + case GL_DEBUG_SOURCE_SHADER_COMPILER: s = "shader compiler"; break; + case GL_DEBUG_SOURCE_THIRD_PARTY: s = "third party"; break; + case GL_DEBUG_SOURCE_APPLICATION: s = "application"; break; + case GL_DEBUG_SOURCE_OTHER: s = "other"; break; + default: s.Format("%d", (int)source); + } + return s; +} + +FString FGLDebug::TypeToString(GLenum type) +{ + FString s; + switch (type) + { + case GL_DEBUG_TYPE_ERROR: s = "error"; break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: s = "deprecated"; break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: s = "undefined"; break; + case GL_DEBUG_TYPE_PORTABILITY: s = "portability"; break; + case GL_DEBUG_TYPE_PERFORMANCE: s = "performance"; break; + case GL_DEBUG_TYPE_MARKER: s = "marker"; break; + case GL_DEBUG_TYPE_PUSH_GROUP: s = "push group"; break; + case GL_DEBUG_TYPE_POP_GROUP: s = "pop group"; break; + case GL_DEBUG_TYPE_OTHER: s = "other"; break; + default: s.Format("%d", (int)type); + } + return s; +} + +FString FGLDebug::SeverityToString(GLenum severity) +{ + FString s; + switch (severity) + { + case GL_DEBUG_SEVERITY_LOW: s = "low severity"; break; + case GL_DEBUG_SEVERITY_MEDIUM: s = "medium severity"; break; + case GL_DEBUG_SEVERITY_HIGH: s = "high severity"; break; + case GL_DEBUG_SEVERITY_NOTIFICATION: s = "notification"; break; + default: s.Format("%d", (int)severity); + } + return s; +} diff --git a/src/gl/system/gl_debug.h b/src/gl/system/gl_debug.h new file mode 100644 index 000000000..52645ec16 --- /dev/null +++ b/src/gl/system/gl_debug.h @@ -0,0 +1,40 @@ +#ifndef __GL_DEBUG_H +#define __GL_DEBUG_H + +#include +#include "gl/system/gl_interface.h" +#include "c_cvars.h" +#include "r_defs.h" + +class FGLDebug +{ +public: + void Update(); + + static void LabelObject(GLenum type, GLuint handle, const FString &name); + static void LabelObjectPtr(void *ptr, const FString &name); + + static void PushGroup(const FString &name); + static void PopGroup(); + + static bool HasDebugApi() { return (gl.flags & RFL_DEBUG) != 0; } + +private: + void SetupBreakpointMode(); + void UpdateLoggingLevel(); + void OutputMessageLog(); + + static bool IsFilteredByDebugLevel(GLenum severity); + static void PrintMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message); + + static void APIENTRY DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); + + static FString SourceToString(GLenum source); + static FString TypeToString(GLenum type); + static FString SeverityToString(GLenum severity); + + GLenum mCurrentLevel = 0; + bool mBreakpointMode = false; +}; + +#endif diff --git a/src/gl/system/gl_extlist.txt b/src/gl/system/gl_extlist.txt new file mode 100644 index 000000000..efa51ad01 --- /dev/null +++ b/src/gl/system/gl_extlist.txt @@ -0,0 +1,16 @@ +-- List of OpenGL extensions for glLoadGen + +-- Generation of gl_load.c and gl_load.h files: +-- > lua LoadGen.lua -style=pointer_c -spec=gl -version=3.3 -profile=compatibility -extfile=gl_extlist.txt load + +APPLE_client_storage +ARB_buffer_storage +ARB_shader_storage_buffer_object +ARB_texture_compression +ARB_texture_rectangle +EXT_framebuffer_object +EXT_texture_compression_s3tc +EXT_texture_filter_anisotropic +EXT_texture_sRGB +KHR_debug +ARB_invalidate_subdata diff --git a/src/gl/system/gl_framebuffer.cpp b/src/gl/system/gl_framebuffer.cpp new file mode 100644 index 000000000..a015e99d9 --- /dev/null +++ b/src/gl/system/gl_framebuffer.cpp @@ -0,0 +1,551 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2010-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_framebuffer.cpp +** Implementation of the non-hardware specific parts of the +** OpenGL frame buffer +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "doomstat.h" +#include "m_png.h" +#include "m_crc32.h" +#include "vectors.h" +#include "v_palette.h" +#include "templates.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/data/gl_data.h" +#include "gl/textures/gl_hwtexture.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_skyboxtexture.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/gl_functions.h" +#include "gl/renderer/gl_2ddrawer.h" +#include "gl_debug.h" + +IMPLEMENT_CLASS(OpenGLFrameBuffer, false, false) +EXTERN_CVAR (Float, vid_brightness) +EXTERN_CVAR (Float, vid_contrast) +EXTERN_CVAR (Bool, vid_vsync) + +CVAR(Bool, gl_aalines, false, CVAR_ARCHIVE) + +FGLRenderer *GLRenderer; + +void gl_LoadExtensions(); +void gl_PrintStartupLog(); +void gl_SetupMenu(); + +CUSTOM_CVAR(Int, vid_hwgamma, 2, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (self < 0 || self > 2) self = 2; + if (GLRenderer != NULL && GLRenderer->framebuffer != NULL) GLRenderer->framebuffer->DoSetGamma(); +} + +//========================================================================== +// +// +// +//========================================================================== + +OpenGLFrameBuffer::OpenGLFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen) : + Super(hMonitor, width, height, bits, refreshHz, fullscreen, false) +{ + // SetVSync needs to be at the very top to workaround a bug in Nvidia's OpenGL driver. + // If wglSwapIntervalEXT is called after glBindFramebuffer in a frame the setting is not changed! + SetVSync(vid_vsync); + + // Make sure all global variables tracking OpenGL context state are reset.. + FHardwareTexture::InitGlobalState(); + FMaterial::InitGlobalState(); + gl_RenderState.Reset(); + + GLRenderer = new FGLRenderer(this); + memcpy (SourcePalette, GPalette.BaseColors, sizeof(PalEntry)*256); + UpdatePalette (); + ScreenshotBuffer = NULL; + LastCamera = NULL; + + InitializeState(); + mDebug = std::make_shared(); + mDebug->Update(); + gl_SetupMenu(); + gl_GenerateGlobalBrightmapFromColormap(); + DoSetGamma(); + needsetgamma = true; + swapped = false; + Accel2D = true; +} + +OpenGLFrameBuffer::~OpenGLFrameBuffer() +{ + delete GLRenderer; + GLRenderer = NULL; +} + +//========================================================================== +// +// Initializes the GL renderer +// +//========================================================================== + +void OpenGLFrameBuffer::InitializeState() +{ + static bool first=true; + + if (first) + { + ogl_LoadFunctions(); + } + + gl_LoadExtensions(); + Super::InitializeState(); + + if (first) + { + first=false; + gl_PrintStartupLog(); + } + + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClearDepth(1.0f); + glDepthFunc(GL_LESS); + + glEnable(GL_DITHER); + glDisable(GL_CULL_FACE); + glDisable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_POLYGON_OFFSET_LINE); + glEnable(GL_BLEND); + glEnable(GL_DEPTH_CLAMP); + glDisable(GL_DEPTH_TEST); + if (gl.legacyMode) glEnable(GL_TEXTURE_2D); + glDisable(GL_LINE_SMOOTH); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + GLRenderer->Initialize(GetWidth(), GetHeight()); + GLRenderer->SetOutputViewport(nullptr); + Begin2D(false); +} + +//========================================================================== +// +// Updates the screen +// +//========================================================================== + +void OpenGLFrameBuffer::Update() +{ + if (!CanUpdate()) + { + GLRenderer->Flush(); + return; + } + + Begin2D(false); + + DrawRateStuff(); + GLRenderer->Flush(); + + Swap(); + swapped = false; + Unlock(); + CheckBench(); + + if (!IsFullscreen()) + { + int clientWidth = GetClientWidth(); + int clientHeight = GetClientHeight(); + if (clientWidth > 0 && clientHeight > 0 && (Width != clientWidth || Height != clientHeight)) + { + // Do not call Resize here because it's only for software canvases + Pitch = Width = clientWidth; + Height = clientHeight; + V_OutputResized(Width, Height); + GLRenderer->mVBO->OutputResized(Width, Height); + } + } + + GLRenderer->SetOutputViewport(nullptr); +} + + +//========================================================================== +// +// Swap the buffers +// +//========================================================================== + +CVAR(Bool, gl_finishbeforeswap, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG); +extern int camtexcount; + +void OpenGLFrameBuffer::Swap() +{ + bool swapbefore = gl_finishbeforeswap && camtexcount == 0; + Finish.Reset(); + Finish.Clock(); + if (swapbefore) glFinish(); + if (needsetgamma) + { + //DoSetGamma(); + needsetgamma = false; + } + SwapBuffers(); + if (!swapbefore) glFinish(); + Finish.Unclock(); + swapped = true; + camtexcount = 0; + FHardwareTexture::UnbindAll(); + mDebug->Update(); +} + +//=========================================================================== +// +// DoSetGamma +// +// (Unfortunately Windows has some safety precautions that block gamma ramps +// that are considered too extreme. As a result this doesn't work flawlessly) +// +//=========================================================================== + +void OpenGLFrameBuffer::DoSetGamma() +{ + bool useHWGamma = m_supportsGamma && ((vid_hwgamma == 0) || (vid_hwgamma == 2 && IsFullscreen())); + if (useHWGamma) + { + WORD gammaTable[768]; + + // This formula is taken from Doomsday + float gamma = clamp(Gamma, 0.1f, 4.f); + float contrast = clamp(vid_contrast, 0.1f, 3.f); + float bright = clamp(vid_brightness, -0.8f, 0.8f); + + double invgamma = 1 / gamma; + double norm = pow(255., invgamma - 1); + + for (int i = 0; i < 256; i++) + { + double val = i * contrast - (contrast - 1) * 127; + val += bright * 128; + if(gamma != 1) val = pow(val, invgamma) / norm; + + gammaTable[i] = gammaTable[i + 256] = gammaTable[i + 512] = (WORD)clamp(val*256, 0, 0xffff); + } + SetGammaTable(gammaTable); + + HWGammaActive = true; + } + else if (HWGammaActive) + { + ResetGammaTable(); + HWGammaActive = false; + } +} + +bool OpenGLFrameBuffer::SetGamma(float gamma) +{ + DoSetGamma(); + return true; +} + +bool OpenGLFrameBuffer::SetBrightness(float bright) +{ + DoSetGamma(); + return true; +} + +bool OpenGLFrameBuffer::SetContrast(float contrast) +{ + DoSetGamma(); + return true; +} + +//=========================================================================== +// +// +//=========================================================================== + +void OpenGLFrameBuffer::UpdatePalette() +{ + int rr=0,gg=0,bb=0; + for(int x=0;x<256;x++) + { + rr+=GPalette.BaseColors[x].r; + gg+=GPalette.BaseColors[x].g; + bb+=GPalette.BaseColors[x].b; + } + rr>>=8; + gg>>=8; + bb>>=8; + + palette_brightness = (rr*77 + gg*143 + bb*35)/255; + + if (GLRenderer) + GLRenderer->ClearTonemapPalette(); +} + +void OpenGLFrameBuffer::GetFlashedPalette (PalEntry pal[256]) +{ + memcpy(pal, SourcePalette, 256*sizeof(PalEntry)); +} + +PalEntry *OpenGLFrameBuffer::GetPalette () +{ + return SourcePalette; +} + +bool OpenGLFrameBuffer::SetFlash(PalEntry rgb, int amount) +{ + Flash = PalEntry(amount, rgb.r, rgb.g, rgb.b); + return true; +} + +void OpenGLFrameBuffer::GetFlash(PalEntry &rgb, int &amount) +{ + rgb = Flash; + rgb.a = 0; + amount = Flash.a; +} + +int OpenGLFrameBuffer::GetPageCount() +{ + return 1; +} + + +//========================================================================== +// +// DFrameBuffer :: CreatePalette +// +// Creates a native palette from a remap table, if supported. +// +//========================================================================== + +FNativePalette *OpenGLFrameBuffer::CreatePalette(FRemapTable *remap) +{ + return GLTranslationPalette::CreatePalette(remap); +} + +//========================================================================== +// +// +// +//========================================================================== +bool OpenGLFrameBuffer::Begin2D(bool) +{ + gl_RenderState.mViewMatrix.loadIdentity(); + gl_RenderState.mProjectionMatrix.ortho(0, GetWidth(), GetHeight(), 0, -1.0f, 1.0f); + gl_RenderState.ApplyMatrices(); + + glDisable(GL_DEPTH_TEST); + + // Korshun: ENABLE AUTOMAP ANTIALIASING!!! + if (gl_aalines) + glEnable(GL_LINE_SMOOTH); + else + { + glDisable(GL_MULTISAMPLE); + glDisable(GL_LINE_SMOOTH); + glLineWidth(1.0); + } + + if (GLRenderer != NULL) + GLRenderer->Begin2D(); + return true; +} + +//========================================================================== +// +// Draws a texture +// +//========================================================================== + +void OpenGLFrameBuffer::DrawTextureParms(FTexture *img, DrawParms &parms) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddTexture(img, parms); +} + +//========================================================================== +// +// +// +//========================================================================== +void OpenGLFrameBuffer::DrawLine(int x1, int y1, int x2, int y2, int palcolor, uint32 color) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddLine(x1, y1, x2, y2, palcolor, color); +} + +//========================================================================== +// +// +// +//========================================================================== +void OpenGLFrameBuffer::DrawPixel(int x1, int y1, int palcolor, uint32 color) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddPixel(x1, y1, palcolor, color); +} + +//========================================================================== +// +// +// +//========================================================================== +void OpenGLFrameBuffer::Dim(PalEntry) +{ + // Unlike in the software renderer the color is being ignored here because + // view blending only affects the actual view with the GL renderer. + Super::Dim(0); +} + +void OpenGLFrameBuffer::Dim(PalEntry color, float damount, int x1, int y1, int w, int h) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddDim(color, damount, x1, y1, w, h); +} + +//========================================================================== +// +// +// +//========================================================================== +void OpenGLFrameBuffer::FlatFill (int left, int top, int right, int bottom, FTexture *src, bool local_origin) +{ + + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddFlatFill(left, top, right, bottom, src, local_origin); +} + +//========================================================================== +// +// +// +//========================================================================== +void OpenGLFrameBuffer::Clear(int left, int top, int right, int bottom, int palcolor, uint32 color) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr) + GLRenderer->m2DDrawer->AddClear(left, top, right, bottom, palcolor, color); +} + +//========================================================================== +// +// D3DFB :: FillSimplePoly +// +// Here, "simple" means that a simple triangle fan can draw it. +// +//========================================================================== + +void OpenGLFrameBuffer::FillSimplePoly(FTexture *texture, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel, int bottomclip) +{ + if (GLRenderer != nullptr && GLRenderer->m2DDrawer != nullptr && npoints >= 3) + { + GLRenderer->m2DDrawer->AddPoly(texture, points, npoints, originx, originy, scalex, scaley, rotation, colormap, lightlevel); + } +} + + +//=========================================================================== +// +// Takes a screenshot +// +//=========================================================================== + +void OpenGLFrameBuffer::GetScreenshotBuffer(const BYTE *&buffer, int &pitch, ESSType &color_type) +{ + const auto &viewport = GLRenderer->mOutputLetterbox; + + // Grab what is in the back buffer. + // We cannot rely on SCREENWIDTH/HEIGHT here because the output may have been scaled. + TArray pixels; + pixels.Resize(viewport.width * viewport.height * 3); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(viewport.left, viewport.top, viewport.width, viewport.height, GL_RGB, GL_UNSIGNED_BYTE, &pixels[0]); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + + // Copy to screenshot buffer: + int w = SCREENWIDTH; + int h = SCREENHEIGHT; + + ReleaseScreenshotBuffer(); + ScreenshotBuffer = new BYTE[w * h * 3]; + + float rcpWidth = 1.0f / w; + float rcpHeight = 1.0f / h; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + float u = (x + 0.5f) * rcpWidth; + float v = (y + 0.5f) * rcpHeight; + int sx = u * viewport.width; + int sy = v * viewport.height; + int sindex = (sx + sy * viewport.width) * 3; + int dindex = (x + y * w) * 3; + ScreenshotBuffer[dindex] = pixels[sindex]; + ScreenshotBuffer[dindex + 1] = pixels[sindex + 1]; + ScreenshotBuffer[dindex + 2] = pixels[sindex + 2]; + } + } + + pitch = -w*3; + color_type = SS_RGB; + buffer = ScreenshotBuffer + w * 3 * (h - 1); +} + +//=========================================================================== +// +// Releases the screenshot buffer. +// +//=========================================================================== + +void OpenGLFrameBuffer::ReleaseScreenshotBuffer() +{ + if (ScreenshotBuffer != NULL) delete [] ScreenshotBuffer; + ScreenshotBuffer = NULL; +} + + +void OpenGLFrameBuffer::GameRestart() +{ + memcpy (SourcePalette, GPalette.BaseColors, sizeof(PalEntry)*256); + UpdatePalette (); + ScreenshotBuffer = NULL; + LastCamera = NULL; + gl_GenerateGlobalBrightmapFromColormap(); +} + diff --git a/src/gl/system/gl_framebuffer.h b/src/gl/system/gl_framebuffer.h new file mode 100644 index 000000000..27c3d1cf9 --- /dev/null +++ b/src/gl/system/gl_framebuffer.h @@ -0,0 +1,131 @@ +#ifndef __GL_FRAMEBUFFER +#define __GL_FRAMEBUFFER + +#ifdef _WIN32 +#include "win32iface.h" +#include "win32gliface.h" +#endif + +#include + +class FHardwareTexture; +class FSimpleVertexBuffer; +class FGLDebug; + +extern long gl_frameMS; +extern long gl_frameCount; +#ifdef _WIN32 +class OpenGLFrameBuffer : public Win32GLFrameBuffer +{ + typedef Win32GLFrameBuffer Super; + DECLARE_CLASS(OpenGLFrameBuffer, Win32GLFrameBuffer) +#else +#include "sdlglvideo.h" +class OpenGLFrameBuffer : public SDLGLFB +{ +// typedef SDLGLFB Super; //[C]commented, DECLARE_CLASS defines this in linux + DECLARE_CLASS(OpenGLFrameBuffer, SDLGLFB) +#endif + + +public: + + explicit OpenGLFrameBuffer() {} + OpenGLFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen) ; + ~OpenGLFrameBuffer(); + + void InitializeState(); + void Update(); + + // Color correction + bool SetGamma (float gamma); + bool SetBrightness(float bright); + bool SetContrast(float contrast); + void DoSetGamma(); + + void UpdatePalette(); + void GetFlashedPalette (PalEntry pal[256]); + PalEntry *GetPalette (); + bool SetFlash(PalEntry rgb, int amount); + void GetFlash(PalEntry &rgb, int &amount); + int GetPageCount(); + bool Begin2D(bool copy3d); + void GameRestart(); + + // Retrieves a buffer containing image data for a screenshot. + // Hint: Pitch can be negative for upside-down images, in which case buffer + // points to the last row in the buffer, which will be the first row output. + virtual void GetScreenshotBuffer(const BYTE *&buffer, int &pitch, ESSType &color_type); + + // Releases the screenshot buffer. + virtual void ReleaseScreenshotBuffer(); + + // 2D drawing + void DrawTextureParms(FTexture *img, DrawParms &parms); + void DrawLine(int x1, int y1, int x2, int y2, int palcolor, uint32 color); + void DrawPixel(int x1, int y1, int palcolor, uint32 color); + void Clear(int left, int top, int right, int bottom, int palcolor, uint32 color); + void Dim(PalEntry color=0); + void Dim (PalEntry color, float damount, int x1, int y1, int w, int h); + void FlatFill (int left, int top, int right, int bottom, FTexture *src, bool local_origin=false); + + void FillSimplePoly(FTexture *tex, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel, int bottomclip); + + FNativePalette *CreatePalette(FRemapTable *remap); + + bool WipeStartScreen(int type); + void WipeEndScreen(); + bool WipeDo(int ticks); + void WipeCleanup(); + void Swap(); + bool Is8BitMode() { return false; } + bool IsHWGammaActive() const { return HWGammaActive; } + +private: + PalEntry Flash; + + // Texture creation info + int cm; + int translation; + bool iscomplex; + bool needsetgamma; + bool swapped; + + PalEntry SourcePalette[256]; + BYTE *ScreenshotBuffer; + + class Wiper + { + + protected: + FSimpleVertexBuffer *mVertexBuf; + + void MakeVBO(OpenGLFrameBuffer *fb); + + public: + Wiper(); + virtual ~Wiper(); + virtual bool Run(int ticks, OpenGLFrameBuffer *fb) = 0; + }; + + class Wiper_Melt; friend class Wiper_Melt; + class Wiper_Burn; friend class Wiper_Burn; + class Wiper_Crossfade; friend class Wiper_Crossfade; + + Wiper *ScreenWipe; + FHardwareTexture *wipestartscreen; + FHardwareTexture *wipeendscreen; + + bool HWGammaActive = false; + + std::shared_ptr mDebug; + +public: + AActor * LastCamera; + int palette_brightness; +}; + + +#endif //__GL_FRAMEBUFFER diff --git a/src/gl/system/gl_interface.cpp b/src/gl/system/gl_interface.cpp new file mode 100644 index 000000000..b0bc46ab2 --- /dev/null +++ b/src/gl/system/gl_interface.cpp @@ -0,0 +1,338 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** r_opengl.cpp +** +** OpenGL system interface +** +*/ + +#include "gl/system/gl_system.h" +#include "tarray.h" +#include "doomtype.h" +#include "m_argv.h" +#include "zstring.h" +#include "version.h" +#include "i_system.h" +#include "v_text.h" +#include "r_data/r_translate.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" + +void gl_PatchMenu(); +static TArray m_Extensions; +RenderContext gl; + +//========================================================================== +// +// +// +//========================================================================== + +static void CollectExtensions() +{ + const char *extension; + + int max = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &max); + + if (0 == max) + { + // Try old method to collect extensions + const char *supported = (char *)glGetString(GL_EXTENSIONS); + + if (nullptr != supported) + { + char *extensions = new char[strlen(supported) + 1]; + strcpy(extensions, supported); + + char *extension = strtok(extensions, " "); + + while (extension) + { + m_Extensions.Push(FString(extension)); + extension = strtok(nullptr, " "); + } + + delete [] extensions; + } + } + else + { + // Use modern method to collect extensions + for (int i = 0; i < max; i++) + { + extension = (const char*)glGetStringi(GL_EXTENSIONS, i); + m_Extensions.Push(FString(extension)); + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +static bool CheckExtension(const char *ext) +{ + for (unsigned int i = 0; i < m_Extensions.Size(); ++i) + { + if (m_Extensions[i].CompareNoCase(ext) == 0) return true; + } + + return false; +} + + + +//========================================================================== +// +// +// +//========================================================================== + +static void InitContext() +{ + gl.flags=0; +} + +//========================================================================== +// +// +// +//========================================================================== + +#define FUDGE_FUNC(name, ext) if (_ptrc_##name == NULL) _ptrc_##name = _ptrc_##name##ext; + + +void gl_LoadExtensions() +{ + InitContext(); + CollectExtensions(); + + const char *version = Args->CheckValue("-glversion"); + const char *glversion = (const char*)glGetString(GL_VERSION); + + if (version == NULL) + { + version = glversion; + } + else + { + double v1 = strtod(version, NULL); + double v2 = strtod(glversion, NULL); + if (v2 < v1) version = glversion; + else Printf("Emulating OpenGL v %s\n", version); + } + + float gl_version = (float)strtod(version, NULL) + 0.01f; + + // Don't even start if it's lower than 2.0 or no framebuffers are available (The framebuffer extension is needed for glGenerateMipmapsEXT!) + if ((gl_version < 2.0f || !CheckExtension("GL_EXT_framebuffer_object")) && gl_version < 3.0f) + { + I_FatalError("Unsupported OpenGL version.\nAt least OpenGL 2.0 with framebuffer support is required to run " GAMENAME ".\n"); + } + + // add 0.01 to account for roundoff errors making the number a tad smaller than the actual version + gl.glslversion = strtod((char*)glGetString(GL_SHADING_LANGUAGE_VERSION), NULL) + 0.01f; + + gl.vendorstring = (char*)glGetString(GL_VENDOR); + + // first test for optional features + if (CheckExtension("GL_ARB_texture_compression")) gl.flags |= RFL_TEXTURE_COMPRESSION; + if (CheckExtension("GL_EXT_texture_compression_s3tc")) gl.flags |= RFL_TEXTURE_COMPRESSION_S3TC; + + if ((gl_version >= 3.3f || CheckExtension("GL_ARB_sampler_objects")) && !Args->CheckParm("-nosampler")) + { + gl.flags |= RFL_SAMPLER_OBJECTS; + } + + // The minimum requirement for the modern render path are GL 3.0 + uniform buffers + if (gl_version < 3.0f || (gl_version < 3.1f && !CheckExtension("GL_ARB_uniform_buffer_object"))) + { + gl.legacyMode = true; + gl.lightmethod = LM_LEGACY; + gl.buffermethod = BM_LEGACY; + gl.glslversion = 0; + gl.flags |= RFL_NO_CLIP_PLANES; + } + else + { + gl.legacyMode = false; + gl.lightmethod = LM_DEFERRED; + gl.buffermethod = BM_DEFERRED; + if (gl_version < 4.f) + { +#ifdef _WIN32 + if (strstr(gl.vendorstring, "ATI Tech")) + { + gl.flags |= RFL_NO_CLIP_PLANES; // gl_ClipDistance is horribly broken on ATI GL3 drivers for Windows. + } +#endif + } + else if (gl_version < 4.5f) + { + // don't use GL 4.x features when running a GL 3.x context. + if (CheckExtension("GL_ARB_buffer_storage")) + { + // work around a problem with older AMD drivers: Their implementation of shader storage buffer objects is piss-poor and does not match uniform buffers even closely. + // Recent drivers, GL 4.4 don't have this problem, these can easily be recognized by also supporting the GL_ARB_buffer_storage extension. + if (CheckExtension("GL_ARB_shader_storage_buffer_object")) + { + // Shader storage buffer objects are broken on current Intel drivers. + if (strstr(gl.vendorstring, "Intel") == NULL) + { + gl.flags |= RFL_SHADER_STORAGE_BUFFER; + } + } + gl.flags |= RFL_BUFFER_STORAGE; + gl.lightmethod = LM_DIRECT; + gl.buffermethod = BM_PERSISTENT; + } + } + else + { + // Assume that everything works without problems on GL 4.5 drivers where these things are core features. + gl.flags |= RFL_SHADER_STORAGE_BUFFER | RFL_BUFFER_STORAGE; + gl.lightmethod = LM_DIRECT; + gl.buffermethod = BM_PERSISTENT; + } + + if (gl_version >= 4.3f || CheckExtension("GL_ARB_invalidate_subdata")) gl.flags |= RFL_INVALIDATE_BUFFER; + if (gl_version >= 4.3f || CheckExtension("GL_KHR_debug")) gl.flags |= RFL_DEBUG; + + const char *lm = Args->CheckValue("-lightmethod"); + if (lm != NULL) + { + if (!stricmp(lm, "deferred") && gl.lightmethod == LM_DIRECT) gl.lightmethod = LM_DEFERRED; + } + + lm = Args->CheckValue("-buffermethod"); + if (lm != NULL) + { + if (!stricmp(lm, "deferred") && gl.buffermethod == BM_PERSISTENT) gl.buffermethod = BM_DEFERRED; + } + } + + int v; + + if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER)) + { + glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &v); + gl.maxuniforms = v; + glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v); + gl.maxuniformblock = v; + glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v); + gl.uniformblockalignment = v; + } + else + { + gl.maxuniforms = 0; + gl.maxuniformblock = 0; + gl.uniformblockalignment = 0; + } + + + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl.max_texturesize); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + if (gl.legacyMode) + { + // fudge a bit with the framebuffer stuff to avoid redundancies in the main code. Some of the older cards do not have the ARB stuff but the calls are nearly identical. + FUDGE_FUNC(glGenerateMipmap, EXT); + FUDGE_FUNC(glGenFramebuffers, EXT); + FUDGE_FUNC(glBindFramebuffer, EXT); + FUDGE_FUNC(glDeleteFramebuffers, EXT); + FUDGE_FUNC(glFramebufferTexture2D, EXT); + FUDGE_FUNC(glGenerateMipmap, EXT); + FUDGE_FUNC(glGenFramebuffers, EXT); + FUDGE_FUNC(glBindFramebuffer, EXT); + FUDGE_FUNC(glDeleteFramebuffers, EXT); + FUDGE_FUNC(glFramebufferTexture2D, EXT); + FUDGE_FUNC(glFramebufferRenderbuffer, EXT); + FUDGE_FUNC(glGenRenderbuffers, EXT); + FUDGE_FUNC(glDeleteRenderbuffers, EXT); + FUDGE_FUNC(glRenderbufferStorage, EXT); + FUDGE_FUNC(glBindRenderbuffer, EXT); + FUDGE_FUNC(glCheckFramebufferStatus, EXT); + gl_PatchMenu(); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void gl_PrintStartupLog() +{ + int v = 0; + if (!gl.legacyMode) glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &v); + + Printf ("GL_VENDOR: %s\n", glGetString(GL_VENDOR)); + Printf ("GL_RENDERER: %s\n", glGetString(GL_RENDERER)); + Printf ("GL_VERSION: %s (%s profile)\n", glGetString(GL_VERSION), (v & GL_CONTEXT_CORE_PROFILE_BIT)? "Core" : "Compatibility"); + Printf ("GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); + Printf ("GL_EXTENSIONS:"); + for (unsigned i = 0; i < m_Extensions.Size(); i++) + { + Printf(" %s", m_Extensions[i].GetChars()); + } + + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &v); + Printf("\nMax. texture size: %d\n", v); + glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &v); + Printf ("Max. texture units: %d\n", v); + glGetIntegerv(GL_MAX_VARYING_FLOATS, &v); + Printf ("Max. varying: %d\n", v); + + if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER)) + { + glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v); + Printf ("Max. uniform block size: %d\n", v); + glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v); + Printf ("Uniform block alignment: %d\n", v); + } + + if (gl.flags & RFL_SHADER_STORAGE_BUFFER) + { + glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &v); + Printf("Max. combined shader storage blocks: %d\n", v); + glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &v); + Printf("Max. vertex shader storage blocks: %d\n", v); + } + + // For shader-less, the special alphatexture translation must be changed to actually set the alpha, because it won't get translated by a shader. + if (gl.legacyMode) + { + FRemapTable *remap = translationtables[TRANSLATION_Standard][8]; + for (int i = 0; i < 256; i++) + { + remap->Remap[i] = i; + remap->Palette[i] = PalEntry(i, 255, 255, 255); + } + } + +} + diff --git a/src/gl/system/gl_interface.h b/src/gl/system/gl_interface.h new file mode 100644 index 000000000..edaec58c0 --- /dev/null +++ b/src/gl/system/gl_interface.h @@ -0,0 +1,79 @@ +#ifndef R_RENDER +#define R_RENDER + +#include "basictypes.h" + +enum GLCompat +{ + CMPT_GL2, + CMPT_GL2_SHADER, + CMPT_GL3, + CMPT_GL4 +}; + +enum RenderFlags +{ + // [BB] Added texture compression flags. + RFL_TEXTURE_COMPRESSION=1, + RFL_TEXTURE_COMPRESSION_S3TC=2, + + RFL_SHADER_STORAGE_BUFFER = 4, + RFL_BUFFER_STORAGE = 8, + RFL_SAMPLER_OBJECTS = 16, + + RFL_NO_CLIP_PLANES = 32, + + RFL_INVALIDATE_BUFFER = 64, + RFL_DEBUG = 128 +}; + +enum TexMode +{ + TM_MODULATE = 0, // (r, g, b, a) + TM_MASK, // (1, 1, 1, a) + TM_OPAQUE, // (r, g, b, 1) + TM_INVERSE, // (1-r, 1-g, 1-b, a) + TM_REDTOALPHA, // (1, 1, 1, r) + TM_CLAMPY, // (r, g, b, (t >= 0.0 && t <= 1.0)? a:0) + + TM_INVERTOPAQUE, // used by GL 2.x fallback code. +}; + +enum ELightMethod +{ + LM_LEGACY = 0, // placeholder for legacy mode (textured lights), should not be checked anywhere in the code! + LM_DEFERRED = 1, // calculate lights up front in a separate pass + LM_DIRECT = 2, // calculate lights on the fly along with the render data +}; + +enum EBufferMethod +{ + BM_LEGACY = 0, // placeholder for legacy mode (client arrays), should not be checked anywhere in the code! + BM_DEFERRED = 1, // use a temporarily mapped buffer, for GL 3.x core profile + BM_PERSISTENT = 2 // use a persistently mapped buffer +}; + + +struct RenderContext +{ + unsigned int flags; + unsigned int maxuniforms; + unsigned int maxuniformblock; + unsigned int uniformblockalignment; + int lightmethod; + int buffermethod; + float glslversion; + int max_texturesize; + char * vendorstring; + bool legacyMode; + + int MaxLights() const + { + return maxuniforms>=2048? 128:64; + } +}; + +extern RenderContext gl; + +#endif + diff --git a/src/gl/system/gl_load.c b/src/gl/system/gl_load.c new file mode 100644 index 000000000..a32eb226f --- /dev/null +++ b/src/gl/system/gl_load.c @@ -0,0 +1,2564 @@ +#include +#include +#include +#include "gl_load.h" + +#if defined(__APPLE__) +#include + +static void* AppleGLGetProcAddress (const char *name) +{ + static void* image = NULL; + + if (NULL == image) + image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY); + + return (image ? dlsym(image, name) : NULL); +} +#endif /* __APPLE__ */ + +#if defined(__sgi) || defined (__sun) +#include +#include + +static void* SunGetProcAddress (const GLubyte* name) +{ + static void* h = NULL; + static void* gpa; + + if (h == NULL) + { + if ((h = dlopen(NULL, RTLD_LAZY | RTLD_LOCAL)) == NULL) return NULL; + gpa = dlsym(h, "glXGetProcAddress"); + } + + if (gpa != NULL) + return ((void*(*)(const GLubyte*))gpa)(name); + else + return dlsym(h, (const char*)name); +} +#endif /* __sgi || __sun */ + +#if defined(_WIN32) + +#ifdef _MSC_VER +// disable inlining here because it creates an incredible amount of bloat in this file. +#pragma inline_depth(0) +#pragma warning(disable: 4055) +#pragma warning(disable: 4054) +#pragma warning(disable: 4996) +#endif + +static int TestPointer(const PROC pTest) +{ + ptrdiff_t iTest; + if(!pTest) return 0; + iTest = (ptrdiff_t)pTest; + + if(iTest == 1 || iTest == 2 || iTest == 3 || iTest == -1) return 0; + + return 1; +} + +static PROC WinGetProcAddress(const char *name) +{ + HMODULE glMod = NULL; + PROC pFunc = wglGetProcAddress((LPCSTR)name); + if(TestPointer(pFunc)) + { + return pFunc; + } + glMod = GetModuleHandleA("OpenGL32.dll"); + return (PROC)GetProcAddress(glMod, (LPCSTR)name); +} + +#define IntGetProcAddress(name) WinGetProcAddress(name) +#else + #if defined(__APPLE__) + #define IntGetProcAddress(name) AppleGLGetProcAddress(name) + #else + #if defined(__sgi) || defined(__sun) + #define IntGetProcAddress(name) SunGetProcAddress(name) + #else /* GLX */ + #include + + #define IntGetProcAddress(name) (*glXGetProcAddressARB)((const GLubyte*)name) + #endif + #endif +#endif + +int ogl_ext_APPLE_client_storage = ogl_LOAD_FAILED; +int ogl_ext_ARB_buffer_storage = ogl_LOAD_FAILED; +int ogl_ext_ARB_shader_storage_buffer_object = ogl_LOAD_FAILED; +int ogl_ext_ARB_texture_compression = ogl_LOAD_FAILED; +int ogl_ext_ARB_texture_rectangle = ogl_LOAD_FAILED; +int ogl_ext_EXT_framebuffer_object = ogl_LOAD_FAILED; +int ogl_ext_EXT_texture_compression_s3tc = ogl_LOAD_FAILED; +int ogl_ext_EXT_texture_filter_anisotropic = ogl_LOAD_FAILED; +int ogl_ext_EXT_texture_sRGB = ogl_LOAD_FAILED; +int ogl_ext_KHR_debug = ogl_LOAD_FAILED; +int ogl_ext_ARB_invalidate_subdata = ogl_LOAD_FAILED; + +void (CODEGEN_FUNCPTR *_ptrc_glBufferStorage)(GLenum target, GLsizeiptr size, const void * data, GLbitfield flags) = NULL; + +static int Load_ARB_buffer_storage(void) +{ + int numFailed = 0; + _ptrc_glBufferStorage = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizeiptr, const void *, GLbitfield))IntGetProcAddress("glBufferStorage"); + if(!_ptrc_glBufferStorage) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glShaderStorageBlockBinding)(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding) = NULL; + +static int Load_ARB_shader_storage_buffer_object(void) +{ + int numFailed = 0; + _ptrc_glShaderStorageBlockBinding = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint))IntGetProcAddress("glShaderStorageBlockBinding"); + if(!_ptrc_glShaderStorageBlockBinding) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetCompressedTexImageARB)(GLenum target, GLint level, void * img) = NULL; + +static int Load_ARB_texture_compression(void) +{ + int numFailed = 0; + _ptrc_glCompressedTexImage1DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage1DARB"); + if(!_ptrc_glCompressedTexImage1DARB) numFailed++; + _ptrc_glCompressedTexImage2DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage2DARB"); + if(!_ptrc_glCompressedTexImage2DARB) numFailed++; + _ptrc_glCompressedTexImage3DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage3DARB"); + if(!_ptrc_glCompressedTexImage3DARB) numFailed++; + _ptrc_glCompressedTexSubImage1DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage1DARB"); + if(!_ptrc_glCompressedTexSubImage1DARB) numFailed++; + _ptrc_glCompressedTexSubImage2DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage2DARB"); + if(!_ptrc_glCompressedTexSubImage2DARB) numFailed++; + _ptrc_glCompressedTexSubImage3DARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage3DARB"); + if(!_ptrc_glCompressedTexSubImage3DARB) numFailed++; + _ptrc_glGetCompressedTexImageARB = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, void *))IntGetProcAddress("glGetCompressedTexImageARB"); + if(!_ptrc_glGetCompressedTexImageARB) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glBindFramebufferEXT)(GLenum target, GLuint framebuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindRenderbufferEXT)(GLenum target, GLuint renderbuffer) = NULL; +GLenum (CODEGEN_FUNCPTR *_ptrc_glCheckFramebufferStatusEXT)(GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteFramebuffersEXT)(GLsizei n, const GLuint * framebuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteRenderbuffersEXT)(GLsizei n, const GLuint * renderbuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferRenderbufferEXT)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture1DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture2DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture3DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenFramebuffersEXT)(GLsizei n, GLuint * framebuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenRenderbuffersEXT)(GLsizei n, GLuint * renderbuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenerateMipmapEXT)(GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetFramebufferAttachmentParameterivEXT)(GLenum target, GLenum attachment, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetRenderbufferParameterivEXT)(GLenum target, GLenum pname, GLint * params) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsFramebufferEXT)(GLuint framebuffer) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsRenderbufferEXT)(GLuint renderbuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorageEXT)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) = NULL; + +static int Load_EXT_framebuffer_object(void) +{ + int numFailed = 0; + _ptrc_glBindFramebufferEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindFramebufferEXT"); + if(!_ptrc_glBindFramebufferEXT) numFailed++; + _ptrc_glBindRenderbufferEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindRenderbufferEXT"); + if(!_ptrc_glBindRenderbufferEXT) numFailed++; + _ptrc_glCheckFramebufferStatusEXT = (GLenum (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glCheckFramebufferStatusEXT"); + if(!_ptrc_glCheckFramebufferStatusEXT) numFailed++; + _ptrc_glDeleteFramebuffersEXT = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteFramebuffersEXT"); + if(!_ptrc_glDeleteFramebuffersEXT) numFailed++; + _ptrc_glDeleteRenderbuffersEXT = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteRenderbuffersEXT"); + if(!_ptrc_glDeleteRenderbuffersEXT) numFailed++; + _ptrc_glFramebufferRenderbufferEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint))IntGetProcAddress("glFramebufferRenderbufferEXT"); + if(!_ptrc_glFramebufferRenderbufferEXT) numFailed++; + _ptrc_glFramebufferTexture1DEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint))IntGetProcAddress("glFramebufferTexture1DEXT"); + if(!_ptrc_glFramebufferTexture1DEXT) numFailed++; + _ptrc_glFramebufferTexture2DEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint))IntGetProcAddress("glFramebufferTexture2DEXT"); + if(!_ptrc_glFramebufferTexture2DEXT) numFailed++; + _ptrc_glFramebufferTexture3DEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint, GLint))IntGetProcAddress("glFramebufferTexture3DEXT"); + if(!_ptrc_glFramebufferTexture3DEXT) numFailed++; + _ptrc_glGenFramebuffersEXT = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenFramebuffersEXT"); + if(!_ptrc_glGenFramebuffersEXT) numFailed++; + _ptrc_glGenRenderbuffersEXT = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenRenderbuffersEXT"); + if(!_ptrc_glGenRenderbuffersEXT) numFailed++; + _ptrc_glGenerateMipmapEXT = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glGenerateMipmapEXT"); + if(!_ptrc_glGenerateMipmapEXT) numFailed++; + _ptrc_glGetFramebufferAttachmentParameterivEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLint *))IntGetProcAddress("glGetFramebufferAttachmentParameterivEXT"); + if(!_ptrc_glGetFramebufferAttachmentParameterivEXT) numFailed++; + _ptrc_glGetRenderbufferParameterivEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetRenderbufferParameterivEXT"); + if(!_ptrc_glGetRenderbufferParameterivEXT) numFailed++; + _ptrc_glIsFramebufferEXT = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsFramebufferEXT"); + if(!_ptrc_glIsFramebufferEXT) numFailed++; + _ptrc_glIsRenderbufferEXT = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsRenderbufferEXT"); + if(!_ptrc_glIsRenderbufferEXT) numFailed++; + _ptrc_glRenderbufferStorageEXT = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLsizei, GLsizei))IntGetProcAddress("glRenderbufferStorageEXT"); + if(!_ptrc_glRenderbufferStorageEXT) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageCallback)(GLDEBUGPROC callback, const void * userParam) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageControl)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageInsert)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf) = NULL; +GLuint (CODEGEN_FUNCPTR *_ptrc_glGetDebugMessageLog)(GLuint count, GLsizei bufSize, GLenum * sources, GLenum * types, GLuint * ids, GLenum * severities, GLsizei * lengths, GLchar * messageLog) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetObjectLabel)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei * length, GLchar * label) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetObjectPtrLabel)(const void * ptr, GLsizei bufSize, GLsizei * length, GLchar * label) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetPointerv)(GLenum pname, void ** params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glObjectLabel)(GLenum identifier, GLuint name, GLsizei length, const GLchar * label) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glObjectPtrLabel)(const void * ptr, GLsizei length, const GLchar * label) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPopDebugGroup)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPushDebugGroup)(GLenum source, GLuint id, GLsizei length, const GLchar * message) = NULL; + +static int Load_KHR_debug(void) +{ + int numFailed = 0; + _ptrc_glDebugMessageCallback = (void (CODEGEN_FUNCPTR *)(GLDEBUGPROC, const void *))IntGetProcAddress("glDebugMessageCallback"); + if(!_ptrc_glDebugMessageCallback) numFailed++; + _ptrc_glDebugMessageControl = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLsizei, const GLuint *, GLboolean))IntGetProcAddress("glDebugMessageControl"); + if(!_ptrc_glDebugMessageControl) numFailed++; + _ptrc_glDebugMessageInsert = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLuint, GLenum, GLsizei, const GLchar *))IntGetProcAddress("glDebugMessageInsert"); + if(!_ptrc_glDebugMessageInsert) numFailed++; + _ptrc_glGetDebugMessageLog = (GLuint (CODEGEN_FUNCPTR *)(GLuint, GLsizei, GLenum *, GLenum *, GLuint *, GLenum *, GLsizei *, GLchar *))IntGetProcAddress("glGetDebugMessageLog"); + if(!_ptrc_glGetDebugMessageLog) numFailed++; + _ptrc_glGetObjectLabel = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetObjectLabel"); + if(!_ptrc_glGetObjectLabel) numFailed++; + _ptrc_glGetObjectPtrLabel = (void (CODEGEN_FUNCPTR *)(const void *, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetObjectPtrLabel"); + if(!_ptrc_glGetObjectPtrLabel) numFailed++; + _ptrc_glGetPointerv = (void (CODEGEN_FUNCPTR *)(GLenum, void **))IntGetProcAddress("glGetPointerv"); + if(!_ptrc_glGetPointerv) numFailed++; + _ptrc_glObjectLabel = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLsizei, const GLchar *))IntGetProcAddress("glObjectLabel"); + if(!_ptrc_glObjectLabel) numFailed++; + _ptrc_glObjectPtrLabel = (void (CODEGEN_FUNCPTR *)(const void *, GLsizei, const GLchar *))IntGetProcAddress("glObjectPtrLabel"); + if(!_ptrc_glObjectPtrLabel) numFailed++; + _ptrc_glPopDebugGroup = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPopDebugGroup"); + if(!_ptrc_glPopDebugGroup) numFailed++; + _ptrc_glPushDebugGroup = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLsizei, const GLchar *))IntGetProcAddress("glPushDebugGroup"); + if(!_ptrc_glPushDebugGroup) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateBufferData)(GLuint buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateBufferSubData)(GLuint buffer, GLintptr offset, GLsizeiptr length) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateSubFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateTexImage)(GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInvalidateTexSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth) = NULL; + +static int Load_ARB_invalidate_subdata(void) +{ + int numFailed = 0; + _ptrc_glInvalidateBufferData = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glInvalidateBufferData"); + if(!_ptrc_glInvalidateBufferData) numFailed++; + _ptrc_glInvalidateBufferSubData = (void (CODEGEN_FUNCPTR *)(GLuint, GLintptr, GLsizeiptr))IntGetProcAddress("glInvalidateBufferSubData"); + if(!_ptrc_glInvalidateBufferSubData) numFailed++; + _ptrc_glInvalidateFramebuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const GLenum *))IntGetProcAddress("glInvalidateFramebuffer"); + if(!_ptrc_glInvalidateFramebuffer) numFailed++; + _ptrc_glInvalidateSubFramebuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei))IntGetProcAddress("glInvalidateSubFramebuffer"); + if(!_ptrc_glInvalidateSubFramebuffer) numFailed++; + _ptrc_glInvalidateTexImage = (void (CODEGEN_FUNCPTR *)(GLuint, GLint))IntGetProcAddress("glInvalidateTexImage"); + if(!_ptrc_glInvalidateTexImage) numFailed++; + _ptrc_glInvalidateTexSubImage = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei))IntGetProcAddress("glInvalidateTexSubImage"); + if(!_ptrc_glInvalidateTexSubImage) numFailed++; + return numFailed; +} + +void (CODEGEN_FUNCPTR *_ptrc_glAccum)(GLenum op, GLfloat value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glAlphaFunc)(GLenum func, GLfloat ref) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBegin)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBitmap)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte * bitmap) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBlendFunc)(GLenum sfactor, GLenum dfactor) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCallList)(GLuint list) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCallLists)(GLsizei n, GLenum type, const void * lists) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClear)(GLbitfield mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearAccum)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearDepth)(GLdouble depth) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearIndex)(GLfloat c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearStencil)(GLint s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClipPlane)(GLenum plane, const GLdouble * equation) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3b)(GLbyte red, GLbyte green, GLbyte blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3bv)(const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3d)(GLdouble red, GLdouble green, GLdouble blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3f)(GLfloat red, GLfloat green, GLfloat blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3i)(GLint red, GLint green, GLint blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3s)(GLshort red, GLshort green, GLshort blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3ub)(GLubyte red, GLubyte green, GLubyte blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3ubv)(const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3ui)(GLuint red, GLuint green, GLuint blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3uiv)(const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3us)(GLushort red, GLushort green, GLushort blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor3usv)(const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4b)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4bv)(const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4d)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4i)(GLint red, GLint green, GLint blue, GLint alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4s)(GLshort red, GLshort green, GLshort blue, GLshort alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4ub)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4ubv)(const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4ui)(GLuint red, GLuint green, GLuint blue, GLuint alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4uiv)(const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4us)(GLushort red, GLushort green, GLushort blue, GLushort alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColor4usv)(const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColorMaterial)(GLenum face, GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCopyPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCullFace)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteLists)(GLuint list, GLsizei range) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDepthFunc)(GLenum func) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDepthMask)(GLboolean flag) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDepthRange)(GLdouble ren_near, GLdouble ren_far) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDisable)(GLenum cap) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawBuffer)(GLenum buf) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawPixels)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlag)(GLboolean flag) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlagv)(const GLboolean * flag) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEnable)(GLenum cap) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEnd)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEndList)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1d)(GLdouble u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1dv)(const GLdouble * u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1f)(GLfloat u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1fv)(const GLfloat * u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2d)(GLdouble u, GLdouble v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2dv)(const GLdouble * u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2f)(GLfloat u, GLfloat v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2fv)(const GLfloat * u) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalMesh1)(GLenum mode, GLint i1, GLint i2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalMesh2)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalPoint1)(GLint i) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEvalPoint2)(GLint i, GLint j) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFeedbackBuffer)(GLsizei size, GLenum type, GLfloat * buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFinish)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFlush)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogf)(GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogfv)(GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogi)(GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogiv)(GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFrontFace)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFrustum)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) = NULL; +GLuint (CODEGEN_FUNCPTR *_ptrc_glGenLists)(GLsizei range) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBooleanv)(GLenum pname, GLboolean * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetClipPlane)(GLenum plane, GLdouble * equation) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetDoublev)(GLenum pname, GLdouble * data) = NULL; +GLenum (CODEGEN_FUNCPTR *_ptrc_glGetError)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetFloatv)(GLenum pname, GLfloat * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetIntegerv)(GLenum pname, GLint * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetLightfv)(GLenum light, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetLightiv)(GLenum light, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMapdv)(GLenum target, GLenum query, GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMapfv)(GLenum target, GLenum query, GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMapiv)(GLenum target, GLenum query, GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMaterialfv)(GLenum face, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMaterialiv)(GLenum face, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapfv)(GLenum map, GLfloat * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapuiv)(GLenum map, GLuint * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapusv)(GLenum map, GLushort * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetPolygonStipple)(GLubyte * mask) = NULL; +const GLubyte * (CODEGEN_FUNCPTR *_ptrc_glGetString)(GLenum name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexEnvfv)(GLenum target, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexEnviv)(GLenum target, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexGendv)(GLenum coord, GLenum pname, GLdouble * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexGenfv)(GLenum coord, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexGeniv)(GLenum coord, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameteriv)(GLenum target, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glHint)(GLenum target, GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexMask)(GLuint mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexd)(GLdouble c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexdv)(const GLdouble * c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexf)(GLfloat c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexfv)(const GLfloat * c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexi)(GLint c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexiv)(const GLint * c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexs)(GLshort c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexsv)(const GLshort * c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInitNames)(void) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsEnabled)(GLenum cap) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsList)(GLuint list) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightModelf)(GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightModelfv)(GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightModeli)(GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightModeliv)(GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightf)(GLenum light, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightfv)(GLenum light, GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLighti)(GLenum light, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLightiv)(GLenum light, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLineStipple)(GLint factor, GLushort pattern) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLineWidth)(GLfloat width) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glListBase)(GLuint base) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadIdentity)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadMatrixd)(const GLdouble * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadMatrixf)(const GLfloat * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadName)(GLuint name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLogicOp)(GLenum opcode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMap1d)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble * points) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMap1f)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat * points) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMap2d)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble * points) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMap2f)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat * points) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMapGrid1d)(GLint un, GLdouble u1, GLdouble u2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMapGrid1f)(GLint un, GLfloat u1, GLfloat u2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMapGrid2d)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMapGrid2f)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMaterialf)(GLenum face, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMaterialfv)(GLenum face, GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMateriali)(GLenum face, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMaterialiv)(GLenum face, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMatrixMode)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultMatrixd)(const GLdouble * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultMatrixf)(const GLfloat * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNewList)(GLuint list, GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3b)(GLbyte nx, GLbyte ny, GLbyte nz) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3bv)(const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3d)(GLdouble nx, GLdouble ny, GLdouble nz) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3f)(GLfloat nx, GLfloat ny, GLfloat nz) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3i)(GLint nx, GLint ny, GLint nz) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3s)(GLshort nx, GLshort ny, GLshort nz) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormal3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glOrtho)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPassThrough)(GLfloat token) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelMapfv)(GLenum map, GLsizei mapsize, const GLfloat * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelMapuiv)(GLenum map, GLsizei mapsize, const GLuint * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelMapusv)(GLenum map, GLsizei mapsize, const GLushort * values) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelStoref)(GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelStorei)(GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelTransferf)(GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelTransferi)(GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPixelZoom)(GLfloat xfactor, GLfloat yfactor) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPointSize)(GLfloat size) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPolygonMode)(GLenum face, GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPolygonStipple)(const GLubyte * mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPopAttrib)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPopMatrix)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPopName)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPushAttrib)(GLbitfield mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPushMatrix)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPushName)(GLuint name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2d)(GLdouble x, GLdouble y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2f)(GLfloat x, GLfloat y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2i)(GLint x, GLint y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2s)(GLshort x, GLshort y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3d)(GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3f)(GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3i)(GLint x, GLint y, GLint z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3s)(GLshort x, GLshort y, GLshort z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4i)(GLint x, GLint y, GLint z, GLint w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4s)(GLshort x, GLshort y, GLshort z, GLshort w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glReadBuffer)(GLenum src) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectd)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectdv)(const GLdouble * v1, const GLdouble * v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectf)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectfv)(const GLfloat * v1, const GLfloat * v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRecti)(GLint x1, GLint y1, GLint x2, GLint y2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectiv)(const GLint * v1, const GLint * v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRects)(GLshort x1, GLshort y1, GLshort x2, GLshort y2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRectsv)(const GLshort * v1, const GLshort * v2) = NULL; +GLint (CODEGEN_FUNCPTR *_ptrc_glRenderMode)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRotated)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRotatef)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glScaled)(GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glScalef)(GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSelectBuffer)(GLsizei size, GLuint * buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glShadeModel)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilFunc)(GLenum func, GLint ref, GLuint mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilMask)(GLuint mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1d)(GLdouble s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1f)(GLfloat s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1i)(GLint s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1s)(GLshort s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2d)(GLdouble s, GLdouble t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2f)(GLfloat s, GLfloat t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2i)(GLint s, GLint t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2s)(GLshort s, GLshort t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3d)(GLdouble s, GLdouble t, GLdouble r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3f)(GLfloat s, GLfloat t, GLfloat r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3i)(GLint s, GLint t, GLint r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3s)(GLshort s, GLshort t, GLshort r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4d)(GLdouble s, GLdouble t, GLdouble r, GLdouble q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4f)(GLfloat s, GLfloat t, GLfloat r, GLfloat q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4i)(GLint s, GLint t, GLint r, GLint q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4s)(GLshort s, GLshort t, GLshort r, GLshort q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexEnvf)(GLenum target, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexEnvfv)(GLenum target, GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexEnvi)(GLenum target, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexEnviv)(GLenum target, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGend)(GLenum coord, GLenum pname, GLdouble param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGendv)(GLenum coord, GLenum pname, const GLdouble * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGenf)(GLenum coord, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGenfv)(GLenum coord, GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGeni)(GLenum coord, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexGeniv)(GLenum coord, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameterf)(GLenum target, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameteri)(GLenum target, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameteriv)(GLenum target, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTranslated)(GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTranslatef)(GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2d)(GLdouble x, GLdouble y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2f)(GLfloat x, GLfloat y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2i)(GLint x, GLint y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2s)(GLshort x, GLshort y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex2sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3d)(GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3f)(GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3i)(GLint x, GLint y, GLint z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3s)(GLshort x, GLshort y, GLshort z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4i)(GLint x, GLint y, GLint z, GLint w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4s)(GLshort x, GLshort y, GLshort z, GLshort w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertex4sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height) = NULL; + +GLboolean (CODEGEN_FUNCPTR *_ptrc_glAreTexturesResident)(GLsizei n, const GLuint * textures, GLboolean * residences) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glArrayElement)(GLint i) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindTexture)(GLenum target, GLuint texture) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColorPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCopyTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteTextures)(GLsizei n, const GLuint * textures) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDisableClientState)(GLenum ren_array) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawArrays)(GLenum mode, GLint first, GLsizei count) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawElements)(GLenum mode, GLsizei count, GLenum type, const void * indices) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlagPointer)(GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEnableClientState)(GLenum ren_array) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenTextures)(GLsizei n, GLuint * textures) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexPointer)(GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexub)(GLubyte c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glIndexubv)(const GLubyte * c) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glInterleavedArrays)(GLenum format, GLsizei stride, const void * pointer) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsTexture)(GLuint texture) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glNormalPointer)(GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPolygonOffset)(GLfloat factor, GLfloat units) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPopClientAttrib)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPrioritizeTextures)(GLsizei n, const GLuint * textures, const GLfloat * priorities) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPushClientAttrib)(GLbitfield mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexImage3D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glActiveTexture)(GLenum texture) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClientActiveTexture)(GLenum texture) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetCompressedTexImage)(GLenum target, GLint level, void * img) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadTransposeMatrixd)(const GLdouble * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLoadTransposeMatrixf)(const GLfloat * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultTransposeMatrixd)(const GLdouble * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultTransposeMatrixf)(const GLfloat * m) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1d)(GLenum target, GLdouble s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1dv)(GLenum target, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1f)(GLenum target, GLfloat s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1fv)(GLenum target, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1i)(GLenum target, GLint s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1iv)(GLenum target, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1s)(GLenum target, GLshort s) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1sv)(GLenum target, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2dv)(GLenum target, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2fv)(GLenum target, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2i)(GLenum target, GLint s, GLint t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2iv)(GLenum target, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2sv)(GLenum target, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3dv)(GLenum target, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3fv)(GLenum target, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3iv)(GLenum target, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3sv)(GLenum target, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4dv)(GLenum target, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4fv)(GLenum target, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4iv)(GLenum target, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4sv)(GLenum target, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSampleCoverage)(GLfloat value, GLboolean invert) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glBlendColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBlendEquation)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogCoordPointer)(GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogCoordd)(GLdouble coord) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogCoorddv)(const GLdouble * coord) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogCoordf)(GLfloat coord) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFogCoordfv)(const GLfloat * coord) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawArrays)(GLenum mode, const GLint * first, const GLsizei * count, GLsizei drawcount) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawElements)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPointParameterf)(GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPointParameterfv)(GLenum pname, const GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPointParameteri)(GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPointParameteriv)(GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3b)(GLbyte red, GLbyte green, GLbyte blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3bv)(const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3d)(GLdouble red, GLdouble green, GLdouble blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3f)(GLfloat red, GLfloat green, GLfloat blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3i)(GLint red, GLint green, GLint blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3s)(GLshort red, GLshort green, GLshort blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ub)(GLubyte red, GLubyte green, GLubyte blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ubv)(const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ui)(GLuint red, GLuint green, GLuint blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3uiv)(const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3us)(GLushort red, GLushort green, GLushort blue) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3usv)(const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColorPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2d)(GLdouble x, GLdouble y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2f)(GLfloat x, GLfloat y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2i)(GLint x, GLint y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2s)(GLshort x, GLshort y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2sv)(const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3d)(GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3dv)(const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3f)(GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3fv)(const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3i)(GLint x, GLint y, GLint z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3iv)(const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3s)(GLshort x, GLshort y, GLshort z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3sv)(const GLshort * v) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glBeginQuery)(GLenum target, GLuint id) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindBuffer)(GLenum target, GLuint buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBufferData)(GLenum target, GLsizeiptr size, const void * data, GLenum usage) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteBuffers)(GLsizei n, const GLuint * buffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteQueries)(GLsizei n, const GLuint * ids) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEndQuery)(GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenBuffers)(GLsizei n, GLuint * buffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenQueries)(GLsizei n, GLuint * ids) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBufferParameteriv)(GLenum target, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBufferPointerv)(GLenum target, GLenum pname, void ** params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, void * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectiv)(GLuint id, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectuiv)(GLuint id, GLenum pname, GLuint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetQueryiv)(GLenum target, GLenum pname, GLint * params) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsBuffer)(GLuint buffer) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsQuery)(GLuint id) = NULL; +void * (CODEGEN_FUNCPTR *_ptrc_glMapBuffer)(GLenum target, GLenum access) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glUnmapBuffer)(GLenum target) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glAttachShader)(GLuint program, GLuint shader) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindAttribLocation)(GLuint program, GLuint index, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBlendEquationSeparate)(GLenum modeRGB, GLenum modeAlpha) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glCompileShader)(GLuint shader) = NULL; +GLuint (CODEGEN_FUNCPTR *_ptrc_glCreateProgram)(void) = NULL; +GLuint (CODEGEN_FUNCPTR *_ptrc_glCreateShader)(GLenum type) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteProgram)(GLuint program) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteShader)(GLuint shader) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDetachShader)(GLuint program, GLuint shader) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDisableVertexAttribArray)(GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawBuffers)(GLsizei n, const GLenum * bufs) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEnableVertexAttribArray)(GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveAttrib)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniform)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetAttachedShaders)(GLuint program, GLsizei maxCount, GLsizei * count, GLuint * shaders) = NULL; +GLint (CODEGEN_FUNCPTR *_ptrc_glGetAttribLocation)(GLuint program, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetProgramInfoLog)(GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetProgramiv)(GLuint program, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetShaderInfoLog)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetShaderSource)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * source) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetShaderiv)(GLuint shader, GLenum pname, GLint * params) = NULL; +GLint (CODEGEN_FUNCPTR *_ptrc_glGetUniformLocation)(GLuint program, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetUniformfv)(GLuint program, GLint location, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetUniformiv)(GLuint program, GLint location, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribPointerv)(GLuint index, GLenum pname, void ** pointer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribdv)(GLuint index, GLenum pname, GLdouble * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribfv)(GLuint index, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribiv)(GLuint index, GLenum pname, GLint * params) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsProgram)(GLuint program) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsShader)(GLuint shader) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glLinkProgram)(GLuint program) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glShaderSource)(GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilFuncSeparate)(GLenum face, GLenum func, GLint ref, GLuint mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilMaskSeparate)(GLenum face, GLuint mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glStencilOpSeparate)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1f)(GLint location, GLfloat v0) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1fv)(GLint location, GLsizei count, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1i)(GLint location, GLint v0) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1iv)(GLint location, GLsizei count, const GLint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2f)(GLint location, GLfloat v0, GLfloat v1) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2fv)(GLint location, GLsizei count, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2i)(GLint location, GLint v0, GLint v1) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2iv)(GLint location, GLsizei count, const GLint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3fv)(GLint location, GLsizei count, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3i)(GLint location, GLint v0, GLint v1, GLint v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3iv)(GLint location, GLsizei count, const GLint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4fv)(GLint location, GLsizei count, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4i)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4iv)(GLint location, GLsizei count, const GLint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUseProgram)(GLuint program) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glValidateProgram)(GLuint program) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1d)(GLuint index, GLdouble x) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1dv)(GLuint index, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1f)(GLuint index, GLfloat x) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1fv)(GLuint index, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1s)(GLuint index, GLshort x) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1sv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2d)(GLuint index, GLdouble x, GLdouble y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2dv)(GLuint index, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2f)(GLuint index, GLfloat x, GLfloat y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2fv)(GLuint index, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2s)(GLuint index, GLshort x, GLshort y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2sv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3d)(GLuint index, GLdouble x, GLdouble y, GLdouble z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3dv)(GLuint index, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3f)(GLuint index, GLfloat x, GLfloat y, GLfloat z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3fv)(GLuint index, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3s)(GLuint index, GLshort x, GLshort y, GLshort z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3sv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nbv)(GLuint index, const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Niv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nsv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nub)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nubv)(GLuint index, const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nuiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nusv)(GLuint index, const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4bv)(GLuint index, const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4d)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4dv)(GLuint index, const GLdouble * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4f)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4fv)(GLuint index, const GLfloat * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4iv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4s)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4sv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4ubv)(GLuint index, const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4uiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4usv)(GLuint index, const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribPointer)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glBeginConditionalRender)(GLuint id, GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBeginTransformFeedback)(GLenum primitiveMode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindBufferBase)(GLenum target, GLuint index, GLuint buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindFragDataLocation)(GLuint program, GLuint color, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindFramebuffer)(GLenum target, GLuint framebuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindRenderbuffer)(GLenum target, GLuint renderbuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindVertexArray)(GLuint ren_array) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) = NULL; +GLenum (CODEGEN_FUNCPTR *_ptrc_glCheckFramebufferStatus)(GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClampColor)(GLenum target, GLenum clamp) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearBufferfi)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearBufferfv)(GLenum buffer, GLint drawbuffer, const GLfloat * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glClearBufferuiv)(GLenum buffer, GLint drawbuffer, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glColorMaski)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteFramebuffers)(GLsizei n, const GLuint * framebuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteRenderbuffers)(GLsizei n, const GLuint * renderbuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteVertexArrays)(GLsizei n, const GLuint * arrays) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDisablei)(GLenum target, GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEnablei)(GLenum target, GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEndConditionalRender)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glEndTransformFeedback)(void) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFlushMappedBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferRenderbuffer)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture1D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture2D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture3D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenFramebuffers)(GLsizei n, GLuint * framebuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenRenderbuffers)(GLsizei n, GLuint * renderbuffers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenVertexArrays)(GLsizei n, GLuint * arrays) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenerateMipmap)(GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBooleani_v)(GLenum target, GLuint index, GLboolean * data) = NULL; +GLint (CODEGEN_FUNCPTR *_ptrc_glGetFragDataLocation)(GLuint program, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetFramebufferAttachmentParameteriv)(GLenum target, GLenum attachment, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetIntegeri_v)(GLenum target, GLuint index, GLint * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetRenderbufferParameteriv)(GLenum target, GLenum pname, GLint * params) = NULL; +const GLubyte * (CODEGEN_FUNCPTR *_ptrc_glGetStringi)(GLenum name, GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterIiv)(GLenum target, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterIuiv)(GLenum target, GLenum pname, GLuint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetTransformFeedbackVarying)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLsizei * size, GLenum * type, GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetUniformuiv)(GLuint program, GLint location, GLuint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribIiv)(GLuint index, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribIuiv)(GLuint index, GLenum pname, GLuint * params) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsEnabledi)(GLenum target, GLuint index) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsFramebuffer)(GLuint framebuffer) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsRenderbuffer)(GLuint renderbuffer) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsVertexArray)(GLuint ren_array) = NULL; +void * (CODEGEN_FUNCPTR *_ptrc_glMapBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorage)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameterIiv)(GLenum target, GLenum pname, const GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexParameterIuiv)(GLenum target, GLenum pname, const GLuint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTransformFeedbackVaryings)(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1ui)(GLint location, GLuint v0) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform1uiv)(GLint location, GLsizei count, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2ui)(GLint location, GLuint v0, GLuint v1) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform2uiv)(GLint location, GLsizei count, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3ui)(GLint location, GLuint v0, GLuint v1, GLuint v2) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform3uiv)(GLint location, GLsizei count, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4ui)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniform4uiv)(GLint location, GLsizei count, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1i)(GLuint index, GLint x) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1iv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1ui)(GLuint index, GLuint x) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1uiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2i)(GLuint index, GLint x, GLint y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2iv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2ui)(GLuint index, GLuint x, GLuint y) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2uiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3i)(GLuint index, GLint x, GLint y, GLint z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3iv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3ui)(GLuint index, GLuint x, GLuint y, GLuint z) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3uiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4bv)(GLuint index, const GLbyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4i)(GLuint index, GLint x, GLint y, GLint z, GLint w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4iv)(GLuint index, const GLint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4sv)(GLuint index, const GLshort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4ubv)(GLuint index, const GLubyte * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4ui)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4uiv)(GLuint index, const GLuint * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4usv)(GLuint index, const GLushort * v) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribIPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glCopyBufferSubData)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformBlockName) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformName)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformName) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint * params) = NULL; +GLuint (CODEGEN_FUNCPTR *_ptrc_glGetUniformBlockIndex)(GLuint program, const GLchar * uniformBlockName) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint * uniformIndices) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glPrimitiveRestartIndex)(GLuint index) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexBuffer)(GLenum target, GLenum internalformat, GLuint buffer) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glUniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) = NULL; + +GLenum (CODEGEN_FUNCPTR *_ptrc_glClientWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteSync)(GLsync sync) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsInstancedBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDrawRangeElementsBaseVertex)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex) = NULL; +GLsync (CODEGEN_FUNCPTR *_ptrc_glFenceSync)(GLenum condition, GLbitfield flags) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture)(GLenum target, GLenum attachment, GLuint texture, GLint level) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetBufferParameteri64v)(GLenum target, GLenum pname, GLint64 * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetInteger64i_v)(GLenum target, GLuint index, GLint64 * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetInteger64v)(GLenum pname, GLint64 * data) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetMultisamplefv)(GLenum pname, GLuint index, GLfloat * val) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetSynciv)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei * length, GLint * values) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsSync)(GLsync sync) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawElementsBaseVertex)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount, const GLint * basevertex) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glProvokingVertex)(GLenum mode) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSampleMaski)(GLuint maskNumber, GLbitfield mask) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexImage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glTexImage3DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout) = NULL; + +void (CODEGEN_FUNCPTR *_ptrc_glBindFragDataLocationIndexed)(GLuint program, GLuint colorNumber, GLuint index, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glBindSampler)(GLuint unit, GLuint sampler) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glDeleteSamplers)(GLsizei count, const GLuint * samplers) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGenSamplers)(GLsizei count, GLuint * samplers) = NULL; +GLint (CODEGEN_FUNCPTR *_ptrc_glGetFragDataIndex)(GLuint program, const GLchar * name) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjecti64v)(GLuint id, GLenum pname, GLint64 * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectui64v)(GLuint id, GLenum pname, GLuint64 * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterIiv)(GLuint sampler, GLenum pname, GLint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterIuiv)(GLuint sampler, GLenum pname, GLuint * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterfv)(GLuint sampler, GLenum pname, GLfloat * params) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameteriv)(GLuint sampler, GLenum pname, GLint * params) = NULL; +GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsSampler)(GLuint sampler) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glQueryCounter)(GLuint id, GLenum target) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterIiv)(GLuint sampler, GLenum pname, const GLint * param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterIuiv)(GLuint sampler, GLenum pname, const GLuint * param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterf)(GLuint sampler, GLenum pname, GLfloat param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterfv)(GLuint sampler, GLenum pname, const GLfloat * param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameteri)(GLuint sampler, GLenum pname, GLint param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameteriv)(GLuint sampler, GLenum pname, const GLint * param) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribDivisor)(GLuint index, GLuint divisor) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP1ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP1uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP2ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP2uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP3ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP3uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP4ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value) = NULL; +void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP4uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value) = NULL; + +static int Load_Version_3_3(void) +{ + int numFailed = 0; + _ptrc_glAccum = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glAccum"); + if(!_ptrc_glAccum) numFailed++; + _ptrc_glAlphaFunc = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glAlphaFunc"); + if(!_ptrc_glAlphaFunc) numFailed++; + _ptrc_glBegin = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glBegin"); + if(!_ptrc_glBegin) numFailed++; + _ptrc_glBitmap = (void (CODEGEN_FUNCPTR *)(GLsizei, GLsizei, GLfloat, GLfloat, GLfloat, GLfloat, const GLubyte *))IntGetProcAddress("glBitmap"); + if(!_ptrc_glBitmap) numFailed++; + _ptrc_glBlendFunc = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glBlendFunc"); + if(!_ptrc_glBlendFunc) numFailed++; + _ptrc_glCallList = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glCallList"); + if(!_ptrc_glCallList) numFailed++; + _ptrc_glCallLists = (void (CODEGEN_FUNCPTR *)(GLsizei, GLenum, const void *))IntGetProcAddress("glCallLists"); + if(!_ptrc_glCallLists) numFailed++; + _ptrc_glClear = (void (CODEGEN_FUNCPTR *)(GLbitfield))IntGetProcAddress("glClear"); + if(!_ptrc_glClear) numFailed++; + _ptrc_glClearAccum = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glClearAccum"); + if(!_ptrc_glClearAccum) numFailed++; + _ptrc_glClearColor = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glClearColor"); + if(!_ptrc_glClearColor) numFailed++; + _ptrc_glClearDepth = (void (CODEGEN_FUNCPTR *)(GLdouble))IntGetProcAddress("glClearDepth"); + if(!_ptrc_glClearDepth) numFailed++; + _ptrc_glClearIndex = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glClearIndex"); + if(!_ptrc_glClearIndex) numFailed++; + _ptrc_glClearStencil = (void (CODEGEN_FUNCPTR *)(GLint))IntGetProcAddress("glClearStencil"); + if(!_ptrc_glClearStencil) numFailed++; + _ptrc_glClipPlane = (void (CODEGEN_FUNCPTR *)(GLenum, const GLdouble *))IntGetProcAddress("glClipPlane"); + if(!_ptrc_glClipPlane) numFailed++; + _ptrc_glColor3b = (void (CODEGEN_FUNCPTR *)(GLbyte, GLbyte, GLbyte))IntGetProcAddress("glColor3b"); + if(!_ptrc_glColor3b) numFailed++; + _ptrc_glColor3bv = (void (CODEGEN_FUNCPTR *)(const GLbyte *))IntGetProcAddress("glColor3bv"); + if(!_ptrc_glColor3bv) numFailed++; + _ptrc_glColor3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glColor3d"); + if(!_ptrc_glColor3d) numFailed++; + _ptrc_glColor3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glColor3dv"); + if(!_ptrc_glColor3dv) numFailed++; + _ptrc_glColor3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glColor3f"); + if(!_ptrc_glColor3f) numFailed++; + _ptrc_glColor3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glColor3fv"); + if(!_ptrc_glColor3fv) numFailed++; + _ptrc_glColor3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glColor3i"); + if(!_ptrc_glColor3i) numFailed++; + _ptrc_glColor3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glColor3iv"); + if(!_ptrc_glColor3iv) numFailed++; + _ptrc_glColor3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glColor3s"); + if(!_ptrc_glColor3s) numFailed++; + _ptrc_glColor3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glColor3sv"); + if(!_ptrc_glColor3sv) numFailed++; + _ptrc_glColor3ub = (void (CODEGEN_FUNCPTR *)(GLubyte, GLubyte, GLubyte))IntGetProcAddress("glColor3ub"); + if(!_ptrc_glColor3ub) numFailed++; + _ptrc_glColor3ubv = (void (CODEGEN_FUNCPTR *)(const GLubyte *))IntGetProcAddress("glColor3ubv"); + if(!_ptrc_glColor3ubv) numFailed++; + _ptrc_glColor3ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint))IntGetProcAddress("glColor3ui"); + if(!_ptrc_glColor3ui) numFailed++; + _ptrc_glColor3uiv = (void (CODEGEN_FUNCPTR *)(const GLuint *))IntGetProcAddress("glColor3uiv"); + if(!_ptrc_glColor3uiv) numFailed++; + _ptrc_glColor3us = (void (CODEGEN_FUNCPTR *)(GLushort, GLushort, GLushort))IntGetProcAddress("glColor3us"); + if(!_ptrc_glColor3us) numFailed++; + _ptrc_glColor3usv = (void (CODEGEN_FUNCPTR *)(const GLushort *))IntGetProcAddress("glColor3usv"); + if(!_ptrc_glColor3usv) numFailed++; + _ptrc_glColor4b = (void (CODEGEN_FUNCPTR *)(GLbyte, GLbyte, GLbyte, GLbyte))IntGetProcAddress("glColor4b"); + if(!_ptrc_glColor4b) numFailed++; + _ptrc_glColor4bv = (void (CODEGEN_FUNCPTR *)(const GLbyte *))IntGetProcAddress("glColor4bv"); + if(!_ptrc_glColor4bv) numFailed++; + _ptrc_glColor4d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glColor4d"); + if(!_ptrc_glColor4d) numFailed++; + _ptrc_glColor4dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glColor4dv"); + if(!_ptrc_glColor4dv) numFailed++; + _ptrc_glColor4f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glColor4f"); + if(!_ptrc_glColor4f) numFailed++; + _ptrc_glColor4fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glColor4fv"); + if(!_ptrc_glColor4fv) numFailed++; + _ptrc_glColor4i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glColor4i"); + if(!_ptrc_glColor4i) numFailed++; + _ptrc_glColor4iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glColor4iv"); + if(!_ptrc_glColor4iv) numFailed++; + _ptrc_glColor4s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glColor4s"); + if(!_ptrc_glColor4s) numFailed++; + _ptrc_glColor4sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glColor4sv"); + if(!_ptrc_glColor4sv) numFailed++; + _ptrc_glColor4ub = (void (CODEGEN_FUNCPTR *)(GLubyte, GLubyte, GLubyte, GLubyte))IntGetProcAddress("glColor4ub"); + if(!_ptrc_glColor4ub) numFailed++; + _ptrc_glColor4ubv = (void (CODEGEN_FUNCPTR *)(const GLubyte *))IntGetProcAddress("glColor4ubv"); + if(!_ptrc_glColor4ubv) numFailed++; + _ptrc_glColor4ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint, GLuint))IntGetProcAddress("glColor4ui"); + if(!_ptrc_glColor4ui) numFailed++; + _ptrc_glColor4uiv = (void (CODEGEN_FUNCPTR *)(const GLuint *))IntGetProcAddress("glColor4uiv"); + if(!_ptrc_glColor4uiv) numFailed++; + _ptrc_glColor4us = (void (CODEGEN_FUNCPTR *)(GLushort, GLushort, GLushort, GLushort))IntGetProcAddress("glColor4us"); + if(!_ptrc_glColor4us) numFailed++; + _ptrc_glColor4usv = (void (CODEGEN_FUNCPTR *)(const GLushort *))IntGetProcAddress("glColor4usv"); + if(!_ptrc_glColor4usv) numFailed++; + _ptrc_glColorMask = (void (CODEGEN_FUNCPTR *)(GLboolean, GLboolean, GLboolean, GLboolean))IntGetProcAddress("glColorMask"); + if(!_ptrc_glColorMask) numFailed++; + _ptrc_glColorMaterial = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glColorMaterial"); + if(!_ptrc_glColorMaterial) numFailed++; + _ptrc_glCopyPixels = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLsizei, GLsizei, GLenum))IntGetProcAddress("glCopyPixels"); + if(!_ptrc_glCopyPixels) numFailed++; + _ptrc_glCullFace = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glCullFace"); + if(!_ptrc_glCullFace) numFailed++; + _ptrc_glDeleteLists = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei))IntGetProcAddress("glDeleteLists"); + if(!_ptrc_glDeleteLists) numFailed++; + _ptrc_glDepthFunc = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glDepthFunc"); + if(!_ptrc_glDepthFunc) numFailed++; + _ptrc_glDepthMask = (void (CODEGEN_FUNCPTR *)(GLboolean))IntGetProcAddress("glDepthMask"); + if(!_ptrc_glDepthMask) numFailed++; + _ptrc_glDepthRange = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glDepthRange"); + if(!_ptrc_glDepthRange) numFailed++; + _ptrc_glDisable = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glDisable"); + if(!_ptrc_glDisable) numFailed++; + _ptrc_glDrawBuffer = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glDrawBuffer"); + if(!_ptrc_glDrawBuffer) numFailed++; + _ptrc_glDrawPixels = (void (CODEGEN_FUNCPTR *)(GLsizei, GLsizei, GLenum, GLenum, const void *))IntGetProcAddress("glDrawPixels"); + if(!_ptrc_glDrawPixels) numFailed++; + _ptrc_glEdgeFlag = (void (CODEGEN_FUNCPTR *)(GLboolean))IntGetProcAddress("glEdgeFlag"); + if(!_ptrc_glEdgeFlag) numFailed++; + _ptrc_glEdgeFlagv = (void (CODEGEN_FUNCPTR *)(const GLboolean *))IntGetProcAddress("glEdgeFlagv"); + if(!_ptrc_glEdgeFlagv) numFailed++; + _ptrc_glEnable = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glEnable"); + if(!_ptrc_glEnable) numFailed++; + _ptrc_glEnd = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glEnd"); + if(!_ptrc_glEnd) numFailed++; + _ptrc_glEndList = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glEndList"); + if(!_ptrc_glEndList) numFailed++; + _ptrc_glEvalCoord1d = (void (CODEGEN_FUNCPTR *)(GLdouble))IntGetProcAddress("glEvalCoord1d"); + if(!_ptrc_glEvalCoord1d) numFailed++; + _ptrc_glEvalCoord1dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glEvalCoord1dv"); + if(!_ptrc_glEvalCoord1dv) numFailed++; + _ptrc_glEvalCoord1f = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glEvalCoord1f"); + if(!_ptrc_glEvalCoord1f) numFailed++; + _ptrc_glEvalCoord1fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glEvalCoord1fv"); + if(!_ptrc_glEvalCoord1fv) numFailed++; + _ptrc_glEvalCoord2d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glEvalCoord2d"); + if(!_ptrc_glEvalCoord2d) numFailed++; + _ptrc_glEvalCoord2dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glEvalCoord2dv"); + if(!_ptrc_glEvalCoord2dv) numFailed++; + _ptrc_glEvalCoord2f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glEvalCoord2f"); + if(!_ptrc_glEvalCoord2f) numFailed++; + _ptrc_glEvalCoord2fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glEvalCoord2fv"); + if(!_ptrc_glEvalCoord2fv) numFailed++; + _ptrc_glEvalMesh1 = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint))IntGetProcAddress("glEvalMesh1"); + if(!_ptrc_glEvalMesh1) numFailed++; + _ptrc_glEvalMesh2 = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint))IntGetProcAddress("glEvalMesh2"); + if(!_ptrc_glEvalMesh2) numFailed++; + _ptrc_glEvalPoint1 = (void (CODEGEN_FUNCPTR *)(GLint))IntGetProcAddress("glEvalPoint1"); + if(!_ptrc_glEvalPoint1) numFailed++; + _ptrc_glEvalPoint2 = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glEvalPoint2"); + if(!_ptrc_glEvalPoint2) numFailed++; + _ptrc_glFeedbackBuffer = (void (CODEGEN_FUNCPTR *)(GLsizei, GLenum, GLfloat *))IntGetProcAddress("glFeedbackBuffer"); + if(!_ptrc_glFeedbackBuffer) numFailed++; + _ptrc_glFinish = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glFinish"); + if(!_ptrc_glFinish) numFailed++; + _ptrc_glFlush = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glFlush"); + if(!_ptrc_glFlush) numFailed++; + _ptrc_glFogf = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glFogf"); + if(!_ptrc_glFogf) numFailed++; + _ptrc_glFogfv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glFogfv"); + if(!_ptrc_glFogfv) numFailed++; + _ptrc_glFogi = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glFogi"); + if(!_ptrc_glFogi) numFailed++; + _ptrc_glFogiv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glFogiv"); + if(!_ptrc_glFogiv) numFailed++; + _ptrc_glFrontFace = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glFrontFace"); + if(!_ptrc_glFrontFace) numFailed++; + _ptrc_glFrustum = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glFrustum"); + if(!_ptrc_glFrustum) numFailed++; + _ptrc_glGenLists = (GLuint (CODEGEN_FUNCPTR *)(GLsizei))IntGetProcAddress("glGenLists"); + if(!_ptrc_glGenLists) numFailed++; + _ptrc_glGetBooleanv = (void (CODEGEN_FUNCPTR *)(GLenum, GLboolean *))IntGetProcAddress("glGetBooleanv"); + if(!_ptrc_glGetBooleanv) numFailed++; + _ptrc_glGetClipPlane = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble *))IntGetProcAddress("glGetClipPlane"); + if(!_ptrc_glGetClipPlane) numFailed++; + _ptrc_glGetDoublev = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble *))IntGetProcAddress("glGetDoublev"); + if(!_ptrc_glGetDoublev) numFailed++; + _ptrc_glGetError = (GLenum (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glGetError"); + if(!_ptrc_glGetError) numFailed++; + _ptrc_glGetFloatv = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat *))IntGetProcAddress("glGetFloatv"); + if(!_ptrc_glGetFloatv) numFailed++; + _ptrc_glGetIntegerv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint *))IntGetProcAddress("glGetIntegerv"); + if(!_ptrc_glGetIntegerv) numFailed++; + _ptrc_glGetLightfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetLightfv"); + if(!_ptrc_glGetLightfv) numFailed++; + _ptrc_glGetLightiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetLightiv"); + if(!_ptrc_glGetLightiv) numFailed++; + _ptrc_glGetMapdv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLdouble *))IntGetProcAddress("glGetMapdv"); + if(!_ptrc_glGetMapdv) numFailed++; + _ptrc_glGetMapfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetMapfv"); + if(!_ptrc_glGetMapfv) numFailed++; + _ptrc_glGetMapiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetMapiv"); + if(!_ptrc_glGetMapiv) numFailed++; + _ptrc_glGetMaterialfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetMaterialfv"); + if(!_ptrc_glGetMaterialfv) numFailed++; + _ptrc_glGetMaterialiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetMaterialiv"); + if(!_ptrc_glGetMaterialiv) numFailed++; + _ptrc_glGetPixelMapfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat *))IntGetProcAddress("glGetPixelMapfv"); + if(!_ptrc_glGetPixelMapfv) numFailed++; + _ptrc_glGetPixelMapuiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint *))IntGetProcAddress("glGetPixelMapuiv"); + if(!_ptrc_glGetPixelMapuiv) numFailed++; + _ptrc_glGetPixelMapusv = (void (CODEGEN_FUNCPTR *)(GLenum, GLushort *))IntGetProcAddress("glGetPixelMapusv"); + if(!_ptrc_glGetPixelMapusv) numFailed++; + _ptrc_glGetPolygonStipple = (void (CODEGEN_FUNCPTR *)(GLubyte *))IntGetProcAddress("glGetPolygonStipple"); + if(!_ptrc_glGetPolygonStipple) numFailed++; + _ptrc_glGetString = (const GLubyte * (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glGetString"); + if(!_ptrc_glGetString) numFailed++; + _ptrc_glGetTexEnvfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetTexEnvfv"); + if(!_ptrc_glGetTexEnvfv) numFailed++; + _ptrc_glGetTexEnviv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetTexEnviv"); + if(!_ptrc_glGetTexEnviv) numFailed++; + _ptrc_glGetTexGendv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLdouble *))IntGetProcAddress("glGetTexGendv"); + if(!_ptrc_glGetTexGendv) numFailed++; + _ptrc_glGetTexGenfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetTexGenfv"); + if(!_ptrc_glGetTexGenfv) numFailed++; + _ptrc_glGetTexGeniv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetTexGeniv"); + if(!_ptrc_glGetTexGeniv) numFailed++; + _ptrc_glGetTexImage = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLenum, void *))IntGetProcAddress("glGetTexImage"); + if(!_ptrc_glGetTexImage) numFailed++; + _ptrc_glGetTexLevelParameterfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLfloat *))IntGetProcAddress("glGetTexLevelParameterfv"); + if(!_ptrc_glGetTexLevelParameterfv) numFailed++; + _ptrc_glGetTexLevelParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLint *))IntGetProcAddress("glGetTexLevelParameteriv"); + if(!_ptrc_glGetTexLevelParameteriv) numFailed++; + _ptrc_glGetTexParameterfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat *))IntGetProcAddress("glGetTexParameterfv"); + if(!_ptrc_glGetTexParameterfv) numFailed++; + _ptrc_glGetTexParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetTexParameteriv"); + if(!_ptrc_glGetTexParameteriv) numFailed++; + _ptrc_glHint = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glHint"); + if(!_ptrc_glHint) numFailed++; + _ptrc_glIndexMask = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIndexMask"); + if(!_ptrc_glIndexMask) numFailed++; + _ptrc_glIndexd = (void (CODEGEN_FUNCPTR *)(GLdouble))IntGetProcAddress("glIndexd"); + if(!_ptrc_glIndexd) numFailed++; + _ptrc_glIndexdv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glIndexdv"); + if(!_ptrc_glIndexdv) numFailed++; + _ptrc_glIndexf = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glIndexf"); + if(!_ptrc_glIndexf) numFailed++; + _ptrc_glIndexfv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glIndexfv"); + if(!_ptrc_glIndexfv) numFailed++; + _ptrc_glIndexi = (void (CODEGEN_FUNCPTR *)(GLint))IntGetProcAddress("glIndexi"); + if(!_ptrc_glIndexi) numFailed++; + _ptrc_glIndexiv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glIndexiv"); + if(!_ptrc_glIndexiv) numFailed++; + _ptrc_glIndexs = (void (CODEGEN_FUNCPTR *)(GLshort))IntGetProcAddress("glIndexs"); + if(!_ptrc_glIndexs) numFailed++; + _ptrc_glIndexsv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glIndexsv"); + if(!_ptrc_glIndexsv) numFailed++; + _ptrc_glInitNames = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glInitNames"); + if(!_ptrc_glInitNames) numFailed++; + _ptrc_glIsEnabled = (GLboolean (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glIsEnabled"); + if(!_ptrc_glIsEnabled) numFailed++; + _ptrc_glIsList = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsList"); + if(!_ptrc_glIsList) numFailed++; + _ptrc_glLightModelf = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glLightModelf"); + if(!_ptrc_glLightModelf) numFailed++; + _ptrc_glLightModelfv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glLightModelfv"); + if(!_ptrc_glLightModelfv) numFailed++; + _ptrc_glLightModeli = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glLightModeli"); + if(!_ptrc_glLightModeli) numFailed++; + _ptrc_glLightModeliv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glLightModeliv"); + if(!_ptrc_glLightModeliv) numFailed++; + _ptrc_glLightf = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat))IntGetProcAddress("glLightf"); + if(!_ptrc_glLightf) numFailed++; + _ptrc_glLightfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLfloat *))IntGetProcAddress("glLightfv"); + if(!_ptrc_glLightfv) numFailed++; + _ptrc_glLighti = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint))IntGetProcAddress("glLighti"); + if(!_ptrc_glLighti) numFailed++; + _ptrc_glLightiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glLightiv"); + if(!_ptrc_glLightiv) numFailed++; + _ptrc_glLineStipple = (void (CODEGEN_FUNCPTR *)(GLint, GLushort))IntGetProcAddress("glLineStipple"); + if(!_ptrc_glLineStipple) numFailed++; + _ptrc_glLineWidth = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glLineWidth"); + if(!_ptrc_glLineWidth) numFailed++; + _ptrc_glListBase = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glListBase"); + if(!_ptrc_glListBase) numFailed++; + _ptrc_glLoadIdentity = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glLoadIdentity"); + if(!_ptrc_glLoadIdentity) numFailed++; + _ptrc_glLoadMatrixd = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glLoadMatrixd"); + if(!_ptrc_glLoadMatrixd) numFailed++; + _ptrc_glLoadMatrixf = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glLoadMatrixf"); + if(!_ptrc_glLoadMatrixf) numFailed++; + _ptrc_glLoadName = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glLoadName"); + if(!_ptrc_glLoadName) numFailed++; + _ptrc_glLogicOp = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glLogicOp"); + if(!_ptrc_glLogicOp) numFailed++; + _ptrc_glMap1d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble, GLdouble, GLint, GLint, const GLdouble *))IntGetProcAddress("glMap1d"); + if(!_ptrc_glMap1d) numFailed++; + _ptrc_glMap1f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat, GLfloat, GLint, GLint, const GLfloat *))IntGetProcAddress("glMap1f"); + if(!_ptrc_glMap1f) numFailed++; + _ptrc_glMap2d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *))IntGetProcAddress("glMap2d"); + if(!_ptrc_glMap2d) numFailed++; + _ptrc_glMap2f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *))IntGetProcAddress("glMap2f"); + if(!_ptrc_glMap2f) numFailed++; + _ptrc_glMapGrid1d = (void (CODEGEN_FUNCPTR *)(GLint, GLdouble, GLdouble))IntGetProcAddress("glMapGrid1d"); + if(!_ptrc_glMapGrid1d) numFailed++; + _ptrc_glMapGrid1f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat, GLfloat))IntGetProcAddress("glMapGrid1f"); + if(!_ptrc_glMapGrid1f) numFailed++; + _ptrc_glMapGrid2d = (void (CODEGEN_FUNCPTR *)(GLint, GLdouble, GLdouble, GLint, GLdouble, GLdouble))IntGetProcAddress("glMapGrid2d"); + if(!_ptrc_glMapGrid2d) numFailed++; + _ptrc_glMapGrid2f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat, GLfloat, GLint, GLfloat, GLfloat))IntGetProcAddress("glMapGrid2f"); + if(!_ptrc_glMapGrid2f) numFailed++; + _ptrc_glMaterialf = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat))IntGetProcAddress("glMaterialf"); + if(!_ptrc_glMaterialf) numFailed++; + _ptrc_glMaterialfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLfloat *))IntGetProcAddress("glMaterialfv"); + if(!_ptrc_glMaterialfv) numFailed++; + _ptrc_glMateriali = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint))IntGetProcAddress("glMateriali"); + if(!_ptrc_glMateriali) numFailed++; + _ptrc_glMaterialiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glMaterialiv"); + if(!_ptrc_glMaterialiv) numFailed++; + _ptrc_glMatrixMode = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glMatrixMode"); + if(!_ptrc_glMatrixMode) numFailed++; + _ptrc_glMultMatrixd = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glMultMatrixd"); + if(!_ptrc_glMultMatrixd) numFailed++; + _ptrc_glMultMatrixf = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glMultMatrixf"); + if(!_ptrc_glMultMatrixf) numFailed++; + _ptrc_glNewList = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum))IntGetProcAddress("glNewList"); + if(!_ptrc_glNewList) numFailed++; + _ptrc_glNormal3b = (void (CODEGEN_FUNCPTR *)(GLbyte, GLbyte, GLbyte))IntGetProcAddress("glNormal3b"); + if(!_ptrc_glNormal3b) numFailed++; + _ptrc_glNormal3bv = (void (CODEGEN_FUNCPTR *)(const GLbyte *))IntGetProcAddress("glNormal3bv"); + if(!_ptrc_glNormal3bv) numFailed++; + _ptrc_glNormal3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glNormal3d"); + if(!_ptrc_glNormal3d) numFailed++; + _ptrc_glNormal3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glNormal3dv"); + if(!_ptrc_glNormal3dv) numFailed++; + _ptrc_glNormal3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glNormal3f"); + if(!_ptrc_glNormal3f) numFailed++; + _ptrc_glNormal3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glNormal3fv"); + if(!_ptrc_glNormal3fv) numFailed++; + _ptrc_glNormal3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glNormal3i"); + if(!_ptrc_glNormal3i) numFailed++; + _ptrc_glNormal3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glNormal3iv"); + if(!_ptrc_glNormal3iv) numFailed++; + _ptrc_glNormal3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glNormal3s"); + if(!_ptrc_glNormal3s) numFailed++; + _ptrc_glNormal3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glNormal3sv"); + if(!_ptrc_glNormal3sv) numFailed++; + _ptrc_glOrtho = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glOrtho"); + if(!_ptrc_glOrtho) numFailed++; + _ptrc_glPassThrough = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glPassThrough"); + if(!_ptrc_glPassThrough) numFailed++; + _ptrc_glPixelMapfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const GLfloat *))IntGetProcAddress("glPixelMapfv"); + if(!_ptrc_glPixelMapfv) numFailed++; + _ptrc_glPixelMapuiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const GLuint *))IntGetProcAddress("glPixelMapuiv"); + if(!_ptrc_glPixelMapuiv) numFailed++; + _ptrc_glPixelMapusv = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const GLushort *))IntGetProcAddress("glPixelMapusv"); + if(!_ptrc_glPixelMapusv) numFailed++; + _ptrc_glPixelStoref = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glPixelStoref"); + if(!_ptrc_glPixelStoref) numFailed++; + _ptrc_glPixelStorei = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glPixelStorei"); + if(!_ptrc_glPixelStorei) numFailed++; + _ptrc_glPixelTransferf = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glPixelTransferf"); + if(!_ptrc_glPixelTransferf) numFailed++; + _ptrc_glPixelTransferi = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glPixelTransferi"); + if(!_ptrc_glPixelTransferi) numFailed++; + _ptrc_glPixelZoom = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glPixelZoom"); + if(!_ptrc_glPixelZoom) numFailed++; + _ptrc_glPointSize = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glPointSize"); + if(!_ptrc_glPointSize) numFailed++; + _ptrc_glPolygonMode = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glPolygonMode"); + if(!_ptrc_glPolygonMode) numFailed++; + _ptrc_glPolygonStipple = (void (CODEGEN_FUNCPTR *)(const GLubyte *))IntGetProcAddress("glPolygonStipple"); + if(!_ptrc_glPolygonStipple) numFailed++; + _ptrc_glPopAttrib = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPopAttrib"); + if(!_ptrc_glPopAttrib) numFailed++; + _ptrc_glPopMatrix = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPopMatrix"); + if(!_ptrc_glPopMatrix) numFailed++; + _ptrc_glPopName = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPopName"); + if(!_ptrc_glPopName) numFailed++; + _ptrc_glPushAttrib = (void (CODEGEN_FUNCPTR *)(GLbitfield))IntGetProcAddress("glPushAttrib"); + if(!_ptrc_glPushAttrib) numFailed++; + _ptrc_glPushMatrix = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPushMatrix"); + if(!_ptrc_glPushMatrix) numFailed++; + _ptrc_glPushName = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glPushName"); + if(!_ptrc_glPushName) numFailed++; + _ptrc_glRasterPos2d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glRasterPos2d"); + if(!_ptrc_glRasterPos2d) numFailed++; + _ptrc_glRasterPos2dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glRasterPos2dv"); + if(!_ptrc_glRasterPos2dv) numFailed++; + _ptrc_glRasterPos2f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glRasterPos2f"); + if(!_ptrc_glRasterPos2f) numFailed++; + _ptrc_glRasterPos2fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glRasterPos2fv"); + if(!_ptrc_glRasterPos2fv) numFailed++; + _ptrc_glRasterPos2i = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glRasterPos2i"); + if(!_ptrc_glRasterPos2i) numFailed++; + _ptrc_glRasterPos2iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glRasterPos2iv"); + if(!_ptrc_glRasterPos2iv) numFailed++; + _ptrc_glRasterPos2s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort))IntGetProcAddress("glRasterPos2s"); + if(!_ptrc_glRasterPos2s) numFailed++; + _ptrc_glRasterPos2sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glRasterPos2sv"); + if(!_ptrc_glRasterPos2sv) numFailed++; + _ptrc_glRasterPos3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glRasterPos3d"); + if(!_ptrc_glRasterPos3d) numFailed++; + _ptrc_glRasterPos3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glRasterPos3dv"); + if(!_ptrc_glRasterPos3dv) numFailed++; + _ptrc_glRasterPos3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glRasterPos3f"); + if(!_ptrc_glRasterPos3f) numFailed++; + _ptrc_glRasterPos3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glRasterPos3fv"); + if(!_ptrc_glRasterPos3fv) numFailed++; + _ptrc_glRasterPos3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glRasterPos3i"); + if(!_ptrc_glRasterPos3i) numFailed++; + _ptrc_glRasterPos3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glRasterPos3iv"); + if(!_ptrc_glRasterPos3iv) numFailed++; + _ptrc_glRasterPos3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glRasterPos3s"); + if(!_ptrc_glRasterPos3s) numFailed++; + _ptrc_glRasterPos3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glRasterPos3sv"); + if(!_ptrc_glRasterPos3sv) numFailed++; + _ptrc_glRasterPos4d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glRasterPos4d"); + if(!_ptrc_glRasterPos4d) numFailed++; + _ptrc_glRasterPos4dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glRasterPos4dv"); + if(!_ptrc_glRasterPos4dv) numFailed++; + _ptrc_glRasterPos4f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glRasterPos4f"); + if(!_ptrc_glRasterPos4f) numFailed++; + _ptrc_glRasterPos4fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glRasterPos4fv"); + if(!_ptrc_glRasterPos4fv) numFailed++; + _ptrc_glRasterPos4i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glRasterPos4i"); + if(!_ptrc_glRasterPos4i) numFailed++; + _ptrc_glRasterPos4iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glRasterPos4iv"); + if(!_ptrc_glRasterPos4iv) numFailed++; + _ptrc_glRasterPos4s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glRasterPos4s"); + if(!_ptrc_glRasterPos4s) numFailed++; + _ptrc_glRasterPos4sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glRasterPos4sv"); + if(!_ptrc_glRasterPos4sv) numFailed++; + _ptrc_glReadBuffer = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glReadBuffer"); + if(!_ptrc_glReadBuffer) numFailed++; + _ptrc_glReadPixels = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *))IntGetProcAddress("glReadPixels"); + if(!_ptrc_glReadPixels) numFailed++; + _ptrc_glRectd = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glRectd"); + if(!_ptrc_glRectd) numFailed++; + _ptrc_glRectdv = (void (CODEGEN_FUNCPTR *)(const GLdouble *, const GLdouble *))IntGetProcAddress("glRectdv"); + if(!_ptrc_glRectdv) numFailed++; + _ptrc_glRectf = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glRectf"); + if(!_ptrc_glRectf) numFailed++; + _ptrc_glRectfv = (void (CODEGEN_FUNCPTR *)(const GLfloat *, const GLfloat *))IntGetProcAddress("glRectfv"); + if(!_ptrc_glRectfv) numFailed++; + _ptrc_glRecti = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glRecti"); + if(!_ptrc_glRecti) numFailed++; + _ptrc_glRectiv = (void (CODEGEN_FUNCPTR *)(const GLint *, const GLint *))IntGetProcAddress("glRectiv"); + if(!_ptrc_glRectiv) numFailed++; + _ptrc_glRects = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glRects"); + if(!_ptrc_glRects) numFailed++; + _ptrc_glRectsv = (void (CODEGEN_FUNCPTR *)(const GLshort *, const GLshort *))IntGetProcAddress("glRectsv"); + if(!_ptrc_glRectsv) numFailed++; + _ptrc_glRenderMode = (GLint (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glRenderMode"); + if(!_ptrc_glRenderMode) numFailed++; + _ptrc_glRotated = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glRotated"); + if(!_ptrc_glRotated) numFailed++; + _ptrc_glRotatef = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glRotatef"); + if(!_ptrc_glRotatef) numFailed++; + _ptrc_glScaled = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glScaled"); + if(!_ptrc_glScaled) numFailed++; + _ptrc_glScalef = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glScalef"); + if(!_ptrc_glScalef) numFailed++; + _ptrc_glScissor = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLsizei, GLsizei))IntGetProcAddress("glScissor"); + if(!_ptrc_glScissor) numFailed++; + _ptrc_glSelectBuffer = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glSelectBuffer"); + if(!_ptrc_glSelectBuffer) numFailed++; + _ptrc_glShadeModel = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glShadeModel"); + if(!_ptrc_glShadeModel) numFailed++; + _ptrc_glStencilFunc = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLuint))IntGetProcAddress("glStencilFunc"); + if(!_ptrc_glStencilFunc) numFailed++; + _ptrc_glStencilMask = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glStencilMask"); + if(!_ptrc_glStencilMask) numFailed++; + _ptrc_glStencilOp = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum))IntGetProcAddress("glStencilOp"); + if(!_ptrc_glStencilOp) numFailed++; + _ptrc_glTexCoord1d = (void (CODEGEN_FUNCPTR *)(GLdouble))IntGetProcAddress("glTexCoord1d"); + if(!_ptrc_glTexCoord1d) numFailed++; + _ptrc_glTexCoord1dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glTexCoord1dv"); + if(!_ptrc_glTexCoord1dv) numFailed++; + _ptrc_glTexCoord1f = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glTexCoord1f"); + if(!_ptrc_glTexCoord1f) numFailed++; + _ptrc_glTexCoord1fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glTexCoord1fv"); + if(!_ptrc_glTexCoord1fv) numFailed++; + _ptrc_glTexCoord1i = (void (CODEGEN_FUNCPTR *)(GLint))IntGetProcAddress("glTexCoord1i"); + if(!_ptrc_glTexCoord1i) numFailed++; + _ptrc_glTexCoord1iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glTexCoord1iv"); + if(!_ptrc_glTexCoord1iv) numFailed++; + _ptrc_glTexCoord1s = (void (CODEGEN_FUNCPTR *)(GLshort))IntGetProcAddress("glTexCoord1s"); + if(!_ptrc_glTexCoord1s) numFailed++; + _ptrc_glTexCoord1sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glTexCoord1sv"); + if(!_ptrc_glTexCoord1sv) numFailed++; + _ptrc_glTexCoord2d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glTexCoord2d"); + if(!_ptrc_glTexCoord2d) numFailed++; + _ptrc_glTexCoord2dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glTexCoord2dv"); + if(!_ptrc_glTexCoord2dv) numFailed++; + _ptrc_glTexCoord2f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glTexCoord2f"); + if(!_ptrc_glTexCoord2f) numFailed++; + _ptrc_glTexCoord2fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glTexCoord2fv"); + if(!_ptrc_glTexCoord2fv) numFailed++; + _ptrc_glTexCoord2i = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glTexCoord2i"); + if(!_ptrc_glTexCoord2i) numFailed++; + _ptrc_glTexCoord2iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glTexCoord2iv"); + if(!_ptrc_glTexCoord2iv) numFailed++; + _ptrc_glTexCoord2s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort))IntGetProcAddress("glTexCoord2s"); + if(!_ptrc_glTexCoord2s) numFailed++; + _ptrc_glTexCoord2sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glTexCoord2sv"); + if(!_ptrc_glTexCoord2sv) numFailed++; + _ptrc_glTexCoord3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glTexCoord3d"); + if(!_ptrc_glTexCoord3d) numFailed++; + _ptrc_glTexCoord3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glTexCoord3dv"); + if(!_ptrc_glTexCoord3dv) numFailed++; + _ptrc_glTexCoord3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glTexCoord3f"); + if(!_ptrc_glTexCoord3f) numFailed++; + _ptrc_glTexCoord3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glTexCoord3fv"); + if(!_ptrc_glTexCoord3fv) numFailed++; + _ptrc_glTexCoord3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glTexCoord3i"); + if(!_ptrc_glTexCoord3i) numFailed++; + _ptrc_glTexCoord3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glTexCoord3iv"); + if(!_ptrc_glTexCoord3iv) numFailed++; + _ptrc_glTexCoord3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glTexCoord3s"); + if(!_ptrc_glTexCoord3s) numFailed++; + _ptrc_glTexCoord3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glTexCoord3sv"); + if(!_ptrc_glTexCoord3sv) numFailed++; + _ptrc_glTexCoord4d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glTexCoord4d"); + if(!_ptrc_glTexCoord4d) numFailed++; + _ptrc_glTexCoord4dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glTexCoord4dv"); + if(!_ptrc_glTexCoord4dv) numFailed++; + _ptrc_glTexCoord4f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glTexCoord4f"); + if(!_ptrc_glTexCoord4f) numFailed++; + _ptrc_glTexCoord4fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glTexCoord4fv"); + if(!_ptrc_glTexCoord4fv) numFailed++; + _ptrc_glTexCoord4i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glTexCoord4i"); + if(!_ptrc_glTexCoord4i) numFailed++; + _ptrc_glTexCoord4iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glTexCoord4iv"); + if(!_ptrc_glTexCoord4iv) numFailed++; + _ptrc_glTexCoord4s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glTexCoord4s"); + if(!_ptrc_glTexCoord4s) numFailed++; + _ptrc_glTexCoord4sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glTexCoord4sv"); + if(!_ptrc_glTexCoord4sv) numFailed++; + _ptrc_glTexEnvf = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat))IntGetProcAddress("glTexEnvf"); + if(!_ptrc_glTexEnvf) numFailed++; + _ptrc_glTexEnvfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLfloat *))IntGetProcAddress("glTexEnvfv"); + if(!_ptrc_glTexEnvfv) numFailed++; + _ptrc_glTexEnvi = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint))IntGetProcAddress("glTexEnvi"); + if(!_ptrc_glTexEnvi) numFailed++; + _ptrc_glTexEnviv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glTexEnviv"); + if(!_ptrc_glTexEnviv) numFailed++; + _ptrc_glTexGend = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLdouble))IntGetProcAddress("glTexGend"); + if(!_ptrc_glTexGend) numFailed++; + _ptrc_glTexGendv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLdouble *))IntGetProcAddress("glTexGendv"); + if(!_ptrc_glTexGendv) numFailed++; + _ptrc_glTexGenf = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat))IntGetProcAddress("glTexGenf"); + if(!_ptrc_glTexGenf) numFailed++; + _ptrc_glTexGenfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLfloat *))IntGetProcAddress("glTexGenfv"); + if(!_ptrc_glTexGenfv) numFailed++; + _ptrc_glTexGeni = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint))IntGetProcAddress("glTexGeni"); + if(!_ptrc_glTexGeni) numFailed++; + _ptrc_glTexGeniv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glTexGeniv"); + if(!_ptrc_glTexGeniv) numFailed++; + _ptrc_glTexImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLint, GLenum, GLenum, const void *))IntGetProcAddress("glTexImage1D"); + if(!_ptrc_glTexImage1D) numFailed++; + _ptrc_glTexImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *))IntGetProcAddress("glTexImage2D"); + if(!_ptrc_glTexImage2D) numFailed++; + _ptrc_glTexParameterf = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLfloat))IntGetProcAddress("glTexParameterf"); + if(!_ptrc_glTexParameterf) numFailed++; + _ptrc_glTexParameterfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLfloat *))IntGetProcAddress("glTexParameterfv"); + if(!_ptrc_glTexParameterfv) numFailed++; + _ptrc_glTexParameteri = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint))IntGetProcAddress("glTexParameteri"); + if(!_ptrc_glTexParameteri) numFailed++; + _ptrc_glTexParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glTexParameteriv"); + if(!_ptrc_glTexParameteriv) numFailed++; + _ptrc_glTranslated = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glTranslated"); + if(!_ptrc_glTranslated) numFailed++; + _ptrc_glTranslatef = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glTranslatef"); + if(!_ptrc_glTranslatef) numFailed++; + _ptrc_glVertex2d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glVertex2d"); + if(!_ptrc_glVertex2d) numFailed++; + _ptrc_glVertex2dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glVertex2dv"); + if(!_ptrc_glVertex2dv) numFailed++; + _ptrc_glVertex2f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glVertex2f"); + if(!_ptrc_glVertex2f) numFailed++; + _ptrc_glVertex2fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glVertex2fv"); + if(!_ptrc_glVertex2fv) numFailed++; + _ptrc_glVertex2i = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glVertex2i"); + if(!_ptrc_glVertex2i) numFailed++; + _ptrc_glVertex2iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glVertex2iv"); + if(!_ptrc_glVertex2iv) numFailed++; + _ptrc_glVertex2s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort))IntGetProcAddress("glVertex2s"); + if(!_ptrc_glVertex2s) numFailed++; + _ptrc_glVertex2sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glVertex2sv"); + if(!_ptrc_glVertex2sv) numFailed++; + _ptrc_glVertex3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glVertex3d"); + if(!_ptrc_glVertex3d) numFailed++; + _ptrc_glVertex3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glVertex3dv"); + if(!_ptrc_glVertex3dv) numFailed++; + _ptrc_glVertex3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glVertex3f"); + if(!_ptrc_glVertex3f) numFailed++; + _ptrc_glVertex3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glVertex3fv"); + if(!_ptrc_glVertex3fv) numFailed++; + _ptrc_glVertex3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glVertex3i"); + if(!_ptrc_glVertex3i) numFailed++; + _ptrc_glVertex3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glVertex3iv"); + if(!_ptrc_glVertex3iv) numFailed++; + _ptrc_glVertex3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glVertex3s"); + if(!_ptrc_glVertex3s) numFailed++; + _ptrc_glVertex3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glVertex3sv"); + if(!_ptrc_glVertex3sv) numFailed++; + _ptrc_glVertex4d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glVertex4d"); + if(!_ptrc_glVertex4d) numFailed++; + _ptrc_glVertex4dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glVertex4dv"); + if(!_ptrc_glVertex4dv) numFailed++; + _ptrc_glVertex4f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glVertex4f"); + if(!_ptrc_glVertex4f) numFailed++; + _ptrc_glVertex4fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glVertex4fv"); + if(!_ptrc_glVertex4fv) numFailed++; + _ptrc_glVertex4i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glVertex4i"); + if(!_ptrc_glVertex4i) numFailed++; + _ptrc_glVertex4iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glVertex4iv"); + if(!_ptrc_glVertex4iv) numFailed++; + _ptrc_glVertex4s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glVertex4s"); + if(!_ptrc_glVertex4s) numFailed++; + _ptrc_glVertex4sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glVertex4sv"); + if(!_ptrc_glVertex4sv) numFailed++; + _ptrc_glViewport = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLsizei, GLsizei))IntGetProcAddress("glViewport"); + if(!_ptrc_glViewport) numFailed++; + _ptrc_glAreTexturesResident = (GLboolean (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *, GLboolean *))IntGetProcAddress("glAreTexturesResident"); + if(!_ptrc_glAreTexturesResident) numFailed++; + _ptrc_glArrayElement = (void (CODEGEN_FUNCPTR *)(GLint))IntGetProcAddress("glArrayElement"); + if(!_ptrc_glArrayElement) numFailed++; + _ptrc_glBindTexture = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindTexture"); + if(!_ptrc_glBindTexture) numFailed++; + _ptrc_glColorPointer = (void (CODEGEN_FUNCPTR *)(GLint, GLenum, GLsizei, const void *))IntGetProcAddress("glColorPointer"); + if(!_ptrc_glColorPointer) numFailed++; + _ptrc_glCopyTexImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint))IntGetProcAddress("glCopyTexImage1D"); + if(!_ptrc_glCopyTexImage1D) numFailed++; + _ptrc_glCopyTexImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint))IntGetProcAddress("glCopyTexImage2D"); + if(!_ptrc_glCopyTexImage2D) numFailed++; + _ptrc_glCopyTexSubImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLsizei))IntGetProcAddress("glCopyTexSubImage1D"); + if(!_ptrc_glCopyTexSubImage1D) numFailed++; + _ptrc_glCopyTexSubImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei))IntGetProcAddress("glCopyTexSubImage2D"); + if(!_ptrc_glCopyTexSubImage2D) numFailed++; + _ptrc_glDeleteTextures = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteTextures"); + if(!_ptrc_glDeleteTextures) numFailed++; + _ptrc_glDisableClientState = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glDisableClientState"); + if(!_ptrc_glDisableClientState) numFailed++; + _ptrc_glDrawArrays = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLsizei))IntGetProcAddress("glDrawArrays"); + if(!_ptrc_glDrawArrays) numFailed++; + _ptrc_glDrawElements = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, const void *))IntGetProcAddress("glDrawElements"); + if(!_ptrc_glDrawElements) numFailed++; + _ptrc_glEdgeFlagPointer = (void (CODEGEN_FUNCPTR *)(GLsizei, const void *))IntGetProcAddress("glEdgeFlagPointer"); + if(!_ptrc_glEdgeFlagPointer) numFailed++; + _ptrc_glEnableClientState = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glEnableClientState"); + if(!_ptrc_glEnableClientState) numFailed++; + _ptrc_glGenTextures = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenTextures"); + if(!_ptrc_glGenTextures) numFailed++; + _ptrc_glGetPointerv = (void (CODEGEN_FUNCPTR *)(GLenum, void **))IntGetProcAddress("glGetPointerv"); + if(!_ptrc_glGetPointerv) numFailed++; + _ptrc_glIndexPointer = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const void *))IntGetProcAddress("glIndexPointer"); + if(!_ptrc_glIndexPointer) numFailed++; + _ptrc_glIndexub = (void (CODEGEN_FUNCPTR *)(GLubyte))IntGetProcAddress("glIndexub"); + if(!_ptrc_glIndexub) numFailed++; + _ptrc_glIndexubv = (void (CODEGEN_FUNCPTR *)(const GLubyte *))IntGetProcAddress("glIndexubv"); + if(!_ptrc_glIndexubv) numFailed++; + _ptrc_glInterleavedArrays = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const void *))IntGetProcAddress("glInterleavedArrays"); + if(!_ptrc_glInterleavedArrays) numFailed++; + _ptrc_glIsTexture = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsTexture"); + if(!_ptrc_glIsTexture) numFailed++; + _ptrc_glNormalPointer = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const void *))IntGetProcAddress("glNormalPointer"); + if(!_ptrc_glNormalPointer) numFailed++; + _ptrc_glPolygonOffset = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glPolygonOffset"); + if(!_ptrc_glPolygonOffset) numFailed++; + _ptrc_glPopClientAttrib = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glPopClientAttrib"); + if(!_ptrc_glPopClientAttrib) numFailed++; + _ptrc_glPrioritizeTextures = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *, const GLfloat *))IntGetProcAddress("glPrioritizeTextures"); + if(!_ptrc_glPrioritizeTextures) numFailed++; + _ptrc_glPushClientAttrib = (void (CODEGEN_FUNCPTR *)(GLbitfield))IntGetProcAddress("glPushClientAttrib"); + if(!_ptrc_glPushClientAttrib) numFailed++; + _ptrc_glTexCoordPointer = (void (CODEGEN_FUNCPTR *)(GLint, GLenum, GLsizei, const void *))IntGetProcAddress("glTexCoordPointer"); + if(!_ptrc_glTexCoordPointer) numFailed++; + _ptrc_glTexSubImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const void *))IntGetProcAddress("glTexSubImage1D"); + if(!_ptrc_glTexSubImage1D) numFailed++; + _ptrc_glTexSubImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *))IntGetProcAddress("glTexSubImage2D"); + if(!_ptrc_glTexSubImage2D) numFailed++; + _ptrc_glVertexPointer = (void (CODEGEN_FUNCPTR *)(GLint, GLenum, GLsizei, const void *))IntGetProcAddress("glVertexPointer"); + if(!_ptrc_glVertexPointer) numFailed++; + _ptrc_glCopyTexSubImage3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei))IntGetProcAddress("glCopyTexSubImage3D"); + if(!_ptrc_glCopyTexSubImage3D) numFailed++; + _ptrc_glDrawRangeElements = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLuint, GLsizei, GLenum, const void *))IntGetProcAddress("glDrawRangeElements"); + if(!_ptrc_glDrawRangeElements) numFailed++; + _ptrc_glTexImage3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *))IntGetProcAddress("glTexImage3D"); + if(!_ptrc_glTexImage3D) numFailed++; + _ptrc_glTexSubImage3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const void *))IntGetProcAddress("glTexSubImage3D"); + if(!_ptrc_glTexSubImage3D) numFailed++; + _ptrc_glActiveTexture = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glActiveTexture"); + if(!_ptrc_glActiveTexture) numFailed++; + _ptrc_glClientActiveTexture = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glClientActiveTexture"); + if(!_ptrc_glClientActiveTexture) numFailed++; + _ptrc_glCompressedTexImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage1D"); + if(!_ptrc_glCompressedTexImage1D) numFailed++; + _ptrc_glCompressedTexImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage2D"); + if(!_ptrc_glCompressedTexImage2D) numFailed++; + _ptrc_glCompressedTexImage3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const void *))IntGetProcAddress("glCompressedTexImage3D"); + if(!_ptrc_glCompressedTexImage3D) numFailed++; + _ptrc_glCompressedTexSubImage1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage1D"); + if(!_ptrc_glCompressedTexSubImage1D) numFailed++; + _ptrc_glCompressedTexSubImage2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage2D"); + if(!_ptrc_glCompressedTexSubImage2D) numFailed++; + _ptrc_glCompressedTexSubImage3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const void *))IntGetProcAddress("glCompressedTexSubImage3D"); + if(!_ptrc_glCompressedTexSubImage3D) numFailed++; + _ptrc_glGetCompressedTexImage = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, void *))IntGetProcAddress("glGetCompressedTexImage"); + if(!_ptrc_glGetCompressedTexImage) numFailed++; + _ptrc_glLoadTransposeMatrixd = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glLoadTransposeMatrixd"); + if(!_ptrc_glLoadTransposeMatrixd) numFailed++; + _ptrc_glLoadTransposeMatrixf = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glLoadTransposeMatrixf"); + if(!_ptrc_glLoadTransposeMatrixf) numFailed++; + _ptrc_glMultTransposeMatrixd = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glMultTransposeMatrixd"); + if(!_ptrc_glMultTransposeMatrixd) numFailed++; + _ptrc_glMultTransposeMatrixf = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glMultTransposeMatrixf"); + if(!_ptrc_glMultTransposeMatrixf) numFailed++; + _ptrc_glMultiTexCoord1d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble))IntGetProcAddress("glMultiTexCoord1d"); + if(!_ptrc_glMultiTexCoord1d) numFailed++; + _ptrc_glMultiTexCoord1dv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLdouble *))IntGetProcAddress("glMultiTexCoord1dv"); + if(!_ptrc_glMultiTexCoord1dv) numFailed++; + _ptrc_glMultiTexCoord1f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glMultiTexCoord1f"); + if(!_ptrc_glMultiTexCoord1f) numFailed++; + _ptrc_glMultiTexCoord1fv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glMultiTexCoord1fv"); + if(!_ptrc_glMultiTexCoord1fv) numFailed++; + _ptrc_glMultiTexCoord1i = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glMultiTexCoord1i"); + if(!_ptrc_glMultiTexCoord1i) numFailed++; + _ptrc_glMultiTexCoord1iv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glMultiTexCoord1iv"); + if(!_ptrc_glMultiTexCoord1iv) numFailed++; + _ptrc_glMultiTexCoord1s = (void (CODEGEN_FUNCPTR *)(GLenum, GLshort))IntGetProcAddress("glMultiTexCoord1s"); + if(!_ptrc_glMultiTexCoord1s) numFailed++; + _ptrc_glMultiTexCoord1sv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLshort *))IntGetProcAddress("glMultiTexCoord1sv"); + if(!_ptrc_glMultiTexCoord1sv) numFailed++; + _ptrc_glMultiTexCoord2d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble, GLdouble))IntGetProcAddress("glMultiTexCoord2d"); + if(!_ptrc_glMultiTexCoord2d) numFailed++; + _ptrc_glMultiTexCoord2dv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLdouble *))IntGetProcAddress("glMultiTexCoord2dv"); + if(!_ptrc_glMultiTexCoord2dv) numFailed++; + _ptrc_glMultiTexCoord2f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat, GLfloat))IntGetProcAddress("glMultiTexCoord2f"); + if(!_ptrc_glMultiTexCoord2f) numFailed++; + _ptrc_glMultiTexCoord2fv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glMultiTexCoord2fv"); + if(!_ptrc_glMultiTexCoord2fv) numFailed++; + _ptrc_glMultiTexCoord2i = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint))IntGetProcAddress("glMultiTexCoord2i"); + if(!_ptrc_glMultiTexCoord2i) numFailed++; + _ptrc_glMultiTexCoord2iv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glMultiTexCoord2iv"); + if(!_ptrc_glMultiTexCoord2iv) numFailed++; + _ptrc_glMultiTexCoord2s = (void (CODEGEN_FUNCPTR *)(GLenum, GLshort, GLshort))IntGetProcAddress("glMultiTexCoord2s"); + if(!_ptrc_glMultiTexCoord2s) numFailed++; + _ptrc_glMultiTexCoord2sv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLshort *))IntGetProcAddress("glMultiTexCoord2sv"); + if(!_ptrc_glMultiTexCoord2sv) numFailed++; + _ptrc_glMultiTexCoord3d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glMultiTexCoord3d"); + if(!_ptrc_glMultiTexCoord3d) numFailed++; + _ptrc_glMultiTexCoord3dv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLdouble *))IntGetProcAddress("glMultiTexCoord3dv"); + if(!_ptrc_glMultiTexCoord3dv) numFailed++; + _ptrc_glMultiTexCoord3f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glMultiTexCoord3f"); + if(!_ptrc_glMultiTexCoord3f) numFailed++; + _ptrc_glMultiTexCoord3fv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glMultiTexCoord3fv"); + if(!_ptrc_glMultiTexCoord3fv) numFailed++; + _ptrc_glMultiTexCoord3i = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint))IntGetProcAddress("glMultiTexCoord3i"); + if(!_ptrc_glMultiTexCoord3i) numFailed++; + _ptrc_glMultiTexCoord3iv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glMultiTexCoord3iv"); + if(!_ptrc_glMultiTexCoord3iv) numFailed++; + _ptrc_glMultiTexCoord3s = (void (CODEGEN_FUNCPTR *)(GLenum, GLshort, GLshort, GLshort))IntGetProcAddress("glMultiTexCoord3s"); + if(!_ptrc_glMultiTexCoord3s) numFailed++; + _ptrc_glMultiTexCoord3sv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLshort *))IntGetProcAddress("glMultiTexCoord3sv"); + if(!_ptrc_glMultiTexCoord3sv) numFailed++; + _ptrc_glMultiTexCoord4d = (void (CODEGEN_FUNCPTR *)(GLenum, GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glMultiTexCoord4d"); + if(!_ptrc_glMultiTexCoord4d) numFailed++; + _ptrc_glMultiTexCoord4dv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLdouble *))IntGetProcAddress("glMultiTexCoord4dv"); + if(!_ptrc_glMultiTexCoord4dv) numFailed++; + _ptrc_glMultiTexCoord4f = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glMultiTexCoord4f"); + if(!_ptrc_glMultiTexCoord4f) numFailed++; + _ptrc_glMultiTexCoord4fv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glMultiTexCoord4fv"); + if(!_ptrc_glMultiTexCoord4fv) numFailed++; + _ptrc_glMultiTexCoord4i = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLint, GLint, GLint))IntGetProcAddress("glMultiTexCoord4i"); + if(!_ptrc_glMultiTexCoord4i) numFailed++; + _ptrc_glMultiTexCoord4iv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glMultiTexCoord4iv"); + if(!_ptrc_glMultiTexCoord4iv) numFailed++; + _ptrc_glMultiTexCoord4s = (void (CODEGEN_FUNCPTR *)(GLenum, GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glMultiTexCoord4s"); + if(!_ptrc_glMultiTexCoord4s) numFailed++; + _ptrc_glMultiTexCoord4sv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLshort *))IntGetProcAddress("glMultiTexCoord4sv"); + if(!_ptrc_glMultiTexCoord4sv) numFailed++; + _ptrc_glSampleCoverage = (void (CODEGEN_FUNCPTR *)(GLfloat, GLboolean))IntGetProcAddress("glSampleCoverage"); + if(!_ptrc_glSampleCoverage) numFailed++; + _ptrc_glBlendColor = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glBlendColor"); + if(!_ptrc_glBlendColor) numFailed++; + _ptrc_glBlendEquation = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glBlendEquation"); + if(!_ptrc_glBlendEquation) numFailed++; + _ptrc_glBlendFuncSeparate = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLenum))IntGetProcAddress("glBlendFuncSeparate"); + if(!_ptrc_glBlendFuncSeparate) numFailed++; + _ptrc_glFogCoordPointer = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, const void *))IntGetProcAddress("glFogCoordPointer"); + if(!_ptrc_glFogCoordPointer) numFailed++; + _ptrc_glFogCoordd = (void (CODEGEN_FUNCPTR *)(GLdouble))IntGetProcAddress("glFogCoordd"); + if(!_ptrc_glFogCoordd) numFailed++; + _ptrc_glFogCoorddv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glFogCoorddv"); + if(!_ptrc_glFogCoorddv) numFailed++; + _ptrc_glFogCoordf = (void (CODEGEN_FUNCPTR *)(GLfloat))IntGetProcAddress("glFogCoordf"); + if(!_ptrc_glFogCoordf) numFailed++; + _ptrc_glFogCoordfv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glFogCoordfv"); + if(!_ptrc_glFogCoordfv) numFailed++; + _ptrc_glMultiDrawArrays = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *, const GLsizei *, GLsizei))IntGetProcAddress("glMultiDrawArrays"); + if(!_ptrc_glMultiDrawArrays) numFailed++; + _ptrc_glMultiDrawElements = (void (CODEGEN_FUNCPTR *)(GLenum, const GLsizei *, GLenum, const void *const*, GLsizei))IntGetProcAddress("glMultiDrawElements"); + if(!_ptrc_glMultiDrawElements) numFailed++; + _ptrc_glPointParameterf = (void (CODEGEN_FUNCPTR *)(GLenum, GLfloat))IntGetProcAddress("glPointParameterf"); + if(!_ptrc_glPointParameterf) numFailed++; + _ptrc_glPointParameterfv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLfloat *))IntGetProcAddress("glPointParameterfv"); + if(!_ptrc_glPointParameterfv) numFailed++; + _ptrc_glPointParameteri = (void (CODEGEN_FUNCPTR *)(GLenum, GLint))IntGetProcAddress("glPointParameteri"); + if(!_ptrc_glPointParameteri) numFailed++; + _ptrc_glPointParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, const GLint *))IntGetProcAddress("glPointParameteriv"); + if(!_ptrc_glPointParameteriv) numFailed++; + _ptrc_glSecondaryColor3b = (void (CODEGEN_FUNCPTR *)(GLbyte, GLbyte, GLbyte))IntGetProcAddress("glSecondaryColor3b"); + if(!_ptrc_glSecondaryColor3b) numFailed++; + _ptrc_glSecondaryColor3bv = (void (CODEGEN_FUNCPTR *)(const GLbyte *))IntGetProcAddress("glSecondaryColor3bv"); + if(!_ptrc_glSecondaryColor3bv) numFailed++; + _ptrc_glSecondaryColor3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glSecondaryColor3d"); + if(!_ptrc_glSecondaryColor3d) numFailed++; + _ptrc_glSecondaryColor3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glSecondaryColor3dv"); + if(!_ptrc_glSecondaryColor3dv) numFailed++; + _ptrc_glSecondaryColor3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glSecondaryColor3f"); + if(!_ptrc_glSecondaryColor3f) numFailed++; + _ptrc_glSecondaryColor3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glSecondaryColor3fv"); + if(!_ptrc_glSecondaryColor3fv) numFailed++; + _ptrc_glSecondaryColor3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glSecondaryColor3i"); + if(!_ptrc_glSecondaryColor3i) numFailed++; + _ptrc_glSecondaryColor3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glSecondaryColor3iv"); + if(!_ptrc_glSecondaryColor3iv) numFailed++; + _ptrc_glSecondaryColor3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glSecondaryColor3s"); + if(!_ptrc_glSecondaryColor3s) numFailed++; + _ptrc_glSecondaryColor3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glSecondaryColor3sv"); + if(!_ptrc_glSecondaryColor3sv) numFailed++; + _ptrc_glSecondaryColor3ub = (void (CODEGEN_FUNCPTR *)(GLubyte, GLubyte, GLubyte))IntGetProcAddress("glSecondaryColor3ub"); + if(!_ptrc_glSecondaryColor3ub) numFailed++; + _ptrc_glSecondaryColor3ubv = (void (CODEGEN_FUNCPTR *)(const GLubyte *))IntGetProcAddress("glSecondaryColor3ubv"); + if(!_ptrc_glSecondaryColor3ubv) numFailed++; + _ptrc_glSecondaryColor3ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint))IntGetProcAddress("glSecondaryColor3ui"); + if(!_ptrc_glSecondaryColor3ui) numFailed++; + _ptrc_glSecondaryColor3uiv = (void (CODEGEN_FUNCPTR *)(const GLuint *))IntGetProcAddress("glSecondaryColor3uiv"); + if(!_ptrc_glSecondaryColor3uiv) numFailed++; + _ptrc_glSecondaryColor3us = (void (CODEGEN_FUNCPTR *)(GLushort, GLushort, GLushort))IntGetProcAddress("glSecondaryColor3us"); + if(!_ptrc_glSecondaryColor3us) numFailed++; + _ptrc_glSecondaryColor3usv = (void (CODEGEN_FUNCPTR *)(const GLushort *))IntGetProcAddress("glSecondaryColor3usv"); + if(!_ptrc_glSecondaryColor3usv) numFailed++; + _ptrc_glSecondaryColorPointer = (void (CODEGEN_FUNCPTR *)(GLint, GLenum, GLsizei, const void *))IntGetProcAddress("glSecondaryColorPointer"); + if(!_ptrc_glSecondaryColorPointer) numFailed++; + _ptrc_glWindowPos2d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble))IntGetProcAddress("glWindowPos2d"); + if(!_ptrc_glWindowPos2d) numFailed++; + _ptrc_glWindowPos2dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glWindowPos2dv"); + if(!_ptrc_glWindowPos2dv) numFailed++; + _ptrc_glWindowPos2f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat))IntGetProcAddress("glWindowPos2f"); + if(!_ptrc_glWindowPos2f) numFailed++; + _ptrc_glWindowPos2fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glWindowPos2fv"); + if(!_ptrc_glWindowPos2fv) numFailed++; + _ptrc_glWindowPos2i = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glWindowPos2i"); + if(!_ptrc_glWindowPos2i) numFailed++; + _ptrc_glWindowPos2iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glWindowPos2iv"); + if(!_ptrc_glWindowPos2iv) numFailed++; + _ptrc_glWindowPos2s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort))IntGetProcAddress("glWindowPos2s"); + if(!_ptrc_glWindowPos2s) numFailed++; + _ptrc_glWindowPos2sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glWindowPos2sv"); + if(!_ptrc_glWindowPos2sv) numFailed++; + _ptrc_glWindowPos3d = (void (CODEGEN_FUNCPTR *)(GLdouble, GLdouble, GLdouble))IntGetProcAddress("glWindowPos3d"); + if(!_ptrc_glWindowPos3d) numFailed++; + _ptrc_glWindowPos3dv = (void (CODEGEN_FUNCPTR *)(const GLdouble *))IntGetProcAddress("glWindowPos3dv"); + if(!_ptrc_glWindowPos3dv) numFailed++; + _ptrc_glWindowPos3f = (void (CODEGEN_FUNCPTR *)(GLfloat, GLfloat, GLfloat))IntGetProcAddress("glWindowPos3f"); + if(!_ptrc_glWindowPos3f) numFailed++; + _ptrc_glWindowPos3fv = (void (CODEGEN_FUNCPTR *)(const GLfloat *))IntGetProcAddress("glWindowPos3fv"); + if(!_ptrc_glWindowPos3fv) numFailed++; + _ptrc_glWindowPos3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glWindowPos3i"); + if(!_ptrc_glWindowPos3i) numFailed++; + _ptrc_glWindowPos3iv = (void (CODEGEN_FUNCPTR *)(const GLint *))IntGetProcAddress("glWindowPos3iv"); + if(!_ptrc_glWindowPos3iv) numFailed++; + _ptrc_glWindowPos3s = (void (CODEGEN_FUNCPTR *)(GLshort, GLshort, GLshort))IntGetProcAddress("glWindowPos3s"); + if(!_ptrc_glWindowPos3s) numFailed++; + _ptrc_glWindowPos3sv = (void (CODEGEN_FUNCPTR *)(const GLshort *))IntGetProcAddress("glWindowPos3sv"); + if(!_ptrc_glWindowPos3sv) numFailed++; + _ptrc_glBeginQuery = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBeginQuery"); + if(!_ptrc_glBeginQuery) numFailed++; + _ptrc_glBindBuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindBuffer"); + if(!_ptrc_glBindBuffer) numFailed++; + _ptrc_glBufferData = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizeiptr, const void *, GLenum))IntGetProcAddress("glBufferData"); + if(!_ptrc_glBufferData) numFailed++; + _ptrc_glBufferSubData = (void (CODEGEN_FUNCPTR *)(GLenum, GLintptr, GLsizeiptr, const void *))IntGetProcAddress("glBufferSubData"); + if(!_ptrc_glBufferSubData) numFailed++; + _ptrc_glDeleteBuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteBuffers"); + if(!_ptrc_glDeleteBuffers) numFailed++; + _ptrc_glDeleteQueries = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteQueries"); + if(!_ptrc_glDeleteQueries) numFailed++; + _ptrc_glEndQuery = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glEndQuery"); + if(!_ptrc_glEndQuery) numFailed++; + _ptrc_glGenBuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenBuffers"); + if(!_ptrc_glGenBuffers) numFailed++; + _ptrc_glGenQueries = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenQueries"); + if(!_ptrc_glGenQueries) numFailed++; + _ptrc_glGetBufferParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetBufferParameteriv"); + if(!_ptrc_glGetBufferParameteriv) numFailed++; + _ptrc_glGetBufferPointerv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, void **))IntGetProcAddress("glGetBufferPointerv"); + if(!_ptrc_glGetBufferPointerv) numFailed++; + _ptrc_glGetBufferSubData = (void (CODEGEN_FUNCPTR *)(GLenum, GLintptr, GLsizeiptr, void *))IntGetProcAddress("glGetBufferSubData"); + if(!_ptrc_glGetBufferSubData) numFailed++; + _ptrc_glGetQueryObjectiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetQueryObjectiv"); + if(!_ptrc_glGetQueryObjectiv) numFailed++; + _ptrc_glGetQueryObjectuiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLuint *))IntGetProcAddress("glGetQueryObjectuiv"); + if(!_ptrc_glGetQueryObjectuiv) numFailed++; + _ptrc_glGetQueryiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetQueryiv"); + if(!_ptrc_glGetQueryiv) numFailed++; + _ptrc_glIsBuffer = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsBuffer"); + if(!_ptrc_glIsBuffer) numFailed++; + _ptrc_glIsQuery = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsQuery"); + if(!_ptrc_glIsQuery) numFailed++; + _ptrc_glMapBuffer = (void * (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glMapBuffer"); + if(!_ptrc_glMapBuffer) numFailed++; + _ptrc_glUnmapBuffer = (GLboolean (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glUnmapBuffer"); + if(!_ptrc_glUnmapBuffer) numFailed++; + _ptrc_glAttachShader = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint))IntGetProcAddress("glAttachShader"); + if(!_ptrc_glAttachShader) numFailed++; + _ptrc_glBindAttribLocation = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, const GLchar *))IntGetProcAddress("glBindAttribLocation"); + if(!_ptrc_glBindAttribLocation) numFailed++; + _ptrc_glBlendEquationSeparate = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glBlendEquationSeparate"); + if(!_ptrc_glBlendEquationSeparate) numFailed++; + _ptrc_glCompileShader = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glCompileShader"); + if(!_ptrc_glCompileShader) numFailed++; + _ptrc_glCreateProgram = (GLuint (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glCreateProgram"); + if(!_ptrc_glCreateProgram) numFailed++; + _ptrc_glCreateShader = (GLuint (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glCreateShader"); + if(!_ptrc_glCreateShader) numFailed++; + _ptrc_glDeleteProgram = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glDeleteProgram"); + if(!_ptrc_glDeleteProgram) numFailed++; + _ptrc_glDeleteShader = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glDeleteShader"); + if(!_ptrc_glDeleteShader) numFailed++; + _ptrc_glDetachShader = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint))IntGetProcAddress("glDetachShader"); + if(!_ptrc_glDetachShader) numFailed++; + _ptrc_glDisableVertexAttribArray = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glDisableVertexAttribArray"); + if(!_ptrc_glDisableVertexAttribArray) numFailed++; + _ptrc_glDrawBuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLenum *))IntGetProcAddress("glDrawBuffers"); + if(!_ptrc_glDrawBuffers) numFailed++; + _ptrc_glEnableVertexAttribArray = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glEnableVertexAttribArray"); + if(!_ptrc_glEnableVertexAttribArray) numFailed++; + _ptrc_glGetActiveAttrib = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *))IntGetProcAddress("glGetActiveAttrib"); + if(!_ptrc_glGetActiveAttrib) numFailed++; + _ptrc_glGetActiveUniform = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *))IntGetProcAddress("glGetActiveUniform"); + if(!_ptrc_glGetActiveUniform) numFailed++; + _ptrc_glGetAttachedShaders = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, GLsizei *, GLuint *))IntGetProcAddress("glGetAttachedShaders"); + if(!_ptrc_glGetAttachedShaders) numFailed++; + _ptrc_glGetAttribLocation = (GLint (CODEGEN_FUNCPTR *)(GLuint, const GLchar *))IntGetProcAddress("glGetAttribLocation"); + if(!_ptrc_glGetAttribLocation) numFailed++; + _ptrc_glGetProgramInfoLog = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetProgramInfoLog"); + if(!_ptrc_glGetProgramInfoLog) numFailed++; + _ptrc_glGetProgramiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetProgramiv"); + if(!_ptrc_glGetProgramiv) numFailed++; + _ptrc_glGetShaderInfoLog = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetShaderInfoLog"); + if(!_ptrc_glGetShaderInfoLog) numFailed++; + _ptrc_glGetShaderSource = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetShaderSource"); + if(!_ptrc_glGetShaderSource) numFailed++; + _ptrc_glGetShaderiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetShaderiv"); + if(!_ptrc_glGetShaderiv) numFailed++; + _ptrc_glGetUniformLocation = (GLint (CODEGEN_FUNCPTR *)(GLuint, const GLchar *))IntGetProcAddress("glGetUniformLocation"); + if(!_ptrc_glGetUniformLocation) numFailed++; + _ptrc_glGetUniformfv = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLfloat *))IntGetProcAddress("glGetUniformfv"); + if(!_ptrc_glGetUniformfv) numFailed++; + _ptrc_glGetUniformiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLint *))IntGetProcAddress("glGetUniformiv"); + if(!_ptrc_glGetUniformiv) numFailed++; + _ptrc_glGetVertexAttribPointerv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, void **))IntGetProcAddress("glGetVertexAttribPointerv"); + if(!_ptrc_glGetVertexAttribPointerv) numFailed++; + _ptrc_glGetVertexAttribdv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLdouble *))IntGetProcAddress("glGetVertexAttribdv"); + if(!_ptrc_glGetVertexAttribdv) numFailed++; + _ptrc_glGetVertexAttribfv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLfloat *))IntGetProcAddress("glGetVertexAttribfv"); + if(!_ptrc_glGetVertexAttribfv) numFailed++; + _ptrc_glGetVertexAttribiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetVertexAttribiv"); + if(!_ptrc_glGetVertexAttribiv) numFailed++; + _ptrc_glIsProgram = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsProgram"); + if(!_ptrc_glIsProgram) numFailed++; + _ptrc_glIsShader = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsShader"); + if(!_ptrc_glIsShader) numFailed++; + _ptrc_glLinkProgram = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glLinkProgram"); + if(!_ptrc_glLinkProgram) numFailed++; + _ptrc_glShaderSource = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, const GLchar *const*, const GLint *))IntGetProcAddress("glShaderSource"); + if(!_ptrc_glShaderSource) numFailed++; + _ptrc_glStencilFuncSeparate = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint, GLuint))IntGetProcAddress("glStencilFuncSeparate"); + if(!_ptrc_glStencilFuncSeparate) numFailed++; + _ptrc_glStencilMaskSeparate = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glStencilMaskSeparate"); + if(!_ptrc_glStencilMaskSeparate) numFailed++; + _ptrc_glStencilOpSeparate = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLenum))IntGetProcAddress("glStencilOpSeparate"); + if(!_ptrc_glStencilOpSeparate) numFailed++; + _ptrc_glUniform1f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat))IntGetProcAddress("glUniform1f"); + if(!_ptrc_glUniform1f) numFailed++; + _ptrc_glUniform1fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLfloat *))IntGetProcAddress("glUniform1fv"); + if(!_ptrc_glUniform1fv) numFailed++; + _ptrc_glUniform1i = (void (CODEGEN_FUNCPTR *)(GLint, GLint))IntGetProcAddress("glUniform1i"); + if(!_ptrc_glUniform1i) numFailed++; + _ptrc_glUniform1iv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLint *))IntGetProcAddress("glUniform1iv"); + if(!_ptrc_glUniform1iv) numFailed++; + _ptrc_glUniform2f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat, GLfloat))IntGetProcAddress("glUniform2f"); + if(!_ptrc_glUniform2f) numFailed++; + _ptrc_glUniform2fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLfloat *))IntGetProcAddress("glUniform2fv"); + if(!_ptrc_glUniform2fv) numFailed++; + _ptrc_glUniform2i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint))IntGetProcAddress("glUniform2i"); + if(!_ptrc_glUniform2i) numFailed++; + _ptrc_glUniform2iv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLint *))IntGetProcAddress("glUniform2iv"); + if(!_ptrc_glUniform2iv) numFailed++; + _ptrc_glUniform3f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glUniform3f"); + if(!_ptrc_glUniform3f) numFailed++; + _ptrc_glUniform3fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLfloat *))IntGetProcAddress("glUniform3fv"); + if(!_ptrc_glUniform3fv) numFailed++; + _ptrc_glUniform3i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint))IntGetProcAddress("glUniform3i"); + if(!_ptrc_glUniform3i) numFailed++; + _ptrc_glUniform3iv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLint *))IntGetProcAddress("glUniform3iv"); + if(!_ptrc_glUniform3iv) numFailed++; + _ptrc_glUniform4f = (void (CODEGEN_FUNCPTR *)(GLint, GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glUniform4f"); + if(!_ptrc_glUniform4f) numFailed++; + _ptrc_glUniform4fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLfloat *))IntGetProcAddress("glUniform4fv"); + if(!_ptrc_glUniform4fv) numFailed++; + _ptrc_glUniform4i = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint, GLint))IntGetProcAddress("glUniform4i"); + if(!_ptrc_glUniform4i) numFailed++; + _ptrc_glUniform4iv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLint *))IntGetProcAddress("glUniform4iv"); + if(!_ptrc_glUniform4iv) numFailed++; + _ptrc_glUniformMatrix2fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix2fv"); + if(!_ptrc_glUniformMatrix2fv) numFailed++; + _ptrc_glUniformMatrix3fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix3fv"); + if(!_ptrc_glUniformMatrix3fv) numFailed++; + _ptrc_glUniformMatrix4fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix4fv"); + if(!_ptrc_glUniformMatrix4fv) numFailed++; + _ptrc_glUseProgram = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glUseProgram"); + if(!_ptrc_glUseProgram) numFailed++; + _ptrc_glValidateProgram = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glValidateProgram"); + if(!_ptrc_glValidateProgram) numFailed++; + _ptrc_glVertexAttrib1d = (void (CODEGEN_FUNCPTR *)(GLuint, GLdouble))IntGetProcAddress("glVertexAttrib1d"); + if(!_ptrc_glVertexAttrib1d) numFailed++; + _ptrc_glVertexAttrib1dv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLdouble *))IntGetProcAddress("glVertexAttrib1dv"); + if(!_ptrc_glVertexAttrib1dv) numFailed++; + _ptrc_glVertexAttrib1f = (void (CODEGEN_FUNCPTR *)(GLuint, GLfloat))IntGetProcAddress("glVertexAttrib1f"); + if(!_ptrc_glVertexAttrib1f) numFailed++; + _ptrc_glVertexAttrib1fv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLfloat *))IntGetProcAddress("glVertexAttrib1fv"); + if(!_ptrc_glVertexAttrib1fv) numFailed++; + _ptrc_glVertexAttrib1s = (void (CODEGEN_FUNCPTR *)(GLuint, GLshort))IntGetProcAddress("glVertexAttrib1s"); + if(!_ptrc_glVertexAttrib1s) numFailed++; + _ptrc_glVertexAttrib1sv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttrib1sv"); + if(!_ptrc_glVertexAttrib1sv) numFailed++; + _ptrc_glVertexAttrib2d = (void (CODEGEN_FUNCPTR *)(GLuint, GLdouble, GLdouble))IntGetProcAddress("glVertexAttrib2d"); + if(!_ptrc_glVertexAttrib2d) numFailed++; + _ptrc_glVertexAttrib2dv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLdouble *))IntGetProcAddress("glVertexAttrib2dv"); + if(!_ptrc_glVertexAttrib2dv) numFailed++; + _ptrc_glVertexAttrib2f = (void (CODEGEN_FUNCPTR *)(GLuint, GLfloat, GLfloat))IntGetProcAddress("glVertexAttrib2f"); + if(!_ptrc_glVertexAttrib2f) numFailed++; + _ptrc_glVertexAttrib2fv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLfloat *))IntGetProcAddress("glVertexAttrib2fv"); + if(!_ptrc_glVertexAttrib2fv) numFailed++; + _ptrc_glVertexAttrib2s = (void (CODEGEN_FUNCPTR *)(GLuint, GLshort, GLshort))IntGetProcAddress("glVertexAttrib2s"); + if(!_ptrc_glVertexAttrib2s) numFailed++; + _ptrc_glVertexAttrib2sv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttrib2sv"); + if(!_ptrc_glVertexAttrib2sv) numFailed++; + _ptrc_glVertexAttrib3d = (void (CODEGEN_FUNCPTR *)(GLuint, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glVertexAttrib3d"); + if(!_ptrc_glVertexAttrib3d) numFailed++; + _ptrc_glVertexAttrib3dv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLdouble *))IntGetProcAddress("glVertexAttrib3dv"); + if(!_ptrc_glVertexAttrib3dv) numFailed++; + _ptrc_glVertexAttrib3f = (void (CODEGEN_FUNCPTR *)(GLuint, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glVertexAttrib3f"); + if(!_ptrc_glVertexAttrib3f) numFailed++; + _ptrc_glVertexAttrib3fv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLfloat *))IntGetProcAddress("glVertexAttrib3fv"); + if(!_ptrc_glVertexAttrib3fv) numFailed++; + _ptrc_glVertexAttrib3s = (void (CODEGEN_FUNCPTR *)(GLuint, GLshort, GLshort, GLshort))IntGetProcAddress("glVertexAttrib3s"); + if(!_ptrc_glVertexAttrib3s) numFailed++; + _ptrc_glVertexAttrib3sv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttrib3sv"); + if(!_ptrc_glVertexAttrib3sv) numFailed++; + _ptrc_glVertexAttrib4Nbv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLbyte *))IntGetProcAddress("glVertexAttrib4Nbv"); + if(!_ptrc_glVertexAttrib4Nbv) numFailed++; + _ptrc_glVertexAttrib4Niv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttrib4Niv"); + if(!_ptrc_glVertexAttrib4Niv) numFailed++; + _ptrc_glVertexAttrib4Nsv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttrib4Nsv"); + if(!_ptrc_glVertexAttrib4Nsv) numFailed++; + _ptrc_glVertexAttrib4Nub = (void (CODEGEN_FUNCPTR *)(GLuint, GLubyte, GLubyte, GLubyte, GLubyte))IntGetProcAddress("glVertexAttrib4Nub"); + if(!_ptrc_glVertexAttrib4Nub) numFailed++; + _ptrc_glVertexAttrib4Nubv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLubyte *))IntGetProcAddress("glVertexAttrib4Nubv"); + if(!_ptrc_glVertexAttrib4Nubv) numFailed++; + _ptrc_glVertexAttrib4Nuiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttrib4Nuiv"); + if(!_ptrc_glVertexAttrib4Nuiv) numFailed++; + _ptrc_glVertexAttrib4Nusv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLushort *))IntGetProcAddress("glVertexAttrib4Nusv"); + if(!_ptrc_glVertexAttrib4Nusv) numFailed++; + _ptrc_glVertexAttrib4bv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLbyte *))IntGetProcAddress("glVertexAttrib4bv"); + if(!_ptrc_glVertexAttrib4bv) numFailed++; + _ptrc_glVertexAttrib4d = (void (CODEGEN_FUNCPTR *)(GLuint, GLdouble, GLdouble, GLdouble, GLdouble))IntGetProcAddress("glVertexAttrib4d"); + if(!_ptrc_glVertexAttrib4d) numFailed++; + _ptrc_glVertexAttrib4dv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLdouble *))IntGetProcAddress("glVertexAttrib4dv"); + if(!_ptrc_glVertexAttrib4dv) numFailed++; + _ptrc_glVertexAttrib4f = (void (CODEGEN_FUNCPTR *)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat))IntGetProcAddress("glVertexAttrib4f"); + if(!_ptrc_glVertexAttrib4f) numFailed++; + _ptrc_glVertexAttrib4fv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLfloat *))IntGetProcAddress("glVertexAttrib4fv"); + if(!_ptrc_glVertexAttrib4fv) numFailed++; + _ptrc_glVertexAttrib4iv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttrib4iv"); + if(!_ptrc_glVertexAttrib4iv) numFailed++; + _ptrc_glVertexAttrib4s = (void (CODEGEN_FUNCPTR *)(GLuint, GLshort, GLshort, GLshort, GLshort))IntGetProcAddress("glVertexAttrib4s"); + if(!_ptrc_glVertexAttrib4s) numFailed++; + _ptrc_glVertexAttrib4sv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttrib4sv"); + if(!_ptrc_glVertexAttrib4sv) numFailed++; + _ptrc_glVertexAttrib4ubv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLubyte *))IntGetProcAddress("glVertexAttrib4ubv"); + if(!_ptrc_glVertexAttrib4ubv) numFailed++; + _ptrc_glVertexAttrib4uiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttrib4uiv"); + if(!_ptrc_glVertexAttrib4uiv) numFailed++; + _ptrc_glVertexAttrib4usv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLushort *))IntGetProcAddress("glVertexAttrib4usv"); + if(!_ptrc_glVertexAttrib4usv) numFailed++; + _ptrc_glVertexAttribPointer = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *))IntGetProcAddress("glVertexAttribPointer"); + if(!_ptrc_glVertexAttribPointer) numFailed++; + _ptrc_glUniformMatrix2x3fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix2x3fv"); + if(!_ptrc_glUniformMatrix2x3fv) numFailed++; + _ptrc_glUniformMatrix2x4fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix2x4fv"); + if(!_ptrc_glUniformMatrix2x4fv) numFailed++; + _ptrc_glUniformMatrix3x2fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix3x2fv"); + if(!_ptrc_glUniformMatrix3x2fv) numFailed++; + _ptrc_glUniformMatrix3x4fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix3x4fv"); + if(!_ptrc_glUniformMatrix3x4fv) numFailed++; + _ptrc_glUniformMatrix4x2fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix4x2fv"); + if(!_ptrc_glUniformMatrix4x2fv) numFailed++; + _ptrc_glUniformMatrix4x3fv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, GLboolean, const GLfloat *))IntGetProcAddress("glUniformMatrix4x3fv"); + if(!_ptrc_glUniformMatrix4x3fv) numFailed++; + _ptrc_glBeginConditionalRender = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum))IntGetProcAddress("glBeginConditionalRender"); + if(!_ptrc_glBeginConditionalRender) numFailed++; + _ptrc_glBeginTransformFeedback = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glBeginTransformFeedback"); + if(!_ptrc_glBeginTransformFeedback) numFailed++; + _ptrc_glBindBufferBase = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLuint))IntGetProcAddress("glBindBufferBase"); + if(!_ptrc_glBindBufferBase) numFailed++; + _ptrc_glBindBufferRange = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr))IntGetProcAddress("glBindBufferRange"); + if(!_ptrc_glBindBufferRange) numFailed++; + _ptrc_glBindFragDataLocation = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, const GLchar *))IntGetProcAddress("glBindFragDataLocation"); + if(!_ptrc_glBindFragDataLocation) numFailed++; + _ptrc_glBindFramebuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindFramebuffer"); + if(!_ptrc_glBindFramebuffer) numFailed++; + _ptrc_glBindRenderbuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glBindRenderbuffer"); + if(!_ptrc_glBindRenderbuffer) numFailed++; + _ptrc_glBindVertexArray = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glBindVertexArray"); + if(!_ptrc_glBindVertexArray) numFailed++; + _ptrc_glBlitFramebuffer = (void (CODEGEN_FUNCPTR *)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum))IntGetProcAddress("glBlitFramebuffer"); + if(!_ptrc_glBlitFramebuffer) numFailed++; + _ptrc_glCheckFramebufferStatus = (GLenum (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glCheckFramebufferStatus"); + if(!_ptrc_glCheckFramebufferStatus) numFailed++; + _ptrc_glClampColor = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum))IntGetProcAddress("glClampColor"); + if(!_ptrc_glClampColor) numFailed++; + _ptrc_glClearBufferfi = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLfloat, GLint))IntGetProcAddress("glClearBufferfi"); + if(!_ptrc_glClearBufferfi) numFailed++; + _ptrc_glClearBufferfv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, const GLfloat *))IntGetProcAddress("glClearBufferfv"); + if(!_ptrc_glClearBufferfv) numFailed++; + _ptrc_glClearBufferiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, const GLint *))IntGetProcAddress("glClearBufferiv"); + if(!_ptrc_glClearBufferiv) numFailed++; + _ptrc_glClearBufferuiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, const GLuint *))IntGetProcAddress("glClearBufferuiv"); + if(!_ptrc_glClearBufferuiv) numFailed++; + _ptrc_glColorMaski = (void (CODEGEN_FUNCPTR *)(GLuint, GLboolean, GLboolean, GLboolean, GLboolean))IntGetProcAddress("glColorMaski"); + if(!_ptrc_glColorMaski) numFailed++; + _ptrc_glDeleteFramebuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteFramebuffers"); + if(!_ptrc_glDeleteFramebuffers) numFailed++; + _ptrc_glDeleteRenderbuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteRenderbuffers"); + if(!_ptrc_glDeleteRenderbuffers) numFailed++; + _ptrc_glDeleteVertexArrays = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteVertexArrays"); + if(!_ptrc_glDeleteVertexArrays) numFailed++; + _ptrc_glDisablei = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glDisablei"); + if(!_ptrc_glDisablei) numFailed++; + _ptrc_glEnablei = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glEnablei"); + if(!_ptrc_glEnablei) numFailed++; + _ptrc_glEndConditionalRender = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glEndConditionalRender"); + if(!_ptrc_glEndConditionalRender) numFailed++; + _ptrc_glEndTransformFeedback = (void (CODEGEN_FUNCPTR *)(void))IntGetProcAddress("glEndTransformFeedback"); + if(!_ptrc_glEndTransformFeedback) numFailed++; + _ptrc_glFlushMappedBufferRange = (void (CODEGEN_FUNCPTR *)(GLenum, GLintptr, GLsizeiptr))IntGetProcAddress("glFlushMappedBufferRange"); + if(!_ptrc_glFlushMappedBufferRange) numFailed++; + _ptrc_glFramebufferRenderbuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint))IntGetProcAddress("glFramebufferRenderbuffer"); + if(!_ptrc_glFramebufferRenderbuffer) numFailed++; + _ptrc_glFramebufferTexture1D = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint))IntGetProcAddress("glFramebufferTexture1D"); + if(!_ptrc_glFramebufferTexture1D) numFailed++; + _ptrc_glFramebufferTexture2D = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint))IntGetProcAddress("glFramebufferTexture2D"); + if(!_ptrc_glFramebufferTexture2D) numFailed++; + _ptrc_glFramebufferTexture3D = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLuint, GLint, GLint))IntGetProcAddress("glFramebufferTexture3D"); + if(!_ptrc_glFramebufferTexture3D) numFailed++; + _ptrc_glFramebufferTextureLayer = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLuint, GLint, GLint))IntGetProcAddress("glFramebufferTextureLayer"); + if(!_ptrc_glFramebufferTextureLayer) numFailed++; + _ptrc_glGenFramebuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenFramebuffers"); + if(!_ptrc_glGenFramebuffers) numFailed++; + _ptrc_glGenRenderbuffers = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenRenderbuffers"); + if(!_ptrc_glGenRenderbuffers) numFailed++; + _ptrc_glGenVertexArrays = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenVertexArrays"); + if(!_ptrc_glGenVertexArrays) numFailed++; + _ptrc_glGenerateMipmap = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glGenerateMipmap"); + if(!_ptrc_glGenerateMipmap) numFailed++; + _ptrc_glGetBooleani_v = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLboolean *))IntGetProcAddress("glGetBooleani_v"); + if(!_ptrc_glGetBooleani_v) numFailed++; + _ptrc_glGetFragDataLocation = (GLint (CODEGEN_FUNCPTR *)(GLuint, const GLchar *))IntGetProcAddress("glGetFragDataLocation"); + if(!_ptrc_glGetFragDataLocation) numFailed++; + _ptrc_glGetFramebufferAttachmentParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLenum, GLint *))IntGetProcAddress("glGetFramebufferAttachmentParameteriv"); + if(!_ptrc_glGetFramebufferAttachmentParameteriv) numFailed++; + _ptrc_glGetIntegeri_v = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLint *))IntGetProcAddress("glGetIntegeri_v"); + if(!_ptrc_glGetIntegeri_v) numFailed++; + _ptrc_glGetRenderbufferParameteriv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetRenderbufferParameteriv"); + if(!_ptrc_glGetRenderbufferParameteriv) numFailed++; + _ptrc_glGetStringi = (const GLubyte * (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glGetStringi"); + if(!_ptrc_glGetStringi) numFailed++; + _ptrc_glGetTexParameterIiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint *))IntGetProcAddress("glGetTexParameterIiv"); + if(!_ptrc_glGetTexParameterIiv) numFailed++; + _ptrc_glGetTexParameterIuiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLuint *))IntGetProcAddress("glGetTexParameterIuiv"); + if(!_ptrc_glGetTexParameterIuiv) numFailed++; + _ptrc_glGetTransformFeedbackVarying = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *))IntGetProcAddress("glGetTransformFeedbackVarying"); + if(!_ptrc_glGetTransformFeedbackVarying) numFailed++; + _ptrc_glGetUniformuiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLuint *))IntGetProcAddress("glGetUniformuiv"); + if(!_ptrc_glGetUniformuiv) numFailed++; + _ptrc_glGetVertexAttribIiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetVertexAttribIiv"); + if(!_ptrc_glGetVertexAttribIiv) numFailed++; + _ptrc_glGetVertexAttribIuiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLuint *))IntGetProcAddress("glGetVertexAttribIuiv"); + if(!_ptrc_glGetVertexAttribIuiv) numFailed++; + _ptrc_glIsEnabledi = (GLboolean (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glIsEnabledi"); + if(!_ptrc_glIsEnabledi) numFailed++; + _ptrc_glIsFramebuffer = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsFramebuffer"); + if(!_ptrc_glIsFramebuffer) numFailed++; + _ptrc_glIsRenderbuffer = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsRenderbuffer"); + if(!_ptrc_glIsRenderbuffer) numFailed++; + _ptrc_glIsVertexArray = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsVertexArray"); + if(!_ptrc_glIsVertexArray) numFailed++; + _ptrc_glMapBufferRange = (void * (CODEGEN_FUNCPTR *)(GLenum, GLintptr, GLsizeiptr, GLbitfield))IntGetProcAddress("glMapBufferRange"); + if(!_ptrc_glMapBufferRange) numFailed++; + _ptrc_glRenderbufferStorage = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLsizei, GLsizei))IntGetProcAddress("glRenderbufferStorage"); + if(!_ptrc_glRenderbufferStorage) numFailed++; + _ptrc_glRenderbufferStorageMultisample = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, GLsizei, GLsizei))IntGetProcAddress("glRenderbufferStorageMultisample"); + if(!_ptrc_glRenderbufferStorageMultisample) numFailed++; + _ptrc_glTexParameterIiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLint *))IntGetProcAddress("glTexParameterIiv"); + if(!_ptrc_glTexParameterIiv) numFailed++; + _ptrc_glTexParameterIuiv = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, const GLuint *))IntGetProcAddress("glTexParameterIuiv"); + if(!_ptrc_glTexParameterIuiv) numFailed++; + _ptrc_glTransformFeedbackVaryings = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, const GLchar *const*, GLenum))IntGetProcAddress("glTransformFeedbackVaryings"); + if(!_ptrc_glTransformFeedbackVaryings) numFailed++; + _ptrc_glUniform1ui = (void (CODEGEN_FUNCPTR *)(GLint, GLuint))IntGetProcAddress("glUniform1ui"); + if(!_ptrc_glUniform1ui) numFailed++; + _ptrc_glUniform1uiv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLuint *))IntGetProcAddress("glUniform1uiv"); + if(!_ptrc_glUniform1uiv) numFailed++; + _ptrc_glUniform2ui = (void (CODEGEN_FUNCPTR *)(GLint, GLuint, GLuint))IntGetProcAddress("glUniform2ui"); + if(!_ptrc_glUniform2ui) numFailed++; + _ptrc_glUniform2uiv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLuint *))IntGetProcAddress("glUniform2uiv"); + if(!_ptrc_glUniform2uiv) numFailed++; + _ptrc_glUniform3ui = (void (CODEGEN_FUNCPTR *)(GLint, GLuint, GLuint, GLuint))IntGetProcAddress("glUniform3ui"); + if(!_ptrc_glUniform3ui) numFailed++; + _ptrc_glUniform3uiv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLuint *))IntGetProcAddress("glUniform3uiv"); + if(!_ptrc_glUniform3uiv) numFailed++; + _ptrc_glUniform4ui = (void (CODEGEN_FUNCPTR *)(GLint, GLuint, GLuint, GLuint, GLuint))IntGetProcAddress("glUniform4ui"); + if(!_ptrc_glUniform4ui) numFailed++; + _ptrc_glUniform4uiv = (void (CODEGEN_FUNCPTR *)(GLint, GLsizei, const GLuint *))IntGetProcAddress("glUniform4uiv"); + if(!_ptrc_glUniform4uiv) numFailed++; + _ptrc_glVertexAttribI1i = (void (CODEGEN_FUNCPTR *)(GLuint, GLint))IntGetProcAddress("glVertexAttribI1i"); + if(!_ptrc_glVertexAttribI1i) numFailed++; + _ptrc_glVertexAttribI1iv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttribI1iv"); + if(!_ptrc_glVertexAttribI1iv) numFailed++; + _ptrc_glVertexAttribI1ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint))IntGetProcAddress("glVertexAttribI1ui"); + if(!_ptrc_glVertexAttribI1ui) numFailed++; + _ptrc_glVertexAttribI1uiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttribI1uiv"); + if(!_ptrc_glVertexAttribI1uiv) numFailed++; + _ptrc_glVertexAttribI2i = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLint))IntGetProcAddress("glVertexAttribI2i"); + if(!_ptrc_glVertexAttribI2i) numFailed++; + _ptrc_glVertexAttribI2iv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttribI2iv"); + if(!_ptrc_glVertexAttribI2iv) numFailed++; + _ptrc_glVertexAttribI2ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint))IntGetProcAddress("glVertexAttribI2ui"); + if(!_ptrc_glVertexAttribI2ui) numFailed++; + _ptrc_glVertexAttribI2uiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttribI2uiv"); + if(!_ptrc_glVertexAttribI2uiv) numFailed++; + _ptrc_glVertexAttribI3i = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLint, GLint))IntGetProcAddress("glVertexAttribI3i"); + if(!_ptrc_glVertexAttribI3i) numFailed++; + _ptrc_glVertexAttribI3iv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttribI3iv"); + if(!_ptrc_glVertexAttribI3iv) numFailed++; + _ptrc_glVertexAttribI3ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint, GLuint))IntGetProcAddress("glVertexAttribI3ui"); + if(!_ptrc_glVertexAttribI3ui) numFailed++; + _ptrc_glVertexAttribI3uiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttribI3uiv"); + if(!_ptrc_glVertexAttribI3uiv) numFailed++; + _ptrc_glVertexAttribI4bv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLbyte *))IntGetProcAddress("glVertexAttribI4bv"); + if(!_ptrc_glVertexAttribI4bv) numFailed++; + _ptrc_glVertexAttribI4i = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLint, GLint, GLint))IntGetProcAddress("glVertexAttribI4i"); + if(!_ptrc_glVertexAttribI4i) numFailed++; + _ptrc_glVertexAttribI4iv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLint *))IntGetProcAddress("glVertexAttribI4iv"); + if(!_ptrc_glVertexAttribI4iv) numFailed++; + _ptrc_glVertexAttribI4sv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLshort *))IntGetProcAddress("glVertexAttribI4sv"); + if(!_ptrc_glVertexAttribI4sv) numFailed++; + _ptrc_glVertexAttribI4ubv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLubyte *))IntGetProcAddress("glVertexAttribI4ubv"); + if(!_ptrc_glVertexAttribI4ubv) numFailed++; + _ptrc_glVertexAttribI4ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint, GLuint, GLuint))IntGetProcAddress("glVertexAttribI4ui"); + if(!_ptrc_glVertexAttribI4ui) numFailed++; + _ptrc_glVertexAttribI4uiv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLuint *))IntGetProcAddress("glVertexAttribI4uiv"); + if(!_ptrc_glVertexAttribI4uiv) numFailed++; + _ptrc_glVertexAttribI4usv = (void (CODEGEN_FUNCPTR *)(GLuint, const GLushort *))IntGetProcAddress("glVertexAttribI4usv"); + if(!_ptrc_glVertexAttribI4usv) numFailed++; + _ptrc_glVertexAttribIPointer = (void (CODEGEN_FUNCPTR *)(GLuint, GLint, GLenum, GLsizei, const void *))IntGetProcAddress("glVertexAttribIPointer"); + if(!_ptrc_glVertexAttribIPointer) numFailed++; + _ptrc_glCopyBufferSubData = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr))IntGetProcAddress("glCopyBufferSubData"); + if(!_ptrc_glCopyBufferSubData) numFailed++; + _ptrc_glDrawArraysInstanced = (void (CODEGEN_FUNCPTR *)(GLenum, GLint, GLsizei, GLsizei))IntGetProcAddress("glDrawArraysInstanced"); + if(!_ptrc_glDrawArraysInstanced) numFailed++; + _ptrc_glDrawElementsInstanced = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, const void *, GLsizei))IntGetProcAddress("glDrawElementsInstanced"); + if(!_ptrc_glDrawElementsInstanced) numFailed++; + _ptrc_glGetActiveUniformBlockName = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetActiveUniformBlockName"); + if(!_ptrc_glGetActiveUniformBlockName) numFailed++; + _ptrc_glGetActiveUniformBlockiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLenum, GLint *))IntGetProcAddress("glGetActiveUniformBlockiv"); + if(!_ptrc_glGetActiveUniformBlockiv) numFailed++; + _ptrc_glGetActiveUniformName = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *))IntGetProcAddress("glGetActiveUniformName"); + if(!_ptrc_glGetActiveUniformName) numFailed++; + _ptrc_glGetActiveUniformsiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, const GLuint *, GLenum, GLint *))IntGetProcAddress("glGetActiveUniformsiv"); + if(!_ptrc_glGetActiveUniformsiv) numFailed++; + _ptrc_glGetUniformBlockIndex = (GLuint (CODEGEN_FUNCPTR *)(GLuint, const GLchar *))IntGetProcAddress("glGetUniformBlockIndex"); + if(!_ptrc_glGetUniformBlockIndex) numFailed++; + _ptrc_glGetUniformIndices = (void (CODEGEN_FUNCPTR *)(GLuint, GLsizei, const GLchar *const*, GLuint *))IntGetProcAddress("glGetUniformIndices"); + if(!_ptrc_glGetUniformIndices) numFailed++; + _ptrc_glPrimitiveRestartIndex = (void (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glPrimitiveRestartIndex"); + if(!_ptrc_glPrimitiveRestartIndex) numFailed++; + _ptrc_glTexBuffer = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLuint))IntGetProcAddress("glTexBuffer"); + if(!_ptrc_glTexBuffer) numFailed++; + _ptrc_glUniformBlockBinding = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint))IntGetProcAddress("glUniformBlockBinding"); + if(!_ptrc_glUniformBlockBinding) numFailed++; + _ptrc_glClientWaitSync = (GLenum (CODEGEN_FUNCPTR *)(GLsync, GLbitfield, GLuint64))IntGetProcAddress("glClientWaitSync"); + if(!_ptrc_glClientWaitSync) numFailed++; + _ptrc_glDeleteSync = (void (CODEGEN_FUNCPTR *)(GLsync))IntGetProcAddress("glDeleteSync"); + if(!_ptrc_glDeleteSync) numFailed++; + _ptrc_glDrawElementsBaseVertex = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, const void *, GLint))IntGetProcAddress("glDrawElementsBaseVertex"); + if(!_ptrc_glDrawElementsBaseVertex) numFailed++; + _ptrc_glDrawElementsInstancedBaseVertex = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, const void *, GLsizei, GLint))IntGetProcAddress("glDrawElementsInstancedBaseVertex"); + if(!_ptrc_glDrawElementsInstancedBaseVertex) numFailed++; + _ptrc_glDrawRangeElementsBaseVertex = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLuint, GLsizei, GLenum, const void *, GLint))IntGetProcAddress("glDrawRangeElementsBaseVertex"); + if(!_ptrc_glDrawRangeElementsBaseVertex) numFailed++; + _ptrc_glFenceSync = (GLsync (CODEGEN_FUNCPTR *)(GLenum, GLbitfield))IntGetProcAddress("glFenceSync"); + if(!_ptrc_glFenceSync) numFailed++; + _ptrc_glFramebufferTexture = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLuint, GLint))IntGetProcAddress("glFramebufferTexture"); + if(!_ptrc_glFramebufferTexture) numFailed++; + _ptrc_glGetBufferParameteri64v = (void (CODEGEN_FUNCPTR *)(GLenum, GLenum, GLint64 *))IntGetProcAddress("glGetBufferParameteri64v"); + if(!_ptrc_glGetBufferParameteri64v) numFailed++; + _ptrc_glGetInteger64i_v = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLint64 *))IntGetProcAddress("glGetInteger64i_v"); + if(!_ptrc_glGetInteger64i_v) numFailed++; + _ptrc_glGetInteger64v = (void (CODEGEN_FUNCPTR *)(GLenum, GLint64 *))IntGetProcAddress("glGetInteger64v"); + if(!_ptrc_glGetInteger64v) numFailed++; + _ptrc_glGetMultisamplefv = (void (CODEGEN_FUNCPTR *)(GLenum, GLuint, GLfloat *))IntGetProcAddress("glGetMultisamplefv"); + if(!_ptrc_glGetMultisamplefv) numFailed++; + _ptrc_glGetSynciv = (void (CODEGEN_FUNCPTR *)(GLsync, GLenum, GLsizei, GLsizei *, GLint *))IntGetProcAddress("glGetSynciv"); + if(!_ptrc_glGetSynciv) numFailed++; + _ptrc_glIsSync = (GLboolean (CODEGEN_FUNCPTR *)(GLsync))IntGetProcAddress("glIsSync"); + if(!_ptrc_glIsSync) numFailed++; + _ptrc_glMultiDrawElementsBaseVertex = (void (CODEGEN_FUNCPTR *)(GLenum, const GLsizei *, GLenum, const void *const*, GLsizei, const GLint *))IntGetProcAddress("glMultiDrawElementsBaseVertex"); + if(!_ptrc_glMultiDrawElementsBaseVertex) numFailed++; + _ptrc_glProvokingVertex = (void (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glProvokingVertex"); + if(!_ptrc_glProvokingVertex) numFailed++; + _ptrc_glSampleMaski = (void (CODEGEN_FUNCPTR *)(GLuint, GLbitfield))IntGetProcAddress("glSampleMaski"); + if(!_ptrc_glSampleMaski) numFailed++; + _ptrc_glTexImage2DMultisample = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean))IntGetProcAddress("glTexImage2DMultisample"); + if(!_ptrc_glTexImage2DMultisample) numFailed++; + _ptrc_glTexImage3DMultisample = (void (CODEGEN_FUNCPTR *)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei, GLboolean))IntGetProcAddress("glTexImage3DMultisample"); + if(!_ptrc_glTexImage3DMultisample) numFailed++; + _ptrc_glWaitSync = (void (CODEGEN_FUNCPTR *)(GLsync, GLbitfield, GLuint64))IntGetProcAddress("glWaitSync"); + if(!_ptrc_glWaitSync) numFailed++; + _ptrc_glBindFragDataLocationIndexed = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint, GLuint, const GLchar *))IntGetProcAddress("glBindFragDataLocationIndexed"); + if(!_ptrc_glBindFragDataLocationIndexed) numFailed++; + _ptrc_glBindSampler = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint))IntGetProcAddress("glBindSampler"); + if(!_ptrc_glBindSampler) numFailed++; + _ptrc_glDeleteSamplers = (void (CODEGEN_FUNCPTR *)(GLsizei, const GLuint *))IntGetProcAddress("glDeleteSamplers"); + if(!_ptrc_glDeleteSamplers) numFailed++; + _ptrc_glGenSamplers = (void (CODEGEN_FUNCPTR *)(GLsizei, GLuint *))IntGetProcAddress("glGenSamplers"); + if(!_ptrc_glGenSamplers) numFailed++; + _ptrc_glGetFragDataIndex = (GLint (CODEGEN_FUNCPTR *)(GLuint, const GLchar *))IntGetProcAddress("glGetFragDataIndex"); + if(!_ptrc_glGetFragDataIndex) numFailed++; + _ptrc_glGetQueryObjecti64v = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint64 *))IntGetProcAddress("glGetQueryObjecti64v"); + if(!_ptrc_glGetQueryObjecti64v) numFailed++; + _ptrc_glGetQueryObjectui64v = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLuint64 *))IntGetProcAddress("glGetQueryObjectui64v"); + if(!_ptrc_glGetQueryObjectui64v) numFailed++; + _ptrc_glGetSamplerParameterIiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetSamplerParameterIiv"); + if(!_ptrc_glGetSamplerParameterIiv) numFailed++; + _ptrc_glGetSamplerParameterIuiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLuint *))IntGetProcAddress("glGetSamplerParameterIuiv"); + if(!_ptrc_glGetSamplerParameterIuiv) numFailed++; + _ptrc_glGetSamplerParameterfv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLfloat *))IntGetProcAddress("glGetSamplerParameterfv"); + if(!_ptrc_glGetSamplerParameterfv) numFailed++; + _ptrc_glGetSamplerParameteriv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint *))IntGetProcAddress("glGetSamplerParameteriv"); + if(!_ptrc_glGetSamplerParameteriv) numFailed++; + _ptrc_glIsSampler = (GLboolean (CODEGEN_FUNCPTR *)(GLuint))IntGetProcAddress("glIsSampler"); + if(!_ptrc_glIsSampler) numFailed++; + _ptrc_glQueryCounter = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum))IntGetProcAddress("glQueryCounter"); + if(!_ptrc_glQueryCounter) numFailed++; + _ptrc_glSamplerParameterIiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, const GLint *))IntGetProcAddress("glSamplerParameterIiv"); + if(!_ptrc_glSamplerParameterIiv) numFailed++; + _ptrc_glSamplerParameterIuiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, const GLuint *))IntGetProcAddress("glSamplerParameterIuiv"); + if(!_ptrc_glSamplerParameterIuiv) numFailed++; + _ptrc_glSamplerParameterf = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLfloat))IntGetProcAddress("glSamplerParameterf"); + if(!_ptrc_glSamplerParameterf) numFailed++; + _ptrc_glSamplerParameterfv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, const GLfloat *))IntGetProcAddress("glSamplerParameterfv"); + if(!_ptrc_glSamplerParameterfv) numFailed++; + _ptrc_glSamplerParameteri = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLint))IntGetProcAddress("glSamplerParameteri"); + if(!_ptrc_glSamplerParameteri) numFailed++; + _ptrc_glSamplerParameteriv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, const GLint *))IntGetProcAddress("glSamplerParameteriv"); + if(!_ptrc_glSamplerParameteriv) numFailed++; + _ptrc_glVertexAttribDivisor = (void (CODEGEN_FUNCPTR *)(GLuint, GLuint))IntGetProcAddress("glVertexAttribDivisor"); + if(!_ptrc_glVertexAttribDivisor) numFailed++; + _ptrc_glVertexAttribP1ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, GLuint))IntGetProcAddress("glVertexAttribP1ui"); + if(!_ptrc_glVertexAttribP1ui) numFailed++; + _ptrc_glVertexAttribP1uiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, const GLuint *))IntGetProcAddress("glVertexAttribP1uiv"); + if(!_ptrc_glVertexAttribP1uiv) numFailed++; + _ptrc_glVertexAttribP2ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, GLuint))IntGetProcAddress("glVertexAttribP2ui"); + if(!_ptrc_glVertexAttribP2ui) numFailed++; + _ptrc_glVertexAttribP2uiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, const GLuint *))IntGetProcAddress("glVertexAttribP2uiv"); + if(!_ptrc_glVertexAttribP2uiv) numFailed++; + _ptrc_glVertexAttribP3ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, GLuint))IntGetProcAddress("glVertexAttribP3ui"); + if(!_ptrc_glVertexAttribP3ui) numFailed++; + _ptrc_glVertexAttribP3uiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, const GLuint *))IntGetProcAddress("glVertexAttribP3uiv"); + if(!_ptrc_glVertexAttribP3uiv) numFailed++; + _ptrc_glVertexAttribP4ui = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, GLuint))IntGetProcAddress("glVertexAttribP4ui"); + if(!_ptrc_glVertexAttribP4ui) numFailed++; + _ptrc_glVertexAttribP4uiv = (void (CODEGEN_FUNCPTR *)(GLuint, GLenum, GLboolean, const GLuint *))IntGetProcAddress("glVertexAttribP4uiv"); + if(!_ptrc_glVertexAttribP4uiv) numFailed++; + return numFailed; +} + +typedef int (*PFN_LOADFUNCPOINTERS)(void); +typedef struct ogl_StrToExtMap_s +{ + char *extensionName; + int *extensionVariable; + PFN_LOADFUNCPOINTERS LoadExtension; +} ogl_StrToExtMap; + +static ogl_StrToExtMap ExtensionMap[11] = { + {"GL_APPLE_client_storage", &ogl_ext_APPLE_client_storage, NULL}, + {"GL_ARB_buffer_storage", &ogl_ext_ARB_buffer_storage, Load_ARB_buffer_storage}, + {"GL_ARB_shader_storage_buffer_object", &ogl_ext_ARB_shader_storage_buffer_object, Load_ARB_shader_storage_buffer_object}, + {"GL_ARB_texture_compression", &ogl_ext_ARB_texture_compression, Load_ARB_texture_compression}, + {"GL_ARB_texture_rectangle", &ogl_ext_ARB_texture_rectangle, NULL}, + {"GL_EXT_framebuffer_object", &ogl_ext_EXT_framebuffer_object, Load_EXT_framebuffer_object}, + {"GL_EXT_texture_compression_s3tc", &ogl_ext_EXT_texture_compression_s3tc, NULL}, + {"GL_EXT_texture_filter_anisotropic", &ogl_ext_EXT_texture_filter_anisotropic, NULL}, + {"GL_EXT_texture_sRGB", &ogl_ext_EXT_texture_sRGB, NULL}, + {"GL_KHR_debug", &ogl_ext_KHR_debug, Load_KHR_debug}, + {"GL_ARB_invalidate_subdata", &ogl_ext_ARB_invalidate_subdata, Load_ARB_invalidate_subdata}, +}; + +static int g_extensionMapSize = 11; + +static ogl_StrToExtMap *FindExtEntry(const char *extensionName) +{ + int loop; + ogl_StrToExtMap *currLoc = ExtensionMap; + for(loop = 0; loop < g_extensionMapSize; ++loop, ++currLoc) + { + if(strcmp(extensionName, currLoc->extensionName) == 0) + return currLoc; + } + + return NULL; +} + +static void ClearExtensionVars(void) +{ + ogl_ext_APPLE_client_storage = ogl_LOAD_FAILED; + ogl_ext_ARB_buffer_storage = ogl_LOAD_FAILED; + ogl_ext_ARB_shader_storage_buffer_object = ogl_LOAD_FAILED; + ogl_ext_ARB_texture_compression = ogl_LOAD_FAILED; + ogl_ext_ARB_texture_rectangle = ogl_LOAD_FAILED; + ogl_ext_EXT_framebuffer_object = ogl_LOAD_FAILED; + ogl_ext_EXT_texture_compression_s3tc = ogl_LOAD_FAILED; + ogl_ext_EXT_texture_filter_anisotropic = ogl_LOAD_FAILED; + ogl_ext_EXT_texture_sRGB = ogl_LOAD_FAILED; + ogl_ext_KHR_debug = ogl_LOAD_FAILED; + ogl_ext_ARB_invalidate_subdata = ogl_LOAD_FAILED; +} + + +static void LoadExtByName(const char *extensionName) +{ + ogl_StrToExtMap *entry = NULL; + entry = FindExtEntry(extensionName); + if(entry) + { + if(entry->LoadExtension) + { + int numFailed = entry->LoadExtension(); + if(numFailed == 0) + { + *(entry->extensionVariable) = ogl_LOAD_SUCCEEDED; + } + else + { + *(entry->extensionVariable) = ogl_LOAD_SUCCEEDED + numFailed; + } + } + else + { + *(entry->extensionVariable) = ogl_LOAD_SUCCEEDED; + } + } +} + +/* BEGINNING OF MANUAL CHANGES, DO NOT REMOVE! */ + +static void ProcExtsFromExtString(const char *strExtList) +{ + size_t iExtListLen = strlen(strExtList); + const char *strExtListEnd = strExtList + iExtListLen; + const char *strCurrPos = strExtList; + char strWorkBuff[256]; + + while (*strCurrPos) + { + /*Get the extension at our position.*/ + int iStrLen = 0; + const char *strEndStr = strchr(strCurrPos, ' '); + int iStop = 0; + if (strEndStr == NULL) + { + strEndStr = strExtListEnd; + iStop = 1; + } + + iStrLen = (int)((ptrdiff_t)strEndStr - (ptrdiff_t)strCurrPos); + + if (iStrLen > 255) + return; + + strncpy(strWorkBuff, strCurrPos, iStrLen); + strWorkBuff[iStrLen] = '\0'; + + LoadExtByName(strWorkBuff); + + strCurrPos = strEndStr + 1; + if (iStop) break; + } +} + +static int ProcExtsFromExtList(void) +{ + GLint iLoop; + GLint iNumExtensions = 0; + + if (_ptrc_glGetStringi == NULL) return 0; + + _ptrc_glGetIntegerv(GL_NUM_EXTENSIONS, &iNumExtensions); + + for(iLoop = 0; iLoop < iNumExtensions; iLoop++) + { + const char *strExtensionName = (const char *)_ptrc_glGetStringi(GL_EXTENSIONS, iLoop); + LoadExtByName(strExtensionName); + } + + return iNumExtensions; +} + +int ogl_LoadFunctions() +{ + int numFailed = 0; + ClearExtensionVars(); + + _ptrc_glGetIntegerv = (void (CODEGEN_FUNCPTR *)(GLenum, GLint *))IntGetProcAddress("glGetIntegerv"); + if(!_ptrc_glGetIntegerv) return ogl_LOAD_FAILED; + _ptrc_glGetStringi = (const GLubyte * (CODEGEN_FUNCPTR *)(GLenum, GLuint))IntGetProcAddress("glGetStringi"); + + if (0 == ProcExtsFromExtList()) + { + _ptrc_glGetString = (const GLubyte * (CODEGEN_FUNCPTR *)(GLenum))IntGetProcAddress("glGetString"); + if (!_ptrc_glGetString) return ogl_LOAD_FAILED; + + ProcExtsFromExtString((const char *)_ptrc_glGetString(GL_EXTENSIONS)); + } + + numFailed = Load_Version_3_3(); + + if(numFailed == 0) + return ogl_LOAD_SUCCEEDED; + else + return ogl_LOAD_SUCCEEDED + numFailed; +} + +/* END OF MANUAL CHANGES, DO NOT REMOVE! */ + +static int g_major_version = 0; +static int g_minor_version = 0; + +static void GetGLVersion(void) +{ + glGetIntegerv(GL_MAJOR_VERSION, &g_major_version); + glGetIntegerv(GL_MINOR_VERSION, &g_minor_version); +} + +int ogl_GetMajorVersion(void) +{ + if(g_major_version == 0) + GetGLVersion(); + return g_major_version; +} + +int ogl_GetMinorVersion(void) +{ + if(g_major_version == 0) /*Yes, check the major version to get the minor one.*/ + GetGLVersion(); + return g_minor_version; +} + +int ogl_IsVersionGEQ(int majorVersion, int minorVersion) +{ + if(g_major_version == 0) + GetGLVersion(); + + if(majorVersion < g_major_version) return 1; + if(majorVersion > g_major_version) return 0; + if(minorVersion <= g_minor_version) return 1; + return 0; +} + diff --git a/src/gl/system/gl_load.h b/src/gl/system/gl_load.h new file mode 100644 index 000000000..892709ccd --- /dev/null +++ b/src/gl/system/gl_load.h @@ -0,0 +1,3122 @@ +#ifndef POINTER_C_GENERATED_HEADER_OPENGL_H +#define POINTER_C_GENERATED_HEADER_OPENGL_H + +#if defined(__glew_h__) || defined(__GLEW_H__) +#error Attempt to include auto-generated header after including glew.h +#endif +#if defined(__gl_h_) || defined(__GL_H__) +#error Attempt to include auto-generated header after including gl.h +#endif +#if defined(__glext_h_) || defined(__GLEXT_H_) +#error Attempt to include auto-generated header after including glext.h +#endif +#if defined(__gltypes_h_) +#error Attempt to include auto-generated header after gltypes.h +#endif +#if defined(__gl_ATI_h_) +#error Attempt to include auto-generated header after including glATI.h +#endif + +#define __glew_h__ +#define __GLEW_H__ +#define __gl_h_ +#define __GL_H__ +#define __glext_h_ +#define __GLEXT_H_ +#define __gltypes_h_ +#define __gl_ATI_h_ + +#ifndef APIENTRY + #if defined(__MINGW32__) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN 1 + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #elif (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN 1 + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #else + #define APIENTRY + #endif +#endif /*APIENTRY*/ + +#ifndef CODEGEN_FUNCPTR + #define CODEGEN_REMOVE_FUNCPTR + #if defined(_WIN32) + #define CODEGEN_FUNCPTR APIENTRY + #else + #define CODEGEN_FUNCPTR + #endif +#endif /*CODEGEN_FUNCPTR*/ + +#ifndef GLAPI + #define GLAPI extern +#endif + + +#ifndef GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS +#define GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS + + +#endif /*GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS*/ + + +#include +#ifndef GLEXT_64_TYPES_DEFINED +/* This code block is duplicated in glxext.h, so must be protected */ +#define GLEXT_64_TYPES_DEFINED +/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ +/* (as used in the GL_EXT_timer_query extension). */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#include +#elif defined(__sun__) || defined(__digital__) +#include +#if defined(__STDC__) +#if defined(__arch64__) || defined(_LP64) +typedef long int int64_t; +typedef unsigned long int uint64_t; +#else +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#endif /* __arch64__ */ +#endif /* __STDC__ */ +#elif defined( __VMS ) || defined(__sgi) +#include +#elif defined(__SCO__) || defined(__USLC__) +#include +#elif defined(__UNIXOS2__) || defined(__SOL64__) +typedef long int int32_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#elif defined(_WIN32) && defined(__GNUC__) +#include +#elif defined(_WIN32) +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +/* Fallback if nothing above works */ +#include +#endif +#endif + typedef unsigned int GLenum; + typedef unsigned char GLboolean; + typedef unsigned int GLbitfield; + typedef void GLvoid; + typedef signed char GLbyte; + typedef short GLshort; + typedef int GLint; + typedef unsigned char GLubyte; + typedef unsigned short GLushort; + typedef unsigned int GLuint; + typedef int GLsizei; + typedef float GLfloat; + typedef float GLclampf; + typedef double GLdouble; + typedef double GLclampd; + typedef char GLchar; + typedef char GLcharARB; + #ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif + typedef unsigned short GLhalfARB; + typedef unsigned short GLhalf; + typedef GLint GLfixed; + typedef ptrdiff_t GLintptr; + typedef ptrdiff_t GLsizeiptr; + typedef int64_t GLint64; + typedef uint64_t GLuint64; + typedef ptrdiff_t GLintptrARB; + typedef ptrdiff_t GLsizeiptrARB; + typedef int64_t GLint64EXT; + typedef uint64_t GLuint64EXT; + typedef struct __GLsync *GLsync; + struct _cl_context; + struct _cl_event; + typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); + typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); + typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); + typedef unsigned short GLhalfNV; + typedef GLintptr GLvdpauSurfaceNV; + +#ifdef __cplusplus +extern "C" { +#endif /*__cplusplus*/ + +extern int ogl_ext_APPLE_client_storage; +extern int ogl_ext_ARB_buffer_storage; +extern int ogl_ext_ARB_shader_storage_buffer_object; +extern int ogl_ext_ARB_texture_compression; +extern int ogl_ext_ARB_texture_rectangle; +extern int ogl_ext_EXT_framebuffer_object; +extern int ogl_ext_EXT_texture_compression_s3tc; +extern int ogl_ext_EXT_texture_filter_anisotropic; +extern int ogl_ext_EXT_texture_sRGB; +extern int ogl_ext_KHR_debug; +extern int ogl_ext_ARB_invalidate_subdata; + +#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 + +#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F +#define GL_BUFFER_STORAGE_FLAGS 0x8220 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 +#define GL_CLIENT_STORAGE_BIT 0x0200 +#define GL_DYNAMIC_STORAGE_BIT 0x0100 +#define GL_MAP_COHERENT_BIT 0x0080 +#define GL_MAP_PERSISTENT_BIT 0x0040 +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 + +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 +#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 +#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC +#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB +#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 +#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 +#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF +#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 +#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 + +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF + +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 +#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 +#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 +#define GL_TEXTURE_RECTANGLE_ARB 0x84F5 + +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 + +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 + +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE + +#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B +#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A +#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F +#define GL_COMPRESSED_SRGB_EXT 0x8C48 +#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C +#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 +#define GL_SLUMINANCE8_EXT 0x8C47 +#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 +#define GL_SLUMINANCE_EXT 0x8C46 +#define GL_SRGB8_ALPHA8_EXT 0x8C43 +#define GL_SRGB8_EXT 0x8C41 +#define GL_SRGB_ALPHA_EXT 0x8C42 +#define GL_SRGB_EXT 0x8C40 + +#define GL_BUFFER 0x82E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DISPLAY_LIST 0x82E7 +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_PROGRAM 0x82E2 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_QUERY 0x82E3 +#define GL_SAMPLER 0x82E6 +#define GL_SHADER 0x82E1 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_VERTEX_ARRAY 0x8074 + +#define GL_2D 0x0600 +#define GL_2_BYTES 0x1407 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_3_BYTES 0x1408 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_4_BYTES 0x1409 +#define GL_ACCUM 0x0100 +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ADD 0x0104 +#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_ALPHA 0x1906 +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_ALPHA_BITS 0x0D55 +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_ALWAYS 0x0207 +#define GL_AMBIENT 0x1200 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_AND 0x1501 +#define GL_AND_INVERTED 0x1504 +#define GL_AND_REVERSE 0x1502 +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_AUTO_NORMAL 0x0D80 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_AUX_BUFFERS 0x0C00 +#define GL_BACK 0x0405 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_BITMAP 0x1A00 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_BLEND 0x0BE2 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLUE 0x1905 +#define GL_BLUE_BIAS 0x0D1B +#define GL_BLUE_BITS 0x0D54 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BYTE 0x1400 +#define GL_C3F_V3F 0x2A24 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_CCW 0x0901 +#define GL_CLAMP 0x2900 +#define GL_CLEAR 0x1500 +#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 +#define GL_COEFF 0x0A00 +#define GL_COLOR 0x1800 +#define GL_COLOR_ARRAY 0x8076 +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_INDEX 0x1900 +#define GL_COLOR_INDEXES 0x1603 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_COPY 0x1503 +#define GL_COPY_INVERTED 0x150C +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_CURRENT_BIT 0x00000001 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_CW 0x0900 +#define GL_DECAL 0x2101 +#define GL_DECR 0x1E03 +#define GL_DEPTH 0x1801 +#define GL_DEPTH_BIAS 0x0D1F +#define GL_DEPTH_BITS 0x0D56 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DIFFUSE 0x1201 +#define GL_DITHER 0x0BD0 +#define GL_DOMAIN 0x0A02 +#define GL_DONT_CARE 0x1100 +#define GL_DOUBLE 0x140A +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_DST_ALPHA 0x0304 +#define GL_DST_COLOR 0x0306 +#define GL_EDGE_FLAG 0x0B43 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_EMISSION 0x1600 +#define GL_ENABLE_BIT 0x00002000 +#define GL_EQUAL 0x0202 +#define GL_EQUIV 0x1509 +#define GL_EVAL_BIT 0x00010000 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 +#define GL_EXTENSIONS 0x1F03 +#define GL_EYE_LINEAR 0x2400 +#define GL_EYE_PLANE 0x2502 +#define GL_FALSE 0 +#define GL_FASTEST 0x1101 +#define GL_FEEDBACK 0x1C01 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 +#define GL_FILL 0x1B02 +#define GL_FLAT 0x1D00 +#define GL_FLOAT 0x1406 +#define GL_FOG 0x0B60 +#define GL_FOG_BIT 0x00000080 +#define GL_FOG_COLOR 0x0B66 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_END 0x0B64 +#define GL_FOG_HINT 0x0C54 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_START 0x0B63 +#define GL_FRONT 0x0404 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_FRONT_FACE 0x0B46 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_GEQUAL 0x0206 +#define GL_GREATER 0x0204 +#define GL_GREEN 0x1904 +#define GL_GREEN_BIAS 0x0D19 +#define GL_GREEN_BITS 0x0D53 +#define GL_GREEN_SCALE 0x0D18 +#define GL_HINT_BIT 0x00008000 +#define GL_INCR 0x1E02 +#define GL_INDEX_ARRAY 0x8077 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_BITS 0x0D51 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_INDEX_MODE 0x0C30 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_INT 0x1404 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_OPERATION 0x0502 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVERT 0x150A +#define GL_KEEP 0x1E00 +#define GL_LEFT 0x0406 +#define GL_LEQUAL 0x0203 +#define GL_LESS 0x0201 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_LIGHTING 0x0B50 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LINE 0x1B01 +#define GL_LINEAR 0x2601 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_LINES 0x0001 +#define GL_LINE_BIT 0x00000004 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LINE_STRIP 0x0003 +#define GL_LINE_TOKEN 0x0702 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_BIT 0x00020000 +#define GL_LIST_INDEX 0x0B33 +#define GL_LIST_MODE 0x0B30 +#define GL_LOAD 0x0101 +#define GL_LOGIC_OP 0x0BF1 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_STENCIL 0x0D11 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_MODELVIEW 0x1700 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_MODULATE 0x2100 +#define GL_MULT 0x0103 +#define GL_N3F_V3F 0x2A25 +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_NAND 0x150E +#define GL_NEAREST 0x2600 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_NEVER 0x0200 +#define GL_NICEST 0x1102 +#define GL_NONE 0 +#define GL_NOOP 0x1505 +#define GL_NOR 0x1508 +#define GL_NORMALIZE 0x0BA1 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NOTEQUAL 0x0205 +#define GL_NO_ERROR 0 +#define GL_OBJECT_LINEAR 0x2401 +#define GL_OBJECT_PLANE 0x2501 +#define GL_ONE 1 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_OR 0x1507 +#define GL_ORDER 0x0A01 +#define GL_OR_INVERTED 0x150D +#define GL_OR_REVERSE 0x150B +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_POINT 0x1B00 +#define GL_POINTS 0x0000 +#define GL_POINT_BIT 0x00000002 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SMOOTH 0x0B10 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_POINT_TOKEN 0x0701 +#define GL_POLYGON 0x0009 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_POSITION 0x1203 +#define GL_PROJECTION 0x1701 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_Q 0x2003 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_QUADS 0x0007 +#define GL_QUAD_STRIP 0x0008 +#define GL_R 0x2002 +#define GL_R3_G3_B2 0x2A10 +#define GL_READ_BUFFER 0x0C02 +#define GL_RED 0x1903 +#define GL_RED_BIAS 0x0D15 +#define GL_RED_BITS 0x0D52 +#define GL_RED_SCALE 0x0D14 +#define GL_RENDER 0x1C00 +#define GL_RENDERER 0x1F01 +#define GL_RENDER_MODE 0x0C40 +#define GL_REPEAT 0x2901 +#define GL_REPLACE 0x1E01 +#define GL_RETURN 0x0102 +#define GL_RGB 0x1907 +#define GL_RGB10 0x8052 +#define GL_RGB10_A2 0x8059 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB5_A1 0x8057 +#define GL_RGB8 0x8051 +#define GL_RGBA 0x1908 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGBA8 0x8058 +#define GL_RGBA_MODE 0x0C31 +#define GL_RIGHT 0x0407 +#define GL_S 0x2000 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_SELECT 0x1C02 +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 +#define GL_SET 0x150F +#define GL_SHADE_MODEL 0x0B54 +#define GL_SHININESS 0x1601 +#define GL_SHORT 0x1402 +#define GL_SMOOTH 0x1D01 +#define GL_SPECULAR 0x1202 +#define GL_SPHERE_MAP 0x2402 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SRC_ALPHA 0x0302 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_SRC_COLOR 0x0300 +/*Copied GL_STACK_OVERFLOW From: KHR_debug*/ +/*Copied GL_STACK_UNDERFLOW From: KHR_debug*/ +#define GL_STENCIL 0x1802 +#define GL_STENCIL_BITS 0x0D57 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_INDEX 0x1901 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STEREO 0x0C33 +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_T 0x2001 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_C4F_N3F_V4F 0x2A2D +#define GL_T4F_V4F 0x2A28 +#define GL_TEXTURE 0x1702 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_BORDER 0x1005 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_TEXTURE_COMPONENTS 0x1003 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_ENV 0x2300 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRUE 1 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_UNSIGNED_INT 0x1405 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_VENDOR 0x1F00 +#define GL_VERSION 0x1F02 +/*Copied GL_VERTEX_ARRAY From: KHR_debug*/ +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VIEWPORT 0x0BA2 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_XOR 0x1506 +#define GL_ZERO 0 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 + +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_RESCALE_NORMAL 0x803A +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 + +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_ADD_SIGNED 0x8574 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_COMBINE 0x8570 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CONSTANT 0x8576 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#define GL_INTERPOLATE 0x8575 +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_MULTISAMPLE 0x809D +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_OPERAND2_RGB 0x8592 +#define GL_PREVIOUS 0x8578 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_REFLECTION_MAP 0x8512 +#define GL_RGB_SCALE 0x8573 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_SOURCE2_RGB 0x8582 +#define GL_SUBTRACT 0x84E7 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 + +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_COLOR_SUM 0x8458 +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_DECR_WRAP 0x8508 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_FOG_COORDINATE 0x8451 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_INCR_WRAP 0x8507 +#define GL_MAX 0x8008 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_MIN 0x8007 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_TEXTURE_LOD_BIAS 0x8501 + +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_CURRENT_QUERY 0x8865 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_FOG_COORD 0x8451 +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_SRC 0x8450 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_READ_ONLY 0x88B8 +#define GL_READ_WRITE 0x88BA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_ALPHA 0x8589 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_ALPHA 0x858A +#define GL_SRC2_RGB 0x8582 +#define GL_STATIC_COPY 0x88E6 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STREAM_COPY 0x88E2 +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_WRITE_ONLY 0x88B9 + +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_COORD_REPLACE 0x8862 +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_DELETE_STATUS 0x8B80 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_LINK_STATUS 0x8B82 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_TEXTURE_COORDS 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_POINT_SPRITE 0x8861 +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_SHADER_TYPE 0x8B4F +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_VERTEX_SHADER 0x8B31 + +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_SRGB_ALPHA 0x8C42 + +#define GL_ALPHA_INTEGER 0x8D97 +#define GL_BGRA_INTEGER 0x8D9B +#define GL_BGR_INTEGER 0x8D9A +#define GL_BLUE_INTEGER 0x8D96 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_RG 0x8226 +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_CONTEXT_FLAGS 0x821E +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_FIXED_ONLY 0x891D +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_FRAMEBUFFER 0x8D40 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_GREEN_INTEGER 0x8D95 +#define GL_HALF_FLOAT 0x140B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_MAJOR_VERSION 0x821B +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +/*Copied GL_MAP_READ_BIT From: ARB_buffer_storage*/ +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +/*Copied GL_MAP_WRITE_BIT From: ARB_buffer_storage*/ +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_MINOR_VERSION 0x821C +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_NUM_EXTENSIONS 0x821D +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_WAIT 0x8E13 +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_R16 0x822A +#define GL_R16F 0x822D +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32F 0x822E +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_R8 0x8229 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RED_INTEGER 0x8D94 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RG 0x8227 +#define GL_RG16 0x822C +#define GL_RG16F 0x822F +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32F 0x8230 +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_RG8 0x822B +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RGB16F 0x881B +#define GL_RGB16I 0x8D89 +#define GL_RGB16UI 0x8D77 +#define GL_RGB32F 0x8815 +#define GL_RGB32I 0x8D83 +#define GL_RGB32UI 0x8D71 +#define GL_RGB8I 0x8D8F +#define GL_RGB8UI 0x8D7D +#define GL_RGB9_E5 0x8C3D +#define GL_RGBA16F 0x881A +#define GL_RGBA16I 0x8D88 +#define GL_RGBA16UI 0x8D76 +#define GL_RGBA32F 0x8814 +#define GL_RGBA32I 0x8D82 +#define GL_RGBA32UI 0x8D70 +#define GL_RGBA8I 0x8D8E +#define GL_RGBA8UI 0x8D7C +#define GL_RGBA_INTEGER 0x8D99 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RG_INTEGER 0x8228 +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD + +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_INVALID_INDEX 0xFFFFFFFF +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_R16_SNORM 0x8F98 +#define GL_R8_SNORM 0x8F94 +#define GL_RG16_SNORM 0x8F99 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA16_SNORM 0x8F9B +#define GL_RGBA8_SNORM 0x8F97 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 + +#define GL_ALREADY_SIGNALED 0x911A +#define GL_CONDITION_SATISFIED 0x911C +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_INTEGER_SAMPLES 0x9110 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_OBJECT_TYPE 0x9112 +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SIGNALED 0x9119 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_SYNC_STATUS 0x9114 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_UNSIGNALED 0x9118 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_WAIT_FAILED 0x911D + +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_RGB10_A2UI 0x906F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_SRC1_COLOR 0x88F9 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIMESTAMP 0x8E28 +#define GL_TIME_ELAPSED 0x88BF +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE + + +#ifndef GL_ARB_buffer_storage +#define GL_ARB_buffer_storage 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glBufferStorage)(GLenum target, GLsizeiptr size, const void * data, GLbitfield flags); +#define glBufferStorage _ptrc_glBufferStorage +#endif /*GL_ARB_buffer_storage*/ + +#ifndef GL_ARB_shader_storage_buffer_object +#define GL_ARB_shader_storage_buffer_object 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glShaderStorageBlockBinding)(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +#define glShaderStorageBlockBinding _ptrc_glShaderStorageBlockBinding +#endif /*GL_ARB_shader_storage_buffer_object*/ + +#ifndef GL_ARB_texture_compression +#define GL_ARB_texture_compression 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage1DARB _ptrc_glCompressedTexImage1DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage2DARB _ptrc_glCompressedTexImage2DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage3DARB _ptrc_glCompressedTexImage3DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage1DARB _ptrc_glCompressedTexSubImage1DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage2DARB _ptrc_glCompressedTexSubImage2DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage3DARB _ptrc_glCompressedTexSubImage3DARB +extern void (CODEGEN_FUNCPTR *_ptrc_glGetCompressedTexImageARB)(GLenum target, GLint level, void * img); +#define glGetCompressedTexImageARB _ptrc_glGetCompressedTexImageARB +#endif /*GL_ARB_texture_compression*/ + + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glBindFramebufferEXT)(GLenum target, GLuint framebuffer); +#define glBindFramebufferEXT _ptrc_glBindFramebufferEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glBindRenderbufferEXT)(GLenum target, GLuint renderbuffer); +#define glBindRenderbufferEXT _ptrc_glBindRenderbufferEXT +extern GLenum (CODEGEN_FUNCPTR *_ptrc_glCheckFramebufferStatusEXT)(GLenum target); +#define glCheckFramebufferStatusEXT _ptrc_glCheckFramebufferStatusEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteFramebuffersEXT)(GLsizei n, const GLuint * framebuffers); +#define glDeleteFramebuffersEXT _ptrc_glDeleteFramebuffersEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteRenderbuffersEXT)(GLsizei n, const GLuint * renderbuffers); +#define glDeleteRenderbuffersEXT _ptrc_glDeleteRenderbuffersEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferRenderbufferEXT)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +#define glFramebufferRenderbufferEXT _ptrc_glFramebufferRenderbufferEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture1DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +#define glFramebufferTexture1DEXT _ptrc_glFramebufferTexture1DEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture2DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +#define glFramebufferTexture2DEXT _ptrc_glFramebufferTexture2DEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture3DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +#define glFramebufferTexture3DEXT _ptrc_glFramebufferTexture3DEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glGenFramebuffersEXT)(GLsizei n, GLuint * framebuffers); +#define glGenFramebuffersEXT _ptrc_glGenFramebuffersEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glGenRenderbuffersEXT)(GLsizei n, GLuint * renderbuffers); +#define glGenRenderbuffersEXT _ptrc_glGenRenderbuffersEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glGenerateMipmapEXT)(GLenum target); +#define glGenerateMipmapEXT _ptrc_glGenerateMipmapEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glGetFramebufferAttachmentParameterivEXT)(GLenum target, GLenum attachment, GLenum pname, GLint * params); +#define glGetFramebufferAttachmentParameterivEXT _ptrc_glGetFramebufferAttachmentParameterivEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glGetRenderbufferParameterivEXT)(GLenum target, GLenum pname, GLint * params); +#define glGetRenderbufferParameterivEXT _ptrc_glGetRenderbufferParameterivEXT +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsFramebufferEXT)(GLuint framebuffer); +#define glIsFramebufferEXT _ptrc_glIsFramebufferEXT +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsRenderbufferEXT)(GLuint renderbuffer); +#define glIsRenderbufferEXT _ptrc_glIsRenderbufferEXT +extern void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorageEXT)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +#define glRenderbufferStorageEXT _ptrc_glRenderbufferStorageEXT +#endif /*GL_EXT_framebuffer_object*/ + + + + +#ifndef GL_KHR_debug +#define GL_KHR_debug 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageCallback)(GLDEBUGPROC callback, const void * userParam); +#define glDebugMessageCallback _ptrc_glDebugMessageCallback +extern void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageControl)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled); +#define glDebugMessageControl _ptrc_glDebugMessageControl +extern void (CODEGEN_FUNCPTR *_ptrc_glDebugMessageInsert)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf); +#define glDebugMessageInsert _ptrc_glDebugMessageInsert +extern GLuint (CODEGEN_FUNCPTR *_ptrc_glGetDebugMessageLog)(GLuint count, GLsizei bufSize, GLenum * sources, GLenum * types, GLuint * ids, GLenum * severities, GLsizei * lengths, GLchar * messageLog); +#define glGetDebugMessageLog _ptrc_glGetDebugMessageLog +extern void (CODEGEN_FUNCPTR *_ptrc_glGetObjectLabel)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei * length, GLchar * label); +#define glGetObjectLabel _ptrc_glGetObjectLabel +extern void (CODEGEN_FUNCPTR *_ptrc_glGetObjectPtrLabel)(const void * ptr, GLsizei bufSize, GLsizei * length, GLchar * label); +#define glGetObjectPtrLabel _ptrc_glGetObjectPtrLabel +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPointerv)(GLenum pname, void ** params); +#define glGetPointerv _ptrc_glGetPointerv +extern void (CODEGEN_FUNCPTR *_ptrc_glObjectLabel)(GLenum identifier, GLuint name, GLsizei length, const GLchar * label); +#define glObjectLabel _ptrc_glObjectLabel +extern void (CODEGEN_FUNCPTR *_ptrc_glObjectPtrLabel)(const void * ptr, GLsizei length, const GLchar * label); +#define glObjectPtrLabel _ptrc_glObjectPtrLabel +extern void (CODEGEN_FUNCPTR *_ptrc_glPopDebugGroup)(void); +#define glPopDebugGroup _ptrc_glPopDebugGroup +extern void (CODEGEN_FUNCPTR *_ptrc_glPushDebugGroup)(GLenum source, GLuint id, GLsizei length, const GLchar * message); +#define glPushDebugGroup _ptrc_glPushDebugGroup +#endif /*GL_KHR_debug*/ + +#ifndef GL_ARB_invalidate_subdata +#define GL_ARB_invalidate_subdata 1 +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateBufferData)(GLuint buffer); +#define glInvalidateBufferData _ptrc_glInvalidateBufferData +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateBufferSubData)(GLuint buffer, GLintptr offset, GLsizeiptr length); +#define glInvalidateBufferSubData _ptrc_glInvalidateBufferSubData +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments); +#define glInvalidateFramebuffer _ptrc_glInvalidateFramebuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateSubFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height); +#define glInvalidateSubFramebuffer _ptrc_glInvalidateSubFramebuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateTexImage)(GLuint texture, GLint level); +#define glInvalidateTexImage _ptrc_glInvalidateTexImage +extern void (CODEGEN_FUNCPTR *_ptrc_glInvalidateTexSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +#define glInvalidateTexSubImage _ptrc_glInvalidateTexSubImage +#endif /*GL_ARB_invalidate_subdata*/ + +extern void (CODEGEN_FUNCPTR *_ptrc_glAccum)(GLenum op, GLfloat value); +#define glAccum _ptrc_glAccum +extern void (CODEGEN_FUNCPTR *_ptrc_glAlphaFunc)(GLenum func, GLfloat ref); +#define glAlphaFunc _ptrc_glAlphaFunc +extern void (CODEGEN_FUNCPTR *_ptrc_glBegin)(GLenum mode); +#define glBegin _ptrc_glBegin +extern void (CODEGEN_FUNCPTR *_ptrc_glBitmap)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte * bitmap); +#define glBitmap _ptrc_glBitmap +extern void (CODEGEN_FUNCPTR *_ptrc_glBlendFunc)(GLenum sfactor, GLenum dfactor); +#define glBlendFunc _ptrc_glBlendFunc +extern void (CODEGEN_FUNCPTR *_ptrc_glCallList)(GLuint list); +#define glCallList _ptrc_glCallList +extern void (CODEGEN_FUNCPTR *_ptrc_glCallLists)(GLsizei n, GLenum type, const void * lists); +#define glCallLists _ptrc_glCallLists +extern void (CODEGEN_FUNCPTR *_ptrc_glClear)(GLbitfield mask); +#define glClear _ptrc_glClear +extern void (CODEGEN_FUNCPTR *_ptrc_glClearAccum)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#define glClearAccum _ptrc_glClearAccum +extern void (CODEGEN_FUNCPTR *_ptrc_glClearColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#define glClearColor _ptrc_glClearColor +extern void (CODEGEN_FUNCPTR *_ptrc_glClearDepth)(GLdouble depth); +#define glClearDepth _ptrc_glClearDepth +extern void (CODEGEN_FUNCPTR *_ptrc_glClearIndex)(GLfloat c); +#define glClearIndex _ptrc_glClearIndex +extern void (CODEGEN_FUNCPTR *_ptrc_glClearStencil)(GLint s); +#define glClearStencil _ptrc_glClearStencil +extern void (CODEGEN_FUNCPTR *_ptrc_glClipPlane)(GLenum plane, const GLdouble * equation); +#define glClipPlane _ptrc_glClipPlane +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3b)(GLbyte red, GLbyte green, GLbyte blue); +#define glColor3b _ptrc_glColor3b +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3bv)(const GLbyte * v); +#define glColor3bv _ptrc_glColor3bv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3d)(GLdouble red, GLdouble green, GLdouble blue); +#define glColor3d _ptrc_glColor3d +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3dv)(const GLdouble * v); +#define glColor3dv _ptrc_glColor3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3f)(GLfloat red, GLfloat green, GLfloat blue); +#define glColor3f _ptrc_glColor3f +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3fv)(const GLfloat * v); +#define glColor3fv _ptrc_glColor3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3i)(GLint red, GLint green, GLint blue); +#define glColor3i _ptrc_glColor3i +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3iv)(const GLint * v); +#define glColor3iv _ptrc_glColor3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3s)(GLshort red, GLshort green, GLshort blue); +#define glColor3s _ptrc_glColor3s +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3sv)(const GLshort * v); +#define glColor3sv _ptrc_glColor3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3ub)(GLubyte red, GLubyte green, GLubyte blue); +#define glColor3ub _ptrc_glColor3ub +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3ubv)(const GLubyte * v); +#define glColor3ubv _ptrc_glColor3ubv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3ui)(GLuint red, GLuint green, GLuint blue); +#define glColor3ui _ptrc_glColor3ui +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3uiv)(const GLuint * v); +#define glColor3uiv _ptrc_glColor3uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3us)(GLushort red, GLushort green, GLushort blue); +#define glColor3us _ptrc_glColor3us +extern void (CODEGEN_FUNCPTR *_ptrc_glColor3usv)(const GLushort * v); +#define glColor3usv _ptrc_glColor3usv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4b)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); +#define glColor4b _ptrc_glColor4b +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4bv)(const GLbyte * v); +#define glColor4bv _ptrc_glColor4bv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4d)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); +#define glColor4d _ptrc_glColor4d +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4dv)(const GLdouble * v); +#define glColor4dv _ptrc_glColor4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#define glColor4f _ptrc_glColor4f +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4fv)(const GLfloat * v); +#define glColor4fv _ptrc_glColor4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4i)(GLint red, GLint green, GLint blue, GLint alpha); +#define glColor4i _ptrc_glColor4i +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4iv)(const GLint * v); +#define glColor4iv _ptrc_glColor4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4s)(GLshort red, GLshort green, GLshort blue, GLshort alpha); +#define glColor4s _ptrc_glColor4s +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4sv)(const GLshort * v); +#define glColor4sv _ptrc_glColor4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4ub)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); +#define glColor4ub _ptrc_glColor4ub +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4ubv)(const GLubyte * v); +#define glColor4ubv _ptrc_glColor4ubv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4ui)(GLuint red, GLuint green, GLuint blue, GLuint alpha); +#define glColor4ui _ptrc_glColor4ui +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4uiv)(const GLuint * v); +#define glColor4uiv _ptrc_glColor4uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4us)(GLushort red, GLushort green, GLushort blue, GLushort alpha); +#define glColor4us _ptrc_glColor4us +extern void (CODEGEN_FUNCPTR *_ptrc_glColor4usv)(const GLushort * v); +#define glColor4usv _ptrc_glColor4usv +extern void (CODEGEN_FUNCPTR *_ptrc_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#define glColorMask _ptrc_glColorMask +extern void (CODEGEN_FUNCPTR *_ptrc_glColorMaterial)(GLenum face, GLenum mode); +#define glColorMaterial _ptrc_glColorMaterial +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); +#define glCopyPixels _ptrc_glCopyPixels +extern void (CODEGEN_FUNCPTR *_ptrc_glCullFace)(GLenum mode); +#define glCullFace _ptrc_glCullFace +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteLists)(GLuint list, GLsizei range); +#define glDeleteLists _ptrc_glDeleteLists +extern void (CODEGEN_FUNCPTR *_ptrc_glDepthFunc)(GLenum func); +#define glDepthFunc _ptrc_glDepthFunc +extern void (CODEGEN_FUNCPTR *_ptrc_glDepthMask)(GLboolean flag); +#define glDepthMask _ptrc_glDepthMask +extern void (CODEGEN_FUNCPTR *_ptrc_glDepthRange)(GLdouble ren_near, GLdouble ren_far); +#define glDepthRange _ptrc_glDepthRange +extern void (CODEGEN_FUNCPTR *_ptrc_glDisable)(GLenum cap); +#define glDisable _ptrc_glDisable +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawBuffer)(GLenum buf); +#define glDrawBuffer _ptrc_glDrawBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawPixels)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels); +#define glDrawPixels _ptrc_glDrawPixels +extern void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlag)(GLboolean flag); +#define glEdgeFlag _ptrc_glEdgeFlag +extern void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlagv)(const GLboolean * flag); +#define glEdgeFlagv _ptrc_glEdgeFlagv +extern void (CODEGEN_FUNCPTR *_ptrc_glEnable)(GLenum cap); +#define glEnable _ptrc_glEnable +extern void (CODEGEN_FUNCPTR *_ptrc_glEnd)(void); +#define glEnd _ptrc_glEnd +extern void (CODEGEN_FUNCPTR *_ptrc_glEndList)(void); +#define glEndList _ptrc_glEndList +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1d)(GLdouble u); +#define glEvalCoord1d _ptrc_glEvalCoord1d +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1dv)(const GLdouble * u); +#define glEvalCoord1dv _ptrc_glEvalCoord1dv +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1f)(GLfloat u); +#define glEvalCoord1f _ptrc_glEvalCoord1f +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord1fv)(const GLfloat * u); +#define glEvalCoord1fv _ptrc_glEvalCoord1fv +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2d)(GLdouble u, GLdouble v); +#define glEvalCoord2d _ptrc_glEvalCoord2d +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2dv)(const GLdouble * u); +#define glEvalCoord2dv _ptrc_glEvalCoord2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2f)(GLfloat u, GLfloat v); +#define glEvalCoord2f _ptrc_glEvalCoord2f +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalCoord2fv)(const GLfloat * u); +#define glEvalCoord2fv _ptrc_glEvalCoord2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalMesh1)(GLenum mode, GLint i1, GLint i2); +#define glEvalMesh1 _ptrc_glEvalMesh1 +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalMesh2)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); +#define glEvalMesh2 _ptrc_glEvalMesh2 +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalPoint1)(GLint i); +#define glEvalPoint1 _ptrc_glEvalPoint1 +extern void (CODEGEN_FUNCPTR *_ptrc_glEvalPoint2)(GLint i, GLint j); +#define glEvalPoint2 _ptrc_glEvalPoint2 +extern void (CODEGEN_FUNCPTR *_ptrc_glFeedbackBuffer)(GLsizei size, GLenum type, GLfloat * buffer); +#define glFeedbackBuffer _ptrc_glFeedbackBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glFinish)(void); +#define glFinish _ptrc_glFinish +extern void (CODEGEN_FUNCPTR *_ptrc_glFlush)(void); +#define glFlush _ptrc_glFlush +extern void (CODEGEN_FUNCPTR *_ptrc_glFogf)(GLenum pname, GLfloat param); +#define glFogf _ptrc_glFogf +extern void (CODEGEN_FUNCPTR *_ptrc_glFogfv)(GLenum pname, const GLfloat * params); +#define glFogfv _ptrc_glFogfv +extern void (CODEGEN_FUNCPTR *_ptrc_glFogi)(GLenum pname, GLint param); +#define glFogi _ptrc_glFogi +extern void (CODEGEN_FUNCPTR *_ptrc_glFogiv)(GLenum pname, const GLint * params); +#define glFogiv _ptrc_glFogiv +extern void (CODEGEN_FUNCPTR *_ptrc_glFrontFace)(GLenum mode); +#define glFrontFace _ptrc_glFrontFace +extern void (CODEGEN_FUNCPTR *_ptrc_glFrustum)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +#define glFrustum _ptrc_glFrustum +extern GLuint (CODEGEN_FUNCPTR *_ptrc_glGenLists)(GLsizei range); +#define glGenLists _ptrc_glGenLists +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBooleanv)(GLenum pname, GLboolean * data); +#define glGetBooleanv _ptrc_glGetBooleanv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetClipPlane)(GLenum plane, GLdouble * equation); +#define glGetClipPlane _ptrc_glGetClipPlane +extern void (CODEGEN_FUNCPTR *_ptrc_glGetDoublev)(GLenum pname, GLdouble * data); +#define glGetDoublev _ptrc_glGetDoublev +extern GLenum (CODEGEN_FUNCPTR *_ptrc_glGetError)(void); +#define glGetError _ptrc_glGetError +extern void (CODEGEN_FUNCPTR *_ptrc_glGetFloatv)(GLenum pname, GLfloat * data); +#define glGetFloatv _ptrc_glGetFloatv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetIntegerv)(GLenum pname, GLint * data); +#define glGetIntegerv _ptrc_glGetIntegerv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetLightfv)(GLenum light, GLenum pname, GLfloat * params); +#define glGetLightfv _ptrc_glGetLightfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetLightiv)(GLenum light, GLenum pname, GLint * params); +#define glGetLightiv _ptrc_glGetLightiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMapdv)(GLenum target, GLenum query, GLdouble * v); +#define glGetMapdv _ptrc_glGetMapdv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMapfv)(GLenum target, GLenum query, GLfloat * v); +#define glGetMapfv _ptrc_glGetMapfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMapiv)(GLenum target, GLenum query, GLint * v); +#define glGetMapiv _ptrc_glGetMapiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMaterialfv)(GLenum face, GLenum pname, GLfloat * params); +#define glGetMaterialfv _ptrc_glGetMaterialfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMaterialiv)(GLenum face, GLenum pname, GLint * params); +#define glGetMaterialiv _ptrc_glGetMaterialiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapfv)(GLenum map, GLfloat * values); +#define glGetPixelMapfv _ptrc_glGetPixelMapfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapuiv)(GLenum map, GLuint * values); +#define glGetPixelMapuiv _ptrc_glGetPixelMapuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPixelMapusv)(GLenum map, GLushort * values); +#define glGetPixelMapusv _ptrc_glGetPixelMapusv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPolygonStipple)(GLubyte * mask); +#define glGetPolygonStipple _ptrc_glGetPolygonStipple +extern const GLubyte * (CODEGEN_FUNCPTR *_ptrc_glGetString)(GLenum name); +#define glGetString _ptrc_glGetString +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexEnvfv)(GLenum target, GLenum pname, GLfloat * params); +#define glGetTexEnvfv _ptrc_glGetTexEnvfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexEnviv)(GLenum target, GLenum pname, GLint * params); +#define glGetTexEnviv _ptrc_glGetTexEnviv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexGendv)(GLenum coord, GLenum pname, GLdouble * params); +#define glGetTexGendv _ptrc_glGetTexGendv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexGenfv)(GLenum coord, GLenum pname, GLfloat * params); +#define glGetTexGenfv _ptrc_glGetTexGenfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexGeniv)(GLenum coord, GLenum pname, GLint * params); +#define glGetTexGeniv _ptrc_glGetTexGeniv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, void * pixels); +#define glGetTexImage _ptrc_glGetTexImage +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat * params); +#define glGetTexLevelParameterfv _ptrc_glGetTexLevelParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint * params); +#define glGetTexLevelParameteriv _ptrc_glGetTexLevelParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat * params); +#define glGetTexParameterfv _ptrc_glGetTexParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameteriv)(GLenum target, GLenum pname, GLint * params); +#define glGetTexParameteriv _ptrc_glGetTexParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glHint)(GLenum target, GLenum mode); +#define glHint _ptrc_glHint +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexMask)(GLuint mask); +#define glIndexMask _ptrc_glIndexMask +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexd)(GLdouble c); +#define glIndexd _ptrc_glIndexd +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexdv)(const GLdouble * c); +#define glIndexdv _ptrc_glIndexdv +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexf)(GLfloat c); +#define glIndexf _ptrc_glIndexf +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexfv)(const GLfloat * c); +#define glIndexfv _ptrc_glIndexfv +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexi)(GLint c); +#define glIndexi _ptrc_glIndexi +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexiv)(const GLint * c); +#define glIndexiv _ptrc_glIndexiv +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexs)(GLshort c); +#define glIndexs _ptrc_glIndexs +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexsv)(const GLshort * c); +#define glIndexsv _ptrc_glIndexsv +extern void (CODEGEN_FUNCPTR *_ptrc_glInitNames)(void); +#define glInitNames _ptrc_glInitNames +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsEnabled)(GLenum cap); +#define glIsEnabled _ptrc_glIsEnabled +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsList)(GLuint list); +#define glIsList _ptrc_glIsList +extern void (CODEGEN_FUNCPTR *_ptrc_glLightModelf)(GLenum pname, GLfloat param); +#define glLightModelf _ptrc_glLightModelf +extern void (CODEGEN_FUNCPTR *_ptrc_glLightModelfv)(GLenum pname, const GLfloat * params); +#define glLightModelfv _ptrc_glLightModelfv +extern void (CODEGEN_FUNCPTR *_ptrc_glLightModeli)(GLenum pname, GLint param); +#define glLightModeli _ptrc_glLightModeli +extern void (CODEGEN_FUNCPTR *_ptrc_glLightModeliv)(GLenum pname, const GLint * params); +#define glLightModeliv _ptrc_glLightModeliv +extern void (CODEGEN_FUNCPTR *_ptrc_glLightf)(GLenum light, GLenum pname, GLfloat param); +#define glLightf _ptrc_glLightf +extern void (CODEGEN_FUNCPTR *_ptrc_glLightfv)(GLenum light, GLenum pname, const GLfloat * params); +#define glLightfv _ptrc_glLightfv +extern void (CODEGEN_FUNCPTR *_ptrc_glLighti)(GLenum light, GLenum pname, GLint param); +#define glLighti _ptrc_glLighti +extern void (CODEGEN_FUNCPTR *_ptrc_glLightiv)(GLenum light, GLenum pname, const GLint * params); +#define glLightiv _ptrc_glLightiv +extern void (CODEGEN_FUNCPTR *_ptrc_glLineStipple)(GLint factor, GLushort pattern); +#define glLineStipple _ptrc_glLineStipple +extern void (CODEGEN_FUNCPTR *_ptrc_glLineWidth)(GLfloat width); +#define glLineWidth _ptrc_glLineWidth +extern void (CODEGEN_FUNCPTR *_ptrc_glListBase)(GLuint base); +#define glListBase _ptrc_glListBase +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadIdentity)(void); +#define glLoadIdentity _ptrc_glLoadIdentity +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadMatrixd)(const GLdouble * m); +#define glLoadMatrixd _ptrc_glLoadMatrixd +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadMatrixf)(const GLfloat * m); +#define glLoadMatrixf _ptrc_glLoadMatrixf +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadName)(GLuint name); +#define glLoadName _ptrc_glLoadName +extern void (CODEGEN_FUNCPTR *_ptrc_glLogicOp)(GLenum opcode); +#define glLogicOp _ptrc_glLogicOp +extern void (CODEGEN_FUNCPTR *_ptrc_glMap1d)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble * points); +#define glMap1d _ptrc_glMap1d +extern void (CODEGEN_FUNCPTR *_ptrc_glMap1f)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat * points); +#define glMap1f _ptrc_glMap1f +extern void (CODEGEN_FUNCPTR *_ptrc_glMap2d)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble * points); +#define glMap2d _ptrc_glMap2d +extern void (CODEGEN_FUNCPTR *_ptrc_glMap2f)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat * points); +#define glMap2f _ptrc_glMap2f +extern void (CODEGEN_FUNCPTR *_ptrc_glMapGrid1d)(GLint un, GLdouble u1, GLdouble u2); +#define glMapGrid1d _ptrc_glMapGrid1d +extern void (CODEGEN_FUNCPTR *_ptrc_glMapGrid1f)(GLint un, GLfloat u1, GLfloat u2); +#define glMapGrid1f _ptrc_glMapGrid1f +extern void (CODEGEN_FUNCPTR *_ptrc_glMapGrid2d)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); +#define glMapGrid2d _ptrc_glMapGrid2d +extern void (CODEGEN_FUNCPTR *_ptrc_glMapGrid2f)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); +#define glMapGrid2f _ptrc_glMapGrid2f +extern void (CODEGEN_FUNCPTR *_ptrc_glMaterialf)(GLenum face, GLenum pname, GLfloat param); +#define glMaterialf _ptrc_glMaterialf +extern void (CODEGEN_FUNCPTR *_ptrc_glMaterialfv)(GLenum face, GLenum pname, const GLfloat * params); +#define glMaterialfv _ptrc_glMaterialfv +extern void (CODEGEN_FUNCPTR *_ptrc_glMateriali)(GLenum face, GLenum pname, GLint param); +#define glMateriali _ptrc_glMateriali +extern void (CODEGEN_FUNCPTR *_ptrc_glMaterialiv)(GLenum face, GLenum pname, const GLint * params); +#define glMaterialiv _ptrc_glMaterialiv +extern void (CODEGEN_FUNCPTR *_ptrc_glMatrixMode)(GLenum mode); +#define glMatrixMode _ptrc_glMatrixMode +extern void (CODEGEN_FUNCPTR *_ptrc_glMultMatrixd)(const GLdouble * m); +#define glMultMatrixd _ptrc_glMultMatrixd +extern void (CODEGEN_FUNCPTR *_ptrc_glMultMatrixf)(const GLfloat * m); +#define glMultMatrixf _ptrc_glMultMatrixf +extern void (CODEGEN_FUNCPTR *_ptrc_glNewList)(GLuint list, GLenum mode); +#define glNewList _ptrc_glNewList +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3b)(GLbyte nx, GLbyte ny, GLbyte nz); +#define glNormal3b _ptrc_glNormal3b +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3bv)(const GLbyte * v); +#define glNormal3bv _ptrc_glNormal3bv +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3d)(GLdouble nx, GLdouble ny, GLdouble nz); +#define glNormal3d _ptrc_glNormal3d +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3dv)(const GLdouble * v); +#define glNormal3dv _ptrc_glNormal3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3f)(GLfloat nx, GLfloat ny, GLfloat nz); +#define glNormal3f _ptrc_glNormal3f +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3fv)(const GLfloat * v); +#define glNormal3fv _ptrc_glNormal3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3i)(GLint nx, GLint ny, GLint nz); +#define glNormal3i _ptrc_glNormal3i +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3iv)(const GLint * v); +#define glNormal3iv _ptrc_glNormal3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3s)(GLshort nx, GLshort ny, GLshort nz); +#define glNormal3s _ptrc_glNormal3s +extern void (CODEGEN_FUNCPTR *_ptrc_glNormal3sv)(const GLshort * v); +#define glNormal3sv _ptrc_glNormal3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glOrtho)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +#define glOrtho _ptrc_glOrtho +extern void (CODEGEN_FUNCPTR *_ptrc_glPassThrough)(GLfloat token); +#define glPassThrough _ptrc_glPassThrough +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelMapfv)(GLenum map, GLsizei mapsize, const GLfloat * values); +#define glPixelMapfv _ptrc_glPixelMapfv +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelMapuiv)(GLenum map, GLsizei mapsize, const GLuint * values); +#define glPixelMapuiv _ptrc_glPixelMapuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelMapusv)(GLenum map, GLsizei mapsize, const GLushort * values); +#define glPixelMapusv _ptrc_glPixelMapusv +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelStoref)(GLenum pname, GLfloat param); +#define glPixelStoref _ptrc_glPixelStoref +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelStorei)(GLenum pname, GLint param); +#define glPixelStorei _ptrc_glPixelStorei +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelTransferf)(GLenum pname, GLfloat param); +#define glPixelTransferf _ptrc_glPixelTransferf +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelTransferi)(GLenum pname, GLint param); +#define glPixelTransferi _ptrc_glPixelTransferi +extern void (CODEGEN_FUNCPTR *_ptrc_glPixelZoom)(GLfloat xfactor, GLfloat yfactor); +#define glPixelZoom _ptrc_glPixelZoom +extern void (CODEGEN_FUNCPTR *_ptrc_glPointSize)(GLfloat size); +#define glPointSize _ptrc_glPointSize +extern void (CODEGEN_FUNCPTR *_ptrc_glPolygonMode)(GLenum face, GLenum mode); +#define glPolygonMode _ptrc_glPolygonMode +extern void (CODEGEN_FUNCPTR *_ptrc_glPolygonStipple)(const GLubyte * mask); +#define glPolygonStipple _ptrc_glPolygonStipple +extern void (CODEGEN_FUNCPTR *_ptrc_glPopAttrib)(void); +#define glPopAttrib _ptrc_glPopAttrib +extern void (CODEGEN_FUNCPTR *_ptrc_glPopMatrix)(void); +#define glPopMatrix _ptrc_glPopMatrix +extern void (CODEGEN_FUNCPTR *_ptrc_glPopName)(void); +#define glPopName _ptrc_glPopName +extern void (CODEGEN_FUNCPTR *_ptrc_glPushAttrib)(GLbitfield mask); +#define glPushAttrib _ptrc_glPushAttrib +extern void (CODEGEN_FUNCPTR *_ptrc_glPushMatrix)(void); +#define glPushMatrix _ptrc_glPushMatrix +extern void (CODEGEN_FUNCPTR *_ptrc_glPushName)(GLuint name); +#define glPushName _ptrc_glPushName +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2d)(GLdouble x, GLdouble y); +#define glRasterPos2d _ptrc_glRasterPos2d +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2dv)(const GLdouble * v); +#define glRasterPos2dv _ptrc_glRasterPos2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2f)(GLfloat x, GLfloat y); +#define glRasterPos2f _ptrc_glRasterPos2f +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2fv)(const GLfloat * v); +#define glRasterPos2fv _ptrc_glRasterPos2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2i)(GLint x, GLint y); +#define glRasterPos2i _ptrc_glRasterPos2i +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2iv)(const GLint * v); +#define glRasterPos2iv _ptrc_glRasterPos2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2s)(GLshort x, GLshort y); +#define glRasterPos2s _ptrc_glRasterPos2s +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos2sv)(const GLshort * v); +#define glRasterPos2sv _ptrc_glRasterPos2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3d)(GLdouble x, GLdouble y, GLdouble z); +#define glRasterPos3d _ptrc_glRasterPos3d +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3dv)(const GLdouble * v); +#define glRasterPos3dv _ptrc_glRasterPos3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3f)(GLfloat x, GLfloat y, GLfloat z); +#define glRasterPos3f _ptrc_glRasterPos3f +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3fv)(const GLfloat * v); +#define glRasterPos3fv _ptrc_glRasterPos3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3i)(GLint x, GLint y, GLint z); +#define glRasterPos3i _ptrc_glRasterPos3i +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3iv)(const GLint * v); +#define glRasterPos3iv _ptrc_glRasterPos3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3s)(GLshort x, GLshort y, GLshort z); +#define glRasterPos3s _ptrc_glRasterPos3s +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos3sv)(const GLshort * v); +#define glRasterPos3sv _ptrc_glRasterPos3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +#define glRasterPos4d _ptrc_glRasterPos4d +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4dv)(const GLdouble * v); +#define glRasterPos4dv _ptrc_glRasterPos4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +#define glRasterPos4f _ptrc_glRasterPos4f +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4fv)(const GLfloat * v); +#define glRasterPos4fv _ptrc_glRasterPos4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4i)(GLint x, GLint y, GLint z, GLint w); +#define glRasterPos4i _ptrc_glRasterPos4i +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4iv)(const GLint * v); +#define glRasterPos4iv _ptrc_glRasterPos4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4s)(GLshort x, GLshort y, GLshort z, GLshort w); +#define glRasterPos4s _ptrc_glRasterPos4s +extern void (CODEGEN_FUNCPTR *_ptrc_glRasterPos4sv)(const GLshort * v); +#define glRasterPos4sv _ptrc_glRasterPos4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glReadBuffer)(GLenum src); +#define glReadBuffer _ptrc_glReadBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void * pixels); +#define glReadPixels _ptrc_glReadPixels +extern void (CODEGEN_FUNCPTR *_ptrc_glRectd)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); +#define glRectd _ptrc_glRectd +extern void (CODEGEN_FUNCPTR *_ptrc_glRectdv)(const GLdouble * v1, const GLdouble * v2); +#define glRectdv _ptrc_glRectdv +extern void (CODEGEN_FUNCPTR *_ptrc_glRectf)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); +#define glRectf _ptrc_glRectf +extern void (CODEGEN_FUNCPTR *_ptrc_glRectfv)(const GLfloat * v1, const GLfloat * v2); +#define glRectfv _ptrc_glRectfv +extern void (CODEGEN_FUNCPTR *_ptrc_glRecti)(GLint x1, GLint y1, GLint x2, GLint y2); +#define glRecti _ptrc_glRecti +extern void (CODEGEN_FUNCPTR *_ptrc_glRectiv)(const GLint * v1, const GLint * v2); +#define glRectiv _ptrc_glRectiv +extern void (CODEGEN_FUNCPTR *_ptrc_glRects)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); +#define glRects _ptrc_glRects +extern void (CODEGEN_FUNCPTR *_ptrc_glRectsv)(const GLshort * v1, const GLshort * v2); +#define glRectsv _ptrc_glRectsv +extern GLint (CODEGEN_FUNCPTR *_ptrc_glRenderMode)(GLenum mode); +#define glRenderMode _ptrc_glRenderMode +extern void (CODEGEN_FUNCPTR *_ptrc_glRotated)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +#define glRotated _ptrc_glRotated +extern void (CODEGEN_FUNCPTR *_ptrc_glRotatef)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +#define glRotatef _ptrc_glRotatef +extern void (CODEGEN_FUNCPTR *_ptrc_glScaled)(GLdouble x, GLdouble y, GLdouble z); +#define glScaled _ptrc_glScaled +extern void (CODEGEN_FUNCPTR *_ptrc_glScalef)(GLfloat x, GLfloat y, GLfloat z); +#define glScalef _ptrc_glScalef +extern void (CODEGEN_FUNCPTR *_ptrc_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); +#define glScissor _ptrc_glScissor +extern void (CODEGEN_FUNCPTR *_ptrc_glSelectBuffer)(GLsizei size, GLuint * buffer); +#define glSelectBuffer _ptrc_glSelectBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glShadeModel)(GLenum mode); +#define glShadeModel _ptrc_glShadeModel +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilFunc)(GLenum func, GLint ref, GLuint mask); +#define glStencilFunc _ptrc_glStencilFunc +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilMask)(GLuint mask); +#define glStencilMask _ptrc_glStencilMask +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass); +#define glStencilOp _ptrc_glStencilOp +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1d)(GLdouble s); +#define glTexCoord1d _ptrc_glTexCoord1d +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1dv)(const GLdouble * v); +#define glTexCoord1dv _ptrc_glTexCoord1dv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1f)(GLfloat s); +#define glTexCoord1f _ptrc_glTexCoord1f +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1fv)(const GLfloat * v); +#define glTexCoord1fv _ptrc_glTexCoord1fv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1i)(GLint s); +#define glTexCoord1i _ptrc_glTexCoord1i +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1iv)(const GLint * v); +#define glTexCoord1iv _ptrc_glTexCoord1iv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1s)(GLshort s); +#define glTexCoord1s _ptrc_glTexCoord1s +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord1sv)(const GLshort * v); +#define glTexCoord1sv _ptrc_glTexCoord1sv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2d)(GLdouble s, GLdouble t); +#define glTexCoord2d _ptrc_glTexCoord2d +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2dv)(const GLdouble * v); +#define glTexCoord2dv _ptrc_glTexCoord2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2f)(GLfloat s, GLfloat t); +#define glTexCoord2f _ptrc_glTexCoord2f +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2fv)(const GLfloat * v); +#define glTexCoord2fv _ptrc_glTexCoord2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2i)(GLint s, GLint t); +#define glTexCoord2i _ptrc_glTexCoord2i +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2iv)(const GLint * v); +#define glTexCoord2iv _ptrc_glTexCoord2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2s)(GLshort s, GLshort t); +#define glTexCoord2s _ptrc_glTexCoord2s +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord2sv)(const GLshort * v); +#define glTexCoord2sv _ptrc_glTexCoord2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3d)(GLdouble s, GLdouble t, GLdouble r); +#define glTexCoord3d _ptrc_glTexCoord3d +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3dv)(const GLdouble * v); +#define glTexCoord3dv _ptrc_glTexCoord3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3f)(GLfloat s, GLfloat t, GLfloat r); +#define glTexCoord3f _ptrc_glTexCoord3f +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3fv)(const GLfloat * v); +#define glTexCoord3fv _ptrc_glTexCoord3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3i)(GLint s, GLint t, GLint r); +#define glTexCoord3i _ptrc_glTexCoord3i +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3iv)(const GLint * v); +#define glTexCoord3iv _ptrc_glTexCoord3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3s)(GLshort s, GLshort t, GLshort r); +#define glTexCoord3s _ptrc_glTexCoord3s +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord3sv)(const GLshort * v); +#define glTexCoord3sv _ptrc_glTexCoord3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4d)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); +#define glTexCoord4d _ptrc_glTexCoord4d +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4dv)(const GLdouble * v); +#define glTexCoord4dv _ptrc_glTexCoord4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4f)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); +#define glTexCoord4f _ptrc_glTexCoord4f +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4fv)(const GLfloat * v); +#define glTexCoord4fv _ptrc_glTexCoord4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4i)(GLint s, GLint t, GLint r, GLint q); +#define glTexCoord4i _ptrc_glTexCoord4i +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4iv)(const GLint * v); +#define glTexCoord4iv _ptrc_glTexCoord4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4s)(GLshort s, GLshort t, GLshort r, GLshort q); +#define glTexCoord4s _ptrc_glTexCoord4s +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoord4sv)(const GLshort * v); +#define glTexCoord4sv _ptrc_glTexCoord4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexEnvf)(GLenum target, GLenum pname, GLfloat param); +#define glTexEnvf _ptrc_glTexEnvf +extern void (CODEGEN_FUNCPTR *_ptrc_glTexEnvfv)(GLenum target, GLenum pname, const GLfloat * params); +#define glTexEnvfv _ptrc_glTexEnvfv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexEnvi)(GLenum target, GLenum pname, GLint param); +#define glTexEnvi _ptrc_glTexEnvi +extern void (CODEGEN_FUNCPTR *_ptrc_glTexEnviv)(GLenum target, GLenum pname, const GLint * params); +#define glTexEnviv _ptrc_glTexEnviv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGend)(GLenum coord, GLenum pname, GLdouble param); +#define glTexGend _ptrc_glTexGend +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGendv)(GLenum coord, GLenum pname, const GLdouble * params); +#define glTexGendv _ptrc_glTexGendv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGenf)(GLenum coord, GLenum pname, GLfloat param); +#define glTexGenf _ptrc_glTexGenf +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGenfv)(GLenum coord, GLenum pname, const GLfloat * params); +#define glTexGenfv _ptrc_glTexGenfv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGeni)(GLenum coord, GLenum pname, GLint param); +#define glTexGeni _ptrc_glTexGeni +extern void (CODEGEN_FUNCPTR *_ptrc_glTexGeniv)(GLenum coord, GLenum pname, const GLint * params); +#define glTexGeniv _ptrc_glTexGeniv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void * pixels); +#define glTexImage1D _ptrc_glTexImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels); +#define glTexImage2D _ptrc_glTexImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); +#define glTexParameterf _ptrc_glTexParameterf +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat * params); +#define glTexParameterfv _ptrc_glTexParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameteri)(GLenum target, GLenum pname, GLint param); +#define glTexParameteri _ptrc_glTexParameteri +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameteriv)(GLenum target, GLenum pname, const GLint * params); +#define glTexParameteriv _ptrc_glTexParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glTranslated)(GLdouble x, GLdouble y, GLdouble z); +#define glTranslated _ptrc_glTranslated +extern void (CODEGEN_FUNCPTR *_ptrc_glTranslatef)(GLfloat x, GLfloat y, GLfloat z); +#define glTranslatef _ptrc_glTranslatef +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2d)(GLdouble x, GLdouble y); +#define glVertex2d _ptrc_glVertex2d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2dv)(const GLdouble * v); +#define glVertex2dv _ptrc_glVertex2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2f)(GLfloat x, GLfloat y); +#define glVertex2f _ptrc_glVertex2f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2fv)(const GLfloat * v); +#define glVertex2fv _ptrc_glVertex2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2i)(GLint x, GLint y); +#define glVertex2i _ptrc_glVertex2i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2iv)(const GLint * v); +#define glVertex2iv _ptrc_glVertex2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2s)(GLshort x, GLshort y); +#define glVertex2s _ptrc_glVertex2s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex2sv)(const GLshort * v); +#define glVertex2sv _ptrc_glVertex2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3d)(GLdouble x, GLdouble y, GLdouble z); +#define glVertex3d _ptrc_glVertex3d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3dv)(const GLdouble * v); +#define glVertex3dv _ptrc_glVertex3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3f)(GLfloat x, GLfloat y, GLfloat z); +#define glVertex3f _ptrc_glVertex3f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3fv)(const GLfloat * v); +#define glVertex3fv _ptrc_glVertex3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3i)(GLint x, GLint y, GLint z); +#define glVertex3i _ptrc_glVertex3i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3iv)(const GLint * v); +#define glVertex3iv _ptrc_glVertex3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3s)(GLshort x, GLshort y, GLshort z); +#define glVertex3s _ptrc_glVertex3s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex3sv)(const GLshort * v); +#define glVertex3sv _ptrc_glVertex3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +#define glVertex4d _ptrc_glVertex4d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4dv)(const GLdouble * v); +#define glVertex4dv _ptrc_glVertex4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +#define glVertex4f _ptrc_glVertex4f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4fv)(const GLfloat * v); +#define glVertex4fv _ptrc_glVertex4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4i)(GLint x, GLint y, GLint z, GLint w); +#define glVertex4i _ptrc_glVertex4i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4iv)(const GLint * v); +#define glVertex4iv _ptrc_glVertex4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4s)(GLshort x, GLshort y, GLshort z, GLshort w); +#define glVertex4s _ptrc_glVertex4s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertex4sv)(const GLshort * v); +#define glVertex4sv _ptrc_glVertex4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); +#define glViewport _ptrc_glViewport + +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glAreTexturesResident)(GLsizei n, const GLuint * textures, GLboolean * residences); +#define glAreTexturesResident _ptrc_glAreTexturesResident +extern void (CODEGEN_FUNCPTR *_ptrc_glArrayElement)(GLint i); +#define glArrayElement _ptrc_glArrayElement +extern void (CODEGEN_FUNCPTR *_ptrc_glBindTexture)(GLenum target, GLuint texture); +#define glBindTexture _ptrc_glBindTexture +extern void (CODEGEN_FUNCPTR *_ptrc_glColorPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer); +#define glColorPointer _ptrc_glColorPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +#define glCopyTexImage1D _ptrc_glCopyTexImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +#define glCopyTexImage2D _ptrc_glCopyTexImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +#define glCopyTexSubImage1D _ptrc_glCopyTexSubImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#define glCopyTexSubImage2D _ptrc_glCopyTexSubImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteTextures)(GLsizei n, const GLuint * textures); +#define glDeleteTextures _ptrc_glDeleteTextures +extern void (CODEGEN_FUNCPTR *_ptrc_glDisableClientState)(GLenum ren_array); +#define glDisableClientState _ptrc_glDisableClientState +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawArrays)(GLenum mode, GLint first, GLsizei count); +#define glDrawArrays _ptrc_glDrawArrays +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawElements)(GLenum mode, GLsizei count, GLenum type, const void * indices); +#define glDrawElements _ptrc_glDrawElements +extern void (CODEGEN_FUNCPTR *_ptrc_glEdgeFlagPointer)(GLsizei stride, const void * pointer); +#define glEdgeFlagPointer _ptrc_glEdgeFlagPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glEnableClientState)(GLenum ren_array); +#define glEnableClientState _ptrc_glEnableClientState +extern void (CODEGEN_FUNCPTR *_ptrc_glGenTextures)(GLsizei n, GLuint * textures); +#define glGenTextures _ptrc_glGenTextures +extern void (CODEGEN_FUNCPTR *_ptrc_glGetPointerv)(GLenum pname, void ** params); +#define glGetPointerv _ptrc_glGetPointerv +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexPointer)(GLenum type, GLsizei stride, const void * pointer); +#define glIndexPointer _ptrc_glIndexPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexub)(GLubyte c); +#define glIndexub _ptrc_glIndexub +extern void (CODEGEN_FUNCPTR *_ptrc_glIndexubv)(const GLubyte * c); +#define glIndexubv _ptrc_glIndexubv +extern void (CODEGEN_FUNCPTR *_ptrc_glInterleavedArrays)(GLenum format, GLsizei stride, const void * pointer); +#define glInterleavedArrays _ptrc_glInterleavedArrays +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsTexture)(GLuint texture); +#define glIsTexture _ptrc_glIsTexture +extern void (CODEGEN_FUNCPTR *_ptrc_glNormalPointer)(GLenum type, GLsizei stride, const void * pointer); +#define glNormalPointer _ptrc_glNormalPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glPolygonOffset)(GLfloat factor, GLfloat units); +#define glPolygonOffset _ptrc_glPolygonOffset +extern void (CODEGEN_FUNCPTR *_ptrc_glPopClientAttrib)(void); +#define glPopClientAttrib _ptrc_glPopClientAttrib +extern void (CODEGEN_FUNCPTR *_ptrc_glPrioritizeTextures)(GLsizei n, const GLuint * textures, const GLfloat * priorities); +#define glPrioritizeTextures _ptrc_glPrioritizeTextures +extern void (CODEGEN_FUNCPTR *_ptrc_glPushClientAttrib)(GLbitfield mask); +#define glPushClientAttrib _ptrc_glPushClientAttrib +extern void (CODEGEN_FUNCPTR *_ptrc_glTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer); +#define glTexCoordPointer _ptrc_glTexCoordPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void * pixels); +#define glTexSubImage1D _ptrc_glTexSubImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels); +#define glTexSubImage2D _ptrc_glTexSubImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer); +#define glVertexPointer _ptrc_glVertexPointer + +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#define glCopyTexSubImage3D _ptrc_glCopyTexSubImage3D +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices); +#define glDrawRangeElements _ptrc_glDrawRangeElements +extern void (CODEGEN_FUNCPTR *_ptrc_glTexImage3D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels); +#define glTexImage3D _ptrc_glTexImage3D +extern void (CODEGEN_FUNCPTR *_ptrc_glTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels); +#define glTexSubImage3D _ptrc_glTexSubImage3D + +extern void (CODEGEN_FUNCPTR *_ptrc_glActiveTexture)(GLenum texture); +#define glActiveTexture _ptrc_glActiveTexture +extern void (CODEGEN_FUNCPTR *_ptrc_glClientActiveTexture)(GLenum texture); +#define glClientActiveTexture _ptrc_glClientActiveTexture +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage1D _ptrc_glCompressedTexImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage2D _ptrc_glCompressedTexImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data); +#define glCompressedTexImage3D _ptrc_glCompressedTexImage3D +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage1D _ptrc_glCompressedTexSubImage1D +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage2D _ptrc_glCompressedTexSubImage2D +extern void (CODEGEN_FUNCPTR *_ptrc_glCompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data); +#define glCompressedTexSubImage3D _ptrc_glCompressedTexSubImage3D +extern void (CODEGEN_FUNCPTR *_ptrc_glGetCompressedTexImage)(GLenum target, GLint level, void * img); +#define glGetCompressedTexImage _ptrc_glGetCompressedTexImage +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadTransposeMatrixd)(const GLdouble * m); +#define glLoadTransposeMatrixd _ptrc_glLoadTransposeMatrixd +extern void (CODEGEN_FUNCPTR *_ptrc_glLoadTransposeMatrixf)(const GLfloat * m); +#define glLoadTransposeMatrixf _ptrc_glLoadTransposeMatrixf +extern void (CODEGEN_FUNCPTR *_ptrc_glMultTransposeMatrixd)(const GLdouble * m); +#define glMultTransposeMatrixd _ptrc_glMultTransposeMatrixd +extern void (CODEGEN_FUNCPTR *_ptrc_glMultTransposeMatrixf)(const GLfloat * m); +#define glMultTransposeMatrixf _ptrc_glMultTransposeMatrixf +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1d)(GLenum target, GLdouble s); +#define glMultiTexCoord1d _ptrc_glMultiTexCoord1d +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1dv)(GLenum target, const GLdouble * v); +#define glMultiTexCoord1dv _ptrc_glMultiTexCoord1dv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1f)(GLenum target, GLfloat s); +#define glMultiTexCoord1f _ptrc_glMultiTexCoord1f +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1fv)(GLenum target, const GLfloat * v); +#define glMultiTexCoord1fv _ptrc_glMultiTexCoord1fv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1i)(GLenum target, GLint s); +#define glMultiTexCoord1i _ptrc_glMultiTexCoord1i +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1iv)(GLenum target, const GLint * v); +#define glMultiTexCoord1iv _ptrc_glMultiTexCoord1iv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1s)(GLenum target, GLshort s); +#define glMultiTexCoord1s _ptrc_glMultiTexCoord1s +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord1sv)(GLenum target, const GLshort * v); +#define glMultiTexCoord1sv _ptrc_glMultiTexCoord1sv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t); +#define glMultiTexCoord2d _ptrc_glMultiTexCoord2d +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2dv)(GLenum target, const GLdouble * v); +#define glMultiTexCoord2dv _ptrc_glMultiTexCoord2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t); +#define glMultiTexCoord2f _ptrc_glMultiTexCoord2f +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2fv)(GLenum target, const GLfloat * v); +#define glMultiTexCoord2fv _ptrc_glMultiTexCoord2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2i)(GLenum target, GLint s, GLint t); +#define glMultiTexCoord2i _ptrc_glMultiTexCoord2i +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2iv)(GLenum target, const GLint * v); +#define glMultiTexCoord2iv _ptrc_glMultiTexCoord2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t); +#define glMultiTexCoord2s _ptrc_glMultiTexCoord2s +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord2sv)(GLenum target, const GLshort * v); +#define glMultiTexCoord2sv _ptrc_glMultiTexCoord2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r); +#define glMultiTexCoord3d _ptrc_glMultiTexCoord3d +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3dv)(GLenum target, const GLdouble * v); +#define glMultiTexCoord3dv _ptrc_glMultiTexCoord3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r); +#define glMultiTexCoord3f _ptrc_glMultiTexCoord3f +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3fv)(GLenum target, const GLfloat * v); +#define glMultiTexCoord3fv _ptrc_glMultiTexCoord3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r); +#define glMultiTexCoord3i _ptrc_glMultiTexCoord3i +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3iv)(GLenum target, const GLint * v); +#define glMultiTexCoord3iv _ptrc_glMultiTexCoord3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r); +#define glMultiTexCoord3s _ptrc_glMultiTexCoord3s +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord3sv)(GLenum target, const GLshort * v); +#define glMultiTexCoord3sv _ptrc_glMultiTexCoord3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +#define glMultiTexCoord4d _ptrc_glMultiTexCoord4d +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4dv)(GLenum target, const GLdouble * v); +#define glMultiTexCoord4dv _ptrc_glMultiTexCoord4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +#define glMultiTexCoord4f _ptrc_glMultiTexCoord4f +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4fv)(GLenum target, const GLfloat * v); +#define glMultiTexCoord4fv _ptrc_glMultiTexCoord4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q); +#define glMultiTexCoord4i _ptrc_glMultiTexCoord4i +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4iv)(GLenum target, const GLint * v); +#define glMultiTexCoord4iv _ptrc_glMultiTexCoord4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +#define glMultiTexCoord4s _ptrc_glMultiTexCoord4s +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiTexCoord4sv)(GLenum target, const GLshort * v); +#define glMultiTexCoord4sv _ptrc_glMultiTexCoord4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glSampleCoverage)(GLfloat value, GLboolean invert); +#define glSampleCoverage _ptrc_glSampleCoverage + +extern void (CODEGEN_FUNCPTR *_ptrc_glBlendColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#define glBlendColor _ptrc_glBlendColor +extern void (CODEGEN_FUNCPTR *_ptrc_glBlendEquation)(GLenum mode); +#define glBlendEquation _ptrc_glBlendEquation +extern void (CODEGEN_FUNCPTR *_ptrc_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#define glBlendFuncSeparate _ptrc_glBlendFuncSeparate +extern void (CODEGEN_FUNCPTR *_ptrc_glFogCoordPointer)(GLenum type, GLsizei stride, const void * pointer); +#define glFogCoordPointer _ptrc_glFogCoordPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glFogCoordd)(GLdouble coord); +#define glFogCoordd _ptrc_glFogCoordd +extern void (CODEGEN_FUNCPTR *_ptrc_glFogCoorddv)(const GLdouble * coord); +#define glFogCoorddv _ptrc_glFogCoorddv +extern void (CODEGEN_FUNCPTR *_ptrc_glFogCoordf)(GLfloat coord); +#define glFogCoordf _ptrc_glFogCoordf +extern void (CODEGEN_FUNCPTR *_ptrc_glFogCoordfv)(const GLfloat * coord); +#define glFogCoordfv _ptrc_glFogCoordfv +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawArrays)(GLenum mode, const GLint * first, const GLsizei * count, GLsizei drawcount); +#define glMultiDrawArrays _ptrc_glMultiDrawArrays +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawElements)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount); +#define glMultiDrawElements _ptrc_glMultiDrawElements +extern void (CODEGEN_FUNCPTR *_ptrc_glPointParameterf)(GLenum pname, GLfloat param); +#define glPointParameterf _ptrc_glPointParameterf +extern void (CODEGEN_FUNCPTR *_ptrc_glPointParameterfv)(GLenum pname, const GLfloat * params); +#define glPointParameterfv _ptrc_glPointParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glPointParameteri)(GLenum pname, GLint param); +#define glPointParameteri _ptrc_glPointParameteri +extern void (CODEGEN_FUNCPTR *_ptrc_glPointParameteriv)(GLenum pname, const GLint * params); +#define glPointParameteriv _ptrc_glPointParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3b)(GLbyte red, GLbyte green, GLbyte blue); +#define glSecondaryColor3b _ptrc_glSecondaryColor3b +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3bv)(const GLbyte * v); +#define glSecondaryColor3bv _ptrc_glSecondaryColor3bv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3d)(GLdouble red, GLdouble green, GLdouble blue); +#define glSecondaryColor3d _ptrc_glSecondaryColor3d +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3dv)(const GLdouble * v); +#define glSecondaryColor3dv _ptrc_glSecondaryColor3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3f)(GLfloat red, GLfloat green, GLfloat blue); +#define glSecondaryColor3f _ptrc_glSecondaryColor3f +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3fv)(const GLfloat * v); +#define glSecondaryColor3fv _ptrc_glSecondaryColor3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3i)(GLint red, GLint green, GLint blue); +#define glSecondaryColor3i _ptrc_glSecondaryColor3i +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3iv)(const GLint * v); +#define glSecondaryColor3iv _ptrc_glSecondaryColor3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3s)(GLshort red, GLshort green, GLshort blue); +#define glSecondaryColor3s _ptrc_glSecondaryColor3s +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3sv)(const GLshort * v); +#define glSecondaryColor3sv _ptrc_glSecondaryColor3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ub)(GLubyte red, GLubyte green, GLubyte blue); +#define glSecondaryColor3ub _ptrc_glSecondaryColor3ub +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ubv)(const GLubyte * v); +#define glSecondaryColor3ubv _ptrc_glSecondaryColor3ubv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3ui)(GLuint red, GLuint green, GLuint blue); +#define glSecondaryColor3ui _ptrc_glSecondaryColor3ui +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3uiv)(const GLuint * v); +#define glSecondaryColor3uiv _ptrc_glSecondaryColor3uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3us)(GLushort red, GLushort green, GLushort blue); +#define glSecondaryColor3us _ptrc_glSecondaryColor3us +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColor3usv)(const GLushort * v); +#define glSecondaryColor3usv _ptrc_glSecondaryColor3usv +extern void (CODEGEN_FUNCPTR *_ptrc_glSecondaryColorPointer)(GLint size, GLenum type, GLsizei stride, const void * pointer); +#define glSecondaryColorPointer _ptrc_glSecondaryColorPointer +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2d)(GLdouble x, GLdouble y); +#define glWindowPos2d _ptrc_glWindowPos2d +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2dv)(const GLdouble * v); +#define glWindowPos2dv _ptrc_glWindowPos2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2f)(GLfloat x, GLfloat y); +#define glWindowPos2f _ptrc_glWindowPos2f +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2fv)(const GLfloat * v); +#define glWindowPos2fv _ptrc_glWindowPos2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2i)(GLint x, GLint y); +#define glWindowPos2i _ptrc_glWindowPos2i +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2iv)(const GLint * v); +#define glWindowPos2iv _ptrc_glWindowPos2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2s)(GLshort x, GLshort y); +#define glWindowPos2s _ptrc_glWindowPos2s +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos2sv)(const GLshort * v); +#define glWindowPos2sv _ptrc_glWindowPos2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3d)(GLdouble x, GLdouble y, GLdouble z); +#define glWindowPos3d _ptrc_glWindowPos3d +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3dv)(const GLdouble * v); +#define glWindowPos3dv _ptrc_glWindowPos3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3f)(GLfloat x, GLfloat y, GLfloat z); +#define glWindowPos3f _ptrc_glWindowPos3f +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3fv)(const GLfloat * v); +#define glWindowPos3fv _ptrc_glWindowPos3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3i)(GLint x, GLint y, GLint z); +#define glWindowPos3i _ptrc_glWindowPos3i +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3iv)(const GLint * v); +#define glWindowPos3iv _ptrc_glWindowPos3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3s)(GLshort x, GLshort y, GLshort z); +#define glWindowPos3s _ptrc_glWindowPos3s +extern void (CODEGEN_FUNCPTR *_ptrc_glWindowPos3sv)(const GLshort * v); +#define glWindowPos3sv _ptrc_glWindowPos3sv + +extern void (CODEGEN_FUNCPTR *_ptrc_glBeginQuery)(GLenum target, GLuint id); +#define glBeginQuery _ptrc_glBeginQuery +extern void (CODEGEN_FUNCPTR *_ptrc_glBindBuffer)(GLenum target, GLuint buffer); +#define glBindBuffer _ptrc_glBindBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glBufferData)(GLenum target, GLsizeiptr size, const void * data, GLenum usage); +#define glBufferData _ptrc_glBufferData +extern void (CODEGEN_FUNCPTR *_ptrc_glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const void * data); +#define glBufferSubData _ptrc_glBufferSubData +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteBuffers)(GLsizei n, const GLuint * buffers); +#define glDeleteBuffers _ptrc_glDeleteBuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteQueries)(GLsizei n, const GLuint * ids); +#define glDeleteQueries _ptrc_glDeleteQueries +extern void (CODEGEN_FUNCPTR *_ptrc_glEndQuery)(GLenum target); +#define glEndQuery _ptrc_glEndQuery +extern void (CODEGEN_FUNCPTR *_ptrc_glGenBuffers)(GLsizei n, GLuint * buffers); +#define glGenBuffers _ptrc_glGenBuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glGenQueries)(GLsizei n, GLuint * ids); +#define glGenQueries _ptrc_glGenQueries +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBufferParameteriv)(GLenum target, GLenum pname, GLint * params); +#define glGetBufferParameteriv _ptrc_glGetBufferParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBufferPointerv)(GLenum target, GLenum pname, void ** params); +#define glGetBufferPointerv _ptrc_glGetBufferPointerv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, void * data); +#define glGetBufferSubData _ptrc_glGetBufferSubData +extern void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectiv)(GLuint id, GLenum pname, GLint * params); +#define glGetQueryObjectiv _ptrc_glGetQueryObjectiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectuiv)(GLuint id, GLenum pname, GLuint * params); +#define glGetQueryObjectuiv _ptrc_glGetQueryObjectuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetQueryiv)(GLenum target, GLenum pname, GLint * params); +#define glGetQueryiv _ptrc_glGetQueryiv +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsBuffer)(GLuint buffer); +#define glIsBuffer _ptrc_glIsBuffer +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsQuery)(GLuint id); +#define glIsQuery _ptrc_glIsQuery +extern void * (CODEGEN_FUNCPTR *_ptrc_glMapBuffer)(GLenum target, GLenum access); +#define glMapBuffer _ptrc_glMapBuffer +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glUnmapBuffer)(GLenum target); +#define glUnmapBuffer _ptrc_glUnmapBuffer + +extern void (CODEGEN_FUNCPTR *_ptrc_glAttachShader)(GLuint program, GLuint shader); +#define glAttachShader _ptrc_glAttachShader +extern void (CODEGEN_FUNCPTR *_ptrc_glBindAttribLocation)(GLuint program, GLuint index, const GLchar * name); +#define glBindAttribLocation _ptrc_glBindAttribLocation +extern void (CODEGEN_FUNCPTR *_ptrc_glBlendEquationSeparate)(GLenum modeRGB, GLenum modeAlpha); +#define glBlendEquationSeparate _ptrc_glBlendEquationSeparate +extern void (CODEGEN_FUNCPTR *_ptrc_glCompileShader)(GLuint shader); +#define glCompileShader _ptrc_glCompileShader +extern GLuint (CODEGEN_FUNCPTR *_ptrc_glCreateProgram)(void); +#define glCreateProgram _ptrc_glCreateProgram +extern GLuint (CODEGEN_FUNCPTR *_ptrc_glCreateShader)(GLenum type); +#define glCreateShader _ptrc_glCreateShader +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteProgram)(GLuint program); +#define glDeleteProgram _ptrc_glDeleteProgram +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteShader)(GLuint shader); +#define glDeleteShader _ptrc_glDeleteShader +extern void (CODEGEN_FUNCPTR *_ptrc_glDetachShader)(GLuint program, GLuint shader); +#define glDetachShader _ptrc_glDetachShader +extern void (CODEGEN_FUNCPTR *_ptrc_glDisableVertexAttribArray)(GLuint index); +#define glDisableVertexAttribArray _ptrc_glDisableVertexAttribArray +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawBuffers)(GLsizei n, const GLenum * bufs); +#define glDrawBuffers _ptrc_glDrawBuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glEnableVertexAttribArray)(GLuint index); +#define glEnableVertexAttribArray _ptrc_glEnableVertexAttribArray +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveAttrib)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name); +#define glGetActiveAttrib _ptrc_glGetActiveAttrib +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniform)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name); +#define glGetActiveUniform _ptrc_glGetActiveUniform +extern void (CODEGEN_FUNCPTR *_ptrc_glGetAttachedShaders)(GLuint program, GLsizei maxCount, GLsizei * count, GLuint * shaders); +#define glGetAttachedShaders _ptrc_glGetAttachedShaders +extern GLint (CODEGEN_FUNCPTR *_ptrc_glGetAttribLocation)(GLuint program, const GLchar * name); +#define glGetAttribLocation _ptrc_glGetAttribLocation +extern void (CODEGEN_FUNCPTR *_ptrc_glGetProgramInfoLog)(GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog); +#define glGetProgramInfoLog _ptrc_glGetProgramInfoLog +extern void (CODEGEN_FUNCPTR *_ptrc_glGetProgramiv)(GLuint program, GLenum pname, GLint * params); +#define glGetProgramiv _ptrc_glGetProgramiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetShaderInfoLog)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog); +#define glGetShaderInfoLog _ptrc_glGetShaderInfoLog +extern void (CODEGEN_FUNCPTR *_ptrc_glGetShaderSource)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * source); +#define glGetShaderSource _ptrc_glGetShaderSource +extern void (CODEGEN_FUNCPTR *_ptrc_glGetShaderiv)(GLuint shader, GLenum pname, GLint * params); +#define glGetShaderiv _ptrc_glGetShaderiv +extern GLint (CODEGEN_FUNCPTR *_ptrc_glGetUniformLocation)(GLuint program, const GLchar * name); +#define glGetUniformLocation _ptrc_glGetUniformLocation +extern void (CODEGEN_FUNCPTR *_ptrc_glGetUniformfv)(GLuint program, GLint location, GLfloat * params); +#define glGetUniformfv _ptrc_glGetUniformfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetUniformiv)(GLuint program, GLint location, GLint * params); +#define glGetUniformiv _ptrc_glGetUniformiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribPointerv)(GLuint index, GLenum pname, void ** pointer); +#define glGetVertexAttribPointerv _ptrc_glGetVertexAttribPointerv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribdv)(GLuint index, GLenum pname, GLdouble * params); +#define glGetVertexAttribdv _ptrc_glGetVertexAttribdv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribfv)(GLuint index, GLenum pname, GLfloat * params); +#define glGetVertexAttribfv _ptrc_glGetVertexAttribfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribiv)(GLuint index, GLenum pname, GLint * params); +#define glGetVertexAttribiv _ptrc_glGetVertexAttribiv +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsProgram)(GLuint program); +#define glIsProgram _ptrc_glIsProgram +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsShader)(GLuint shader); +#define glIsShader _ptrc_glIsShader +extern void (CODEGEN_FUNCPTR *_ptrc_glLinkProgram)(GLuint program); +#define glLinkProgram _ptrc_glLinkProgram +extern void (CODEGEN_FUNCPTR *_ptrc_glShaderSource)(GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length); +#define glShaderSource _ptrc_glShaderSource +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilFuncSeparate)(GLenum face, GLenum func, GLint ref, GLuint mask); +#define glStencilFuncSeparate _ptrc_glStencilFuncSeparate +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilMaskSeparate)(GLenum face, GLuint mask); +#define glStencilMaskSeparate _ptrc_glStencilMaskSeparate +extern void (CODEGEN_FUNCPTR *_ptrc_glStencilOpSeparate)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +#define glStencilOpSeparate _ptrc_glStencilOpSeparate +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1f)(GLint location, GLfloat v0); +#define glUniform1f _ptrc_glUniform1f +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1fv)(GLint location, GLsizei count, const GLfloat * value); +#define glUniform1fv _ptrc_glUniform1fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1i)(GLint location, GLint v0); +#define glUniform1i _ptrc_glUniform1i +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1iv)(GLint location, GLsizei count, const GLint * value); +#define glUniform1iv _ptrc_glUniform1iv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2f)(GLint location, GLfloat v0, GLfloat v1); +#define glUniform2f _ptrc_glUniform2f +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2fv)(GLint location, GLsizei count, const GLfloat * value); +#define glUniform2fv _ptrc_glUniform2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2i)(GLint location, GLint v0, GLint v1); +#define glUniform2i _ptrc_glUniform2i +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2iv)(GLint location, GLsizei count, const GLint * value); +#define glUniform2iv _ptrc_glUniform2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +#define glUniform3f _ptrc_glUniform3f +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3fv)(GLint location, GLsizei count, const GLfloat * value); +#define glUniform3fv _ptrc_glUniform3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3i)(GLint location, GLint v0, GLint v1, GLint v2); +#define glUniform3i _ptrc_glUniform3i +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3iv)(GLint location, GLsizei count, const GLint * value); +#define glUniform3iv _ptrc_glUniform3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +#define glUniform4f _ptrc_glUniform4f +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4fv)(GLint location, GLsizei count, const GLfloat * value); +#define glUniform4fv _ptrc_glUniform4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4i)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +#define glUniform4i _ptrc_glUniform4i +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4iv)(GLint location, GLsizei count, const GLint * value); +#define glUniform4iv _ptrc_glUniform4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix2fv _ptrc_glUniformMatrix2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix3fv _ptrc_glUniformMatrix3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix4fv _ptrc_glUniformMatrix4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUseProgram)(GLuint program); +#define glUseProgram _ptrc_glUseProgram +extern void (CODEGEN_FUNCPTR *_ptrc_glValidateProgram)(GLuint program); +#define glValidateProgram _ptrc_glValidateProgram +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1d)(GLuint index, GLdouble x); +#define glVertexAttrib1d _ptrc_glVertexAttrib1d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1dv)(GLuint index, const GLdouble * v); +#define glVertexAttrib1dv _ptrc_glVertexAttrib1dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1f)(GLuint index, GLfloat x); +#define glVertexAttrib1f _ptrc_glVertexAttrib1f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1fv)(GLuint index, const GLfloat * v); +#define glVertexAttrib1fv _ptrc_glVertexAttrib1fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1s)(GLuint index, GLshort x); +#define glVertexAttrib1s _ptrc_glVertexAttrib1s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib1sv)(GLuint index, const GLshort * v); +#define glVertexAttrib1sv _ptrc_glVertexAttrib1sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2d)(GLuint index, GLdouble x, GLdouble y); +#define glVertexAttrib2d _ptrc_glVertexAttrib2d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2dv)(GLuint index, const GLdouble * v); +#define glVertexAttrib2dv _ptrc_glVertexAttrib2dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2f)(GLuint index, GLfloat x, GLfloat y); +#define glVertexAttrib2f _ptrc_glVertexAttrib2f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2fv)(GLuint index, const GLfloat * v); +#define glVertexAttrib2fv _ptrc_glVertexAttrib2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2s)(GLuint index, GLshort x, GLshort y); +#define glVertexAttrib2s _ptrc_glVertexAttrib2s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib2sv)(GLuint index, const GLshort * v); +#define glVertexAttrib2sv _ptrc_glVertexAttrib2sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3d)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +#define glVertexAttrib3d _ptrc_glVertexAttrib3d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3dv)(GLuint index, const GLdouble * v); +#define glVertexAttrib3dv _ptrc_glVertexAttrib3dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3f)(GLuint index, GLfloat x, GLfloat y, GLfloat z); +#define glVertexAttrib3f _ptrc_glVertexAttrib3f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3fv)(GLuint index, const GLfloat * v); +#define glVertexAttrib3fv _ptrc_glVertexAttrib3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3s)(GLuint index, GLshort x, GLshort y, GLshort z); +#define glVertexAttrib3s _ptrc_glVertexAttrib3s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib3sv)(GLuint index, const GLshort * v); +#define glVertexAttrib3sv _ptrc_glVertexAttrib3sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nbv)(GLuint index, const GLbyte * v); +#define glVertexAttrib4Nbv _ptrc_glVertexAttrib4Nbv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Niv)(GLuint index, const GLint * v); +#define glVertexAttrib4Niv _ptrc_glVertexAttrib4Niv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nsv)(GLuint index, const GLshort * v); +#define glVertexAttrib4Nsv _ptrc_glVertexAttrib4Nsv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nub)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +#define glVertexAttrib4Nub _ptrc_glVertexAttrib4Nub +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nubv)(GLuint index, const GLubyte * v); +#define glVertexAttrib4Nubv _ptrc_glVertexAttrib4Nubv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nuiv)(GLuint index, const GLuint * v); +#define glVertexAttrib4Nuiv _ptrc_glVertexAttrib4Nuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4Nusv)(GLuint index, const GLushort * v); +#define glVertexAttrib4Nusv _ptrc_glVertexAttrib4Nusv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4bv)(GLuint index, const GLbyte * v); +#define glVertexAttrib4bv _ptrc_glVertexAttrib4bv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4d)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +#define glVertexAttrib4d _ptrc_glVertexAttrib4d +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4dv)(GLuint index, const GLdouble * v); +#define glVertexAttrib4dv _ptrc_glVertexAttrib4dv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4f)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +#define glVertexAttrib4f _ptrc_glVertexAttrib4f +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4fv)(GLuint index, const GLfloat * v); +#define glVertexAttrib4fv _ptrc_glVertexAttrib4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4iv)(GLuint index, const GLint * v); +#define glVertexAttrib4iv _ptrc_glVertexAttrib4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4s)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +#define glVertexAttrib4s _ptrc_glVertexAttrib4s +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4sv)(GLuint index, const GLshort * v); +#define glVertexAttrib4sv _ptrc_glVertexAttrib4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4ubv)(GLuint index, const GLubyte * v); +#define glVertexAttrib4ubv _ptrc_glVertexAttrib4ubv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4uiv)(GLuint index, const GLuint * v); +#define glVertexAttrib4uiv _ptrc_glVertexAttrib4uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttrib4usv)(GLuint index, const GLushort * v); +#define glVertexAttrib4usv _ptrc_glVertexAttrib4usv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribPointer)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer); +#define glVertexAttribPointer _ptrc_glVertexAttribPointer + +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix2x3fv _ptrc_glUniformMatrix2x3fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix2x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix2x4fv _ptrc_glUniformMatrix2x4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix3x2fv _ptrc_glUniformMatrix3x2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix3x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix3x4fv _ptrc_glUniformMatrix3x4fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix4x2fv _ptrc_glUniformMatrix4x2fv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformMatrix4x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +#define glUniformMatrix4x3fv _ptrc_glUniformMatrix4x3fv + +extern void (CODEGEN_FUNCPTR *_ptrc_glBeginConditionalRender)(GLuint id, GLenum mode); +#define glBeginConditionalRender _ptrc_glBeginConditionalRender +extern void (CODEGEN_FUNCPTR *_ptrc_glBeginTransformFeedback)(GLenum primitiveMode); +#define glBeginTransformFeedback _ptrc_glBeginTransformFeedback +extern void (CODEGEN_FUNCPTR *_ptrc_glBindBufferBase)(GLenum target, GLuint index, GLuint buffer); +#define glBindBufferBase _ptrc_glBindBufferBase +extern void (CODEGEN_FUNCPTR *_ptrc_glBindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +#define glBindBufferRange _ptrc_glBindBufferRange +extern void (CODEGEN_FUNCPTR *_ptrc_glBindFragDataLocation)(GLuint program, GLuint color, const GLchar * name); +#define glBindFragDataLocation _ptrc_glBindFragDataLocation +extern void (CODEGEN_FUNCPTR *_ptrc_glBindFramebuffer)(GLenum target, GLuint framebuffer); +#define glBindFramebuffer _ptrc_glBindFramebuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glBindRenderbuffer)(GLenum target, GLuint renderbuffer); +#define glBindRenderbuffer _ptrc_glBindRenderbuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glBindVertexArray)(GLuint ren_array); +#define glBindVertexArray _ptrc_glBindVertexArray +extern void (CODEGEN_FUNCPTR *_ptrc_glBlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#define glBlitFramebuffer _ptrc_glBlitFramebuffer +extern GLenum (CODEGEN_FUNCPTR *_ptrc_glCheckFramebufferStatus)(GLenum target); +#define glCheckFramebufferStatus _ptrc_glCheckFramebufferStatus +extern void (CODEGEN_FUNCPTR *_ptrc_glClampColor)(GLenum target, GLenum clamp); +#define glClampColor _ptrc_glClampColor +extern void (CODEGEN_FUNCPTR *_ptrc_glClearBufferfi)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +#define glClearBufferfi _ptrc_glClearBufferfi +extern void (CODEGEN_FUNCPTR *_ptrc_glClearBufferfv)(GLenum buffer, GLint drawbuffer, const GLfloat * value); +#define glClearBufferfv _ptrc_glClearBufferfv +extern void (CODEGEN_FUNCPTR *_ptrc_glClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint * value); +#define glClearBufferiv _ptrc_glClearBufferiv +extern void (CODEGEN_FUNCPTR *_ptrc_glClearBufferuiv)(GLenum buffer, GLint drawbuffer, const GLuint * value); +#define glClearBufferuiv _ptrc_glClearBufferuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glColorMaski)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#define glColorMaski _ptrc_glColorMaski +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteFramebuffers)(GLsizei n, const GLuint * framebuffers); +#define glDeleteFramebuffers _ptrc_glDeleteFramebuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteRenderbuffers)(GLsizei n, const GLuint * renderbuffers); +#define glDeleteRenderbuffers _ptrc_glDeleteRenderbuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteVertexArrays)(GLsizei n, const GLuint * arrays); +#define glDeleteVertexArrays _ptrc_glDeleteVertexArrays +extern void (CODEGEN_FUNCPTR *_ptrc_glDisablei)(GLenum target, GLuint index); +#define glDisablei _ptrc_glDisablei +extern void (CODEGEN_FUNCPTR *_ptrc_glEnablei)(GLenum target, GLuint index); +#define glEnablei _ptrc_glEnablei +extern void (CODEGEN_FUNCPTR *_ptrc_glEndConditionalRender)(void); +#define glEndConditionalRender _ptrc_glEndConditionalRender +extern void (CODEGEN_FUNCPTR *_ptrc_glEndTransformFeedback)(void); +#define glEndTransformFeedback _ptrc_glEndTransformFeedback +extern void (CODEGEN_FUNCPTR *_ptrc_glFlushMappedBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length); +#define glFlushMappedBufferRange _ptrc_glFlushMappedBufferRange +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferRenderbuffer)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +#define glFramebufferRenderbuffer _ptrc_glFramebufferRenderbuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture1D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +#define glFramebufferTexture1D _ptrc_glFramebufferTexture1D +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture2D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +#define glFramebufferTexture2D _ptrc_glFramebufferTexture2D +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture3D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +#define glFramebufferTexture3D _ptrc_glFramebufferTexture3D +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#define glFramebufferTextureLayer _ptrc_glFramebufferTextureLayer +extern void (CODEGEN_FUNCPTR *_ptrc_glGenFramebuffers)(GLsizei n, GLuint * framebuffers); +#define glGenFramebuffers _ptrc_glGenFramebuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glGenRenderbuffers)(GLsizei n, GLuint * renderbuffers); +#define glGenRenderbuffers _ptrc_glGenRenderbuffers +extern void (CODEGEN_FUNCPTR *_ptrc_glGenVertexArrays)(GLsizei n, GLuint * arrays); +#define glGenVertexArrays _ptrc_glGenVertexArrays +extern void (CODEGEN_FUNCPTR *_ptrc_glGenerateMipmap)(GLenum target); +#define glGenerateMipmap _ptrc_glGenerateMipmap +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBooleani_v)(GLenum target, GLuint index, GLboolean * data); +#define glGetBooleani_v _ptrc_glGetBooleani_v +extern GLint (CODEGEN_FUNCPTR *_ptrc_glGetFragDataLocation)(GLuint program, const GLchar * name); +#define glGetFragDataLocation _ptrc_glGetFragDataLocation +extern void (CODEGEN_FUNCPTR *_ptrc_glGetFramebufferAttachmentParameteriv)(GLenum target, GLenum attachment, GLenum pname, GLint * params); +#define glGetFramebufferAttachmentParameteriv _ptrc_glGetFramebufferAttachmentParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetIntegeri_v)(GLenum target, GLuint index, GLint * data); +#define glGetIntegeri_v _ptrc_glGetIntegeri_v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetRenderbufferParameteriv)(GLenum target, GLenum pname, GLint * params); +#define glGetRenderbufferParameteriv _ptrc_glGetRenderbufferParameteriv +extern const GLubyte * (CODEGEN_FUNCPTR *_ptrc_glGetStringi)(GLenum name, GLuint index); +#define glGetStringi _ptrc_glGetStringi +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterIiv)(GLenum target, GLenum pname, GLint * params); +#define glGetTexParameterIiv _ptrc_glGetTexParameterIiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTexParameterIuiv)(GLenum target, GLenum pname, GLuint * params); +#define glGetTexParameterIuiv _ptrc_glGetTexParameterIuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetTransformFeedbackVarying)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLsizei * size, GLenum * type, GLchar * name); +#define glGetTransformFeedbackVarying _ptrc_glGetTransformFeedbackVarying +extern void (CODEGEN_FUNCPTR *_ptrc_glGetUniformuiv)(GLuint program, GLint location, GLuint * params); +#define glGetUniformuiv _ptrc_glGetUniformuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribIiv)(GLuint index, GLenum pname, GLint * params); +#define glGetVertexAttribIiv _ptrc_glGetVertexAttribIiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetVertexAttribIuiv)(GLuint index, GLenum pname, GLuint * params); +#define glGetVertexAttribIuiv _ptrc_glGetVertexAttribIuiv +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsEnabledi)(GLenum target, GLuint index); +#define glIsEnabledi _ptrc_glIsEnabledi +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsFramebuffer)(GLuint framebuffer); +#define glIsFramebuffer _ptrc_glIsFramebuffer +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsRenderbuffer)(GLuint renderbuffer); +#define glIsRenderbuffer _ptrc_glIsRenderbuffer +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsVertexArray)(GLuint ren_array); +#define glIsVertexArray _ptrc_glIsVertexArray +extern void * (CODEGEN_FUNCPTR *_ptrc_glMapBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +#define glMapBufferRange _ptrc_glMapBufferRange +extern void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorage)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +#define glRenderbufferStorage _ptrc_glRenderbufferStorage +extern void (CODEGEN_FUNCPTR *_ptrc_glRenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#define glRenderbufferStorageMultisample _ptrc_glRenderbufferStorageMultisample +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameterIiv)(GLenum target, GLenum pname, const GLint * params); +#define glTexParameterIiv _ptrc_glTexParameterIiv +extern void (CODEGEN_FUNCPTR *_ptrc_glTexParameterIuiv)(GLenum target, GLenum pname, const GLuint * params); +#define glTexParameterIuiv _ptrc_glTexParameterIuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glTransformFeedbackVaryings)(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode); +#define glTransformFeedbackVaryings _ptrc_glTransformFeedbackVaryings +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1ui)(GLint location, GLuint v0); +#define glUniform1ui _ptrc_glUniform1ui +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform1uiv)(GLint location, GLsizei count, const GLuint * value); +#define glUniform1uiv _ptrc_glUniform1uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2ui)(GLint location, GLuint v0, GLuint v1); +#define glUniform2ui _ptrc_glUniform2ui +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform2uiv)(GLint location, GLsizei count, const GLuint * value); +#define glUniform2uiv _ptrc_glUniform2uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3ui)(GLint location, GLuint v0, GLuint v1, GLuint v2); +#define glUniform3ui _ptrc_glUniform3ui +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform3uiv)(GLint location, GLsizei count, const GLuint * value); +#define glUniform3uiv _ptrc_glUniform3uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4ui)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +#define glUniform4ui _ptrc_glUniform4ui +extern void (CODEGEN_FUNCPTR *_ptrc_glUniform4uiv)(GLint location, GLsizei count, const GLuint * value); +#define glUniform4uiv _ptrc_glUniform4uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1i)(GLuint index, GLint x); +#define glVertexAttribI1i _ptrc_glVertexAttribI1i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1iv)(GLuint index, const GLint * v); +#define glVertexAttribI1iv _ptrc_glVertexAttribI1iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1ui)(GLuint index, GLuint x); +#define glVertexAttribI1ui _ptrc_glVertexAttribI1ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI1uiv)(GLuint index, const GLuint * v); +#define glVertexAttribI1uiv _ptrc_glVertexAttribI1uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2i)(GLuint index, GLint x, GLint y); +#define glVertexAttribI2i _ptrc_glVertexAttribI2i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2iv)(GLuint index, const GLint * v); +#define glVertexAttribI2iv _ptrc_glVertexAttribI2iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2ui)(GLuint index, GLuint x, GLuint y); +#define glVertexAttribI2ui _ptrc_glVertexAttribI2ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI2uiv)(GLuint index, const GLuint * v); +#define glVertexAttribI2uiv _ptrc_glVertexAttribI2uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3i)(GLuint index, GLint x, GLint y, GLint z); +#define glVertexAttribI3i _ptrc_glVertexAttribI3i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3iv)(GLuint index, const GLint * v); +#define glVertexAttribI3iv _ptrc_glVertexAttribI3iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3ui)(GLuint index, GLuint x, GLuint y, GLuint z); +#define glVertexAttribI3ui _ptrc_glVertexAttribI3ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI3uiv)(GLuint index, const GLuint * v); +#define glVertexAttribI3uiv _ptrc_glVertexAttribI3uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4bv)(GLuint index, const GLbyte * v); +#define glVertexAttribI4bv _ptrc_glVertexAttribI4bv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4i)(GLuint index, GLint x, GLint y, GLint z, GLint w); +#define glVertexAttribI4i _ptrc_glVertexAttribI4i +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4iv)(GLuint index, const GLint * v); +#define glVertexAttribI4iv _ptrc_glVertexAttribI4iv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4sv)(GLuint index, const GLshort * v); +#define glVertexAttribI4sv _ptrc_glVertexAttribI4sv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4ubv)(GLuint index, const GLubyte * v); +#define glVertexAttribI4ubv _ptrc_glVertexAttribI4ubv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4ui)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +#define glVertexAttribI4ui _ptrc_glVertexAttribI4ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4uiv)(GLuint index, const GLuint * v); +#define glVertexAttribI4uiv _ptrc_glVertexAttribI4uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribI4usv)(GLuint index, const GLushort * v); +#define glVertexAttribI4usv _ptrc_glVertexAttribI4usv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribIPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer); +#define glVertexAttribIPointer _ptrc_glVertexAttribIPointer + +extern void (CODEGEN_FUNCPTR *_ptrc_glCopyBufferSubData)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +#define glCopyBufferSubData _ptrc_glCopyBufferSubData +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +#define glDrawArraysInstanced _ptrc_glDrawArraysInstanced +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount); +#define glDrawElementsInstanced _ptrc_glDrawElementsInstanced +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformBlockName); +#define glGetActiveUniformBlockName _ptrc_glGetActiveUniformBlockName +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint * params); +#define glGetActiveUniformBlockiv _ptrc_glGetActiveUniformBlockiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformName)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformName); +#define glGetActiveUniformName _ptrc_glGetActiveUniformName +extern void (CODEGEN_FUNCPTR *_ptrc_glGetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint * params); +#define glGetActiveUniformsiv _ptrc_glGetActiveUniformsiv +extern GLuint (CODEGEN_FUNCPTR *_ptrc_glGetUniformBlockIndex)(GLuint program, const GLchar * uniformBlockName); +#define glGetUniformBlockIndex _ptrc_glGetUniformBlockIndex +extern void (CODEGEN_FUNCPTR *_ptrc_glGetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint * uniformIndices); +#define glGetUniformIndices _ptrc_glGetUniformIndices +extern void (CODEGEN_FUNCPTR *_ptrc_glPrimitiveRestartIndex)(GLuint index); +#define glPrimitiveRestartIndex _ptrc_glPrimitiveRestartIndex +extern void (CODEGEN_FUNCPTR *_ptrc_glTexBuffer)(GLenum target, GLenum internalformat, GLuint buffer); +#define glTexBuffer _ptrc_glTexBuffer +extern void (CODEGEN_FUNCPTR *_ptrc_glUniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#define glUniformBlockBinding _ptrc_glUniformBlockBinding + +extern GLenum (CODEGEN_FUNCPTR *_ptrc_glClientWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout); +#define glClientWaitSync _ptrc_glClientWaitSync +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteSync)(GLsync sync); +#define glDeleteSync _ptrc_glDeleteSync +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex); +#define glDrawElementsBaseVertex _ptrc_glDrawElementsBaseVertex +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawElementsInstancedBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex); +#define glDrawElementsInstancedBaseVertex _ptrc_glDrawElementsInstancedBaseVertex +extern void (CODEGEN_FUNCPTR *_ptrc_glDrawRangeElementsBaseVertex)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex); +#define glDrawRangeElementsBaseVertex _ptrc_glDrawRangeElementsBaseVertex +extern GLsync (CODEGEN_FUNCPTR *_ptrc_glFenceSync)(GLenum condition, GLbitfield flags); +#define glFenceSync _ptrc_glFenceSync +extern void (CODEGEN_FUNCPTR *_ptrc_glFramebufferTexture)(GLenum target, GLenum attachment, GLuint texture, GLint level); +#define glFramebufferTexture _ptrc_glFramebufferTexture +extern void (CODEGEN_FUNCPTR *_ptrc_glGetBufferParameteri64v)(GLenum target, GLenum pname, GLint64 * params); +#define glGetBufferParameteri64v _ptrc_glGetBufferParameteri64v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetInteger64i_v)(GLenum target, GLuint index, GLint64 * data); +#define glGetInteger64i_v _ptrc_glGetInteger64i_v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetInteger64v)(GLenum pname, GLint64 * data); +#define glGetInteger64v _ptrc_glGetInteger64v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetMultisamplefv)(GLenum pname, GLuint index, GLfloat * val); +#define glGetMultisamplefv _ptrc_glGetMultisamplefv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetSynciv)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei * length, GLint * values); +#define glGetSynciv _ptrc_glGetSynciv +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsSync)(GLsync sync); +#define glIsSync _ptrc_glIsSync +extern void (CODEGEN_FUNCPTR *_ptrc_glMultiDrawElementsBaseVertex)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount, const GLint * basevertex); +#define glMultiDrawElementsBaseVertex _ptrc_glMultiDrawElementsBaseVertex +extern void (CODEGEN_FUNCPTR *_ptrc_glProvokingVertex)(GLenum mode); +#define glProvokingVertex _ptrc_glProvokingVertex +extern void (CODEGEN_FUNCPTR *_ptrc_glSampleMaski)(GLuint maskNumber, GLbitfield mask); +#define glSampleMaski _ptrc_glSampleMaski +extern void (CODEGEN_FUNCPTR *_ptrc_glTexImage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +#define glTexImage2DMultisample _ptrc_glTexImage2DMultisample +extern void (CODEGEN_FUNCPTR *_ptrc_glTexImage3DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +#define glTexImage3DMultisample _ptrc_glTexImage3DMultisample +extern void (CODEGEN_FUNCPTR *_ptrc_glWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout); +#define glWaitSync _ptrc_glWaitSync + +extern void (CODEGEN_FUNCPTR *_ptrc_glBindFragDataLocationIndexed)(GLuint program, GLuint colorNumber, GLuint index, const GLchar * name); +#define glBindFragDataLocationIndexed _ptrc_glBindFragDataLocationIndexed +extern void (CODEGEN_FUNCPTR *_ptrc_glBindSampler)(GLuint unit, GLuint sampler); +#define glBindSampler _ptrc_glBindSampler +extern void (CODEGEN_FUNCPTR *_ptrc_glDeleteSamplers)(GLsizei count, const GLuint * samplers); +#define glDeleteSamplers _ptrc_glDeleteSamplers +extern void (CODEGEN_FUNCPTR *_ptrc_glGenSamplers)(GLsizei count, GLuint * samplers); +#define glGenSamplers _ptrc_glGenSamplers +extern GLint (CODEGEN_FUNCPTR *_ptrc_glGetFragDataIndex)(GLuint program, const GLchar * name); +#define glGetFragDataIndex _ptrc_glGetFragDataIndex +extern void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjecti64v)(GLuint id, GLenum pname, GLint64 * params); +#define glGetQueryObjecti64v _ptrc_glGetQueryObjecti64v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetQueryObjectui64v)(GLuint id, GLenum pname, GLuint64 * params); +#define glGetQueryObjectui64v _ptrc_glGetQueryObjectui64v +extern void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterIiv)(GLuint sampler, GLenum pname, GLint * params); +#define glGetSamplerParameterIiv _ptrc_glGetSamplerParameterIiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterIuiv)(GLuint sampler, GLenum pname, GLuint * params); +#define glGetSamplerParameterIuiv _ptrc_glGetSamplerParameterIuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameterfv)(GLuint sampler, GLenum pname, GLfloat * params); +#define glGetSamplerParameterfv _ptrc_glGetSamplerParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glGetSamplerParameteriv)(GLuint sampler, GLenum pname, GLint * params); +#define glGetSamplerParameteriv _ptrc_glGetSamplerParameteriv +extern GLboolean (CODEGEN_FUNCPTR *_ptrc_glIsSampler)(GLuint sampler); +#define glIsSampler _ptrc_glIsSampler +extern void (CODEGEN_FUNCPTR *_ptrc_glQueryCounter)(GLuint id, GLenum target); +#define glQueryCounter _ptrc_glQueryCounter +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterIiv)(GLuint sampler, GLenum pname, const GLint * param); +#define glSamplerParameterIiv _ptrc_glSamplerParameterIiv +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterIuiv)(GLuint sampler, GLenum pname, const GLuint * param); +#define glSamplerParameterIuiv _ptrc_glSamplerParameterIuiv +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterf)(GLuint sampler, GLenum pname, GLfloat param); +#define glSamplerParameterf _ptrc_glSamplerParameterf +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameterfv)(GLuint sampler, GLenum pname, const GLfloat * param); +#define glSamplerParameterfv _ptrc_glSamplerParameterfv +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameteri)(GLuint sampler, GLenum pname, GLint param); +#define glSamplerParameteri _ptrc_glSamplerParameteri +extern void (CODEGEN_FUNCPTR *_ptrc_glSamplerParameteriv)(GLuint sampler, GLenum pname, const GLint * param); +#define glSamplerParameteriv _ptrc_glSamplerParameteriv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribDivisor)(GLuint index, GLuint divisor); +#define glVertexAttribDivisor _ptrc_glVertexAttribDivisor +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP1ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +#define glVertexAttribP1ui _ptrc_glVertexAttribP1ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP1uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +#define glVertexAttribP1uiv _ptrc_glVertexAttribP1uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP2ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +#define glVertexAttribP2ui _ptrc_glVertexAttribP2ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP2uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +#define glVertexAttribP2uiv _ptrc_glVertexAttribP2uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP3ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +#define glVertexAttribP3ui _ptrc_glVertexAttribP3ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP3uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +#define glVertexAttribP3uiv _ptrc_glVertexAttribP3uiv +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP4ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +#define glVertexAttribP4ui _ptrc_glVertexAttribP4ui +extern void (CODEGEN_FUNCPTR *_ptrc_glVertexAttribP4uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +#define glVertexAttribP4uiv _ptrc_glVertexAttribP4uiv + +enum ogl_LoadStatus +{ + ogl_LOAD_FAILED = 0, + ogl_LOAD_SUCCEEDED = 1, +}; + +int ogl_LoadFunctions(); + +int ogl_GetMinorVersion(void); +int ogl_GetMajorVersion(void); +int ogl_IsVersionGEQ(int majorVersion, int minorVersion); + +#ifdef __cplusplus +} +#endif /*__cplusplus*/ + +#endif /*POINTER_C_GENERATED_HEADER_OPENGL_H*/ diff --git a/src/gl/system/gl_menu.cpp b/src/gl/system/gl_menu.cpp new file mode 100644 index 000000000..11534436b --- /dev/null +++ b/src/gl/system/gl_menu.cpp @@ -0,0 +1,95 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2005-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + + +#include "gl/system/gl_system.h" +#include "c_cvars.h" +#include "c_dispatch.h" +#include "v_video.h" +#include "version.h" +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/renderer/gl_renderer.h" +#include "menu/menu.h" + + + +// OpenGL stuff moved here +// GL related CVARs +CVAR(Bool, gl_portals, true, 0) +CVAR(Bool, gl_noquery, false, 0) +CVAR(Bool,gl_mirrors,true,0) // This is for debugging only! +CVAR(Bool,gl_mirror_envmap, true, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) +CVAR(Bool, gl_seamless, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) + +CUSTOM_CVAR(Int, r_mirror_recursions,4,CVAR_GLOBALCONFIG|CVAR_ARCHIVE) +{ + if (self<0) self=0; + if (self>10) self=10; +} +bool gl_plane_reflection_i; // This is needed in a header that cannot include the CVAR stuff... +CUSTOM_CVAR(Bool, gl_plane_reflection, true, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) +{ + gl_plane_reflection_i = self; +} + +CUSTOM_CVAR(Bool, gl_render_precise, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +{ + gl_seamless=self; +} + +CUSTOM_CVAR (Float, vid_brightness, 0.f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +{ + if (screen != NULL) + { + screen->SetGamma(Gamma); //Brightness (self); + } +} + +CUSTOM_CVAR (Float, vid_contrast, 1.f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) +{ + if (screen != NULL) + { + screen->SetGamma(Gamma); //SetContrast (self); + } +} + + +// Do some tinkering with the menus so that certain options only appear +// when they are actually valid. +void gl_SetupMenu() +{ +#ifndef HAVE_MMX + FOptionValues **opt = OptionValues.CheckKey("HqResizeModes"); + if (opt != NULL) + { + for(int i = (*opt)->mValues.Size()-1; i>=0; i--) + { + // Delete HQnX resize modes for non MSVC targets + if ((*opt)->mValues[i].Value >= 7.0) + { + (*opt)->mValues.Delete(i); + } + } + } +#endif +} diff --git a/src/gl/system/gl_swframebuffer.cpp b/src/gl/system/gl_swframebuffer.cpp new file mode 100644 index 000000000..5f142d30c --- /dev/null +++ b/src/gl/system/gl_swframebuffer.cpp @@ -0,0 +1,3675 @@ +/* +** gl_swframebuffer.cpp +** Code to let ZDoom use OpenGL as a simple framebuffer +** +**--------------------------------------------------------------------------- +** Copyright 1998-2011 Randy Heit +** 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 author 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. +**--------------------------------------------------------------------------- +** +** This file does _not_ implement hardware-acclerated 3D rendering. It is +** just a means of getting the pixel data to the screen in a more reliable +** method on modern hardware by copying the entire frame to a texture, +** drawing that to the screen, and presenting. +** +** That said, it does implement hardware-accelerated 2D rendering. +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "doomstat.h" +#include "m_png.h" +#include "m_crc32.h" +#include "vectors.h" +#include "v_palette.h" +#include "templates.h" + +#include "c_dispatch.h" +#include "templates.h" +#include "i_system.h" +#include "i_video.h" +#include "i_input.h" +#include "v_pfx.h" +#include "stats.h" +#include "doomerrors.h" +#include "r_main.h" +#include "r_data/r_translate.h" +#include "f_wipe.h" +#include "sbar.h" +#include "w_wad.h" +#include "r_data/colormaps.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_swframebuffer.h" +#include "gl/data/gl_data.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/gl_functions.h" +#include "gl_debug.h" + +CVAR(Int, gl_showpacks, 0, 0) +#ifndef WIN32 // Defined in fb_d3d9 for Windows +CVAR(Bool, vid_hwaalines, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CUSTOM_CVAR(Bool, vid_hw2d, true, CVAR_NOINITCALL) +{ + V_SetBorderNeedRefresh(); + ST_SetNeedRefresh(); +} +#else +EXTERN_CVAR(Bool, vid_hwaalines) +EXTERN_CVAR(Bool, vid_hw2d) +#endif + +EXTERN_CVAR(Bool, fullscreen) +EXTERN_CVAR(Float, Gamma) +EXTERN_CVAR(Bool, vid_vsync) +EXTERN_CVAR(Float, transsouls) +EXTERN_CVAR(Int, vid_refreshrate) + +CVAR(Int, vid_max_width, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +CVAR(Int, vid_max_height, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) + +namespace +{ + int ClampWidth(int width) { return (vid_max_width == 0 || width < vid_max_width) ? width : vid_max_width; } + int ClampHeight(int height) { return (vid_max_height == 0 || height < vid_max_height) ? height : vid_max_height; } +} + +#ifdef WIN32 +extern cycle_t BlitCycles; +#endif + +void gl_LoadExtensions(); +void gl_PrintStartupLog(); + +#ifndef WIN32 +// This has to be in this file because system headers conflict Doom headers +DFrameBuffer *CreateGLSWFrameBuffer(int width, int height, bool bgra, bool fullscreen) +{ + return new OpenGLSWFrameBuffer(NULL, width, height, 32, 60, fullscreen, bgra); +} +#endif + +IMPLEMENT_CLASS(OpenGLSWFrameBuffer, false, false) + +const char *const OpenGLSWFrameBuffer::ShaderDefines[OpenGLSWFrameBuffer::NUM_SHADERS] = +{ + "#define ENORMALCOLOR", // NormalColor + "#define ENORMALCOLOR\n#define PALTEX", // NormalColorPal + "#define ENORMALCOLOR\n#define INVERT", // NormalColorInv + "#define ENORMALCOLOR\n#define PALTEX\n#define INVERT", // NormalColorPalInv + + "#define EREDTOALPHA", // RedToAlpha + "#define EREDTOALPHA\n#define INVERT", // RedToAlphaInv + + "#define EVERTEXCOLOR", // VertexColor + + "#define ESPECIALCOLORMAP\n", // SpecialColormap + "#define ESPECIALCOLORMAP\n#define PALTEX", // SpecialColorMapPal + + "#define EINGAMECOLORMAP", // InGameColormap + "#define EINGAMECOLORMAP\n#define DESAT", // InGameColormapDesat + "#define EINGAMECOLORMAP\n#define INVERT", // InGameColormapInv + "#define EINGAMECOLORMAP\n#define INVERT\n#define DESAT", // InGameColormapInvDesat + "#define EINGAMECOLORMAP\n#define PALTEX\n", // InGameColormapPal + "#define EINGAMECOLORMAP\n#define PALTEX\n#define DESAT", // InGameColormapPalDesat + "#define EINGAMECOLORMAP\n#define PALTEX\n#define INVERT", // InGameColormapPalInv + "#define EINGAMECOLORMAP\n#define PALTEX\n#define INVERT\n#define DESAT", // InGameColormapPalInvDesat + + "#define EBURNWIPE", // BurnWipe + "#define EGAMMACORRECTION", // GammaCorrection +}; + +OpenGLSWFrameBuffer::OpenGLSWFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen, bool bgra) : + Super(hMonitor, ClampWidth(width), ClampHeight(height), bits, refreshHz, fullscreen, bgra) +{ + // To do: this needs to cooperate with the same static in OpenGLFrameBuffer::InitializeState + static bool first = true; + if (first) + { + ogl_LoadFunctions(); + } + gl_LoadExtensions(); + InitializeState(); + if (first) + { + gl_PrintStartupLog(); + first = false; + } + + // SetVSync needs to be at the very top to workaround a bug in Nvidia's OpenGL driver. + // If wglSwapIntervalEXT is called after glBindFramebuffer in a frame the setting is not changed! + Super::SetVSync(vid_vsync); + + Debug = std::make_shared(); + Debug->Update(); + + VertexBuffer = nullptr; + IndexBuffer = nullptr; + FBTexture = nullptr; + InitialWipeScreen = nullptr; + ScreenshotTexture = nullptr; + FinalWipeScreen = nullptr; + PaletteTexture = nullptr; + for (int i = 0; i < NUM_SHADERS; ++i) + { + Shaders[i] = nullptr; + } + VSync = vid_vsync; + BlendingRect.left = 0; + BlendingRect.top = 0; + BlendingRect.right = Width; + BlendingRect.bottom = Height; + In2D = 0; + Palettes = nullptr; + Textures = nullptr; + Accel2D = true; + GatheringWipeScreen = false; + ScreenWipe = nullptr; + InScene = false; + QuadExtra = new BufferedTris[MAX_QUAD_BATCH]; + memset(QuadExtra, 0, sizeof(BufferedTris) * MAX_QUAD_BATCH); + Atlases = nullptr; + PixelDoubling = 0; + + Gamma = 1.0; + FlashColor0 = 0; + FlashColor1 = 0xFFFFFFFF; + FlashColor = 0; + FlashAmount = 0; + + NeedGammaUpdate = false; + NeedPalUpdate = false; + + if (MemBuffer == nullptr) + { + return; + } + + memcpy(SourcePalette, GPalette.BaseColors, sizeof(PalEntry) * 256); + + //Windowed = !(static_cast(Video)->GoFullscreen(fullscreen)); + + TrueHeight = height; + + CreateResources(); + SetInitialState(); +} + +OpenGLSWFrameBuffer::~OpenGLSWFrameBuffer() +{ + ReleaseResources(); + delete[] QuadExtra; +} + +void *OpenGLSWFrameBuffer::MapBuffer(int target, int size) +{ + if (glMapBufferRange) + { + return (FBVERTEX*)glMapBufferRange(target, 0, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + } + else + { + glBufferData(target, size, nullptr, GL_STREAM_DRAW); + return glMapBuffer(target, GL_WRITE_ONLY); + } +} + +OpenGLSWFrameBuffer::HWFrameBuffer::~HWFrameBuffer() +{ + if (Framebuffer != 0) glDeleteFramebuffers(1, (GLuint*)&Framebuffer); + delete Texture; +} + +OpenGLSWFrameBuffer::HWTexture::~HWTexture() +{ + if (Texture != 0) glDeleteTextures(1, (GLuint*)&Texture); + if (Buffers[0] != 0) glDeleteBuffers(2, (GLuint*)Buffers); +} + +OpenGLSWFrameBuffer::HWVertexBuffer::~HWVertexBuffer() +{ + if (VertexArray != 0) glDeleteVertexArrays(1, (GLuint*)&VertexArray); + if (Buffer != 0) glDeleteBuffers(1, (GLuint*)&Buffer); +} + +OpenGLSWFrameBuffer::FBVERTEX *OpenGLSWFrameBuffer::HWVertexBuffer::Lock() +{ + glBindBuffer(GL_ARRAY_BUFFER, Buffer); + return (FBVERTEX*)MapBuffer(GL_ARRAY_BUFFER, Size); +} + +void OpenGLSWFrameBuffer::HWVertexBuffer::Unlock() +{ + glUnmapBuffer(GL_ARRAY_BUFFER); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +OpenGLSWFrameBuffer::HWIndexBuffer::~HWIndexBuffer() +{ + if (Buffer != 0) glDeleteBuffers(1, (GLuint*)&Buffer); +} + +uint16_t *OpenGLSWFrameBuffer::HWIndexBuffer::Lock() +{ + glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &LockedOldBinding); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffer); + return (uint16_t*)MapBuffer(GL_ELEMENT_ARRAY_BUFFER, Size); +} + +void OpenGLSWFrameBuffer::HWIndexBuffer::Unlock() +{ + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, LockedOldBinding); +} + +OpenGLSWFrameBuffer::HWPixelShader::~HWPixelShader() +{ + if (Program != 0) glDeleteProgram(Program); + if (VertexShader != 0) glDeleteShader(VertexShader); + if (FragmentShader != 0) glDeleteShader(FragmentShader); +} + +bool OpenGLSWFrameBuffer::CreateFrameBuffer(const FString &name, int width, int height, HWFrameBuffer **outFramebuffer) +{ + auto fb = std::make_unique(); + + if (!CreateTexture(name, width, height, 1, GL_RGBA16F, &fb->Texture)) + { + outFramebuffer = nullptr; + return false; + } + + glGenFramebuffers(1, (GLuint*)&fb->Framebuffer); + + GLint oldFramebufferBinding = 0, oldTextureBinding = 0; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFramebufferBinding); + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTextureBinding); + + glBindFramebuffer(GL_FRAMEBUFFER, fb->Framebuffer); + FGLDebug::LabelObject(GL_FRAMEBUFFER, fb->Framebuffer, name); + + glBindTexture(GL_TEXTURE_2D, fb->Texture->Texture); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->Texture->Texture, 0); + + GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + glBindFramebuffer(GL_FRAMEBUFFER, oldFramebufferBinding); + glBindTexture(GL_TEXTURE_2D, oldTextureBinding); + + if (result != GL_FRAMEBUFFER_COMPLETE) + { + //Printf("Framebuffer is not complete"); + outFramebuffer = nullptr; + return false; + } + + *outFramebuffer = fb.release(); + return true; +} + +bool OpenGLSWFrameBuffer::CreatePixelShader(FString vertexsrc, FString fragmentsrc, const FString &defines, HWPixelShader **outShader) +{ + auto shader = std::make_unique(); + + shader->Program = glCreateProgram(); + shader->VertexShader = glCreateShader(GL_VERTEX_SHADER); + shader->FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + + int maxGlslVersion = 330; + int shaderVersion = MIN((int)round(gl.glslversion * 10) * 10, maxGlslVersion); + + FString prefix; + prefix.AppendFormat("#version %d\n%s\n#line 0\n", shaderVersion, defines.GetChars()); + + vertexsrc = prefix + vertexsrc; + fragmentsrc = prefix + fragmentsrc; + + { + int lengths[1] = { (int)vertexsrc.Len() }; + const char *sources[1] = { vertexsrc.GetChars() }; + glShaderSource(shader->VertexShader, 1, sources, lengths); + glCompileShader(shader->VertexShader); + } + + { + int lengths[1] = { (int)fragmentsrc.Len() }; + const char *sources[1] = { fragmentsrc.GetChars() }; + glShaderSource(shader->FragmentShader, 1, sources, lengths); + glCompileShader(shader->FragmentShader); + } + + GLint status = 0; + int errorShader = shader->VertexShader; + glGetShaderiv(shader->VertexShader, GL_COMPILE_STATUS, &status); + if (status != GL_FALSE) { errorShader = shader->FragmentShader; glGetShaderiv(shader->FragmentShader, GL_COMPILE_STATUS, &status); } + if (status == GL_FALSE) + { + static char buffer[10000]; + GLsizei length = 0; + buffer[0] = 0; + glGetShaderInfoLog(errorShader, 10000, &length, buffer); + //Printf("Shader compile failed: %s", buffer); + + *outShader = nullptr; + return false; + } + + glAttachShader(shader->Program, shader->VertexShader); + glAttachShader(shader->Program, shader->FragmentShader); + glBindFragDataLocation(shader->Program, 0, "FragColor"); + glBindAttribLocation(shader->Program, 0, "AttrPosition"); + glBindAttribLocation(shader->Program, 1, "AttrColor0"); + glBindAttribLocation(shader->Program, 2, "AttrColor1"); + glBindAttribLocation(shader->Program, 3, "AttrTexCoord0"); + glLinkProgram(shader->Program); + glGetProgramiv(shader->Program, GL_LINK_STATUS, &status); + if (status == GL_FALSE) + { + static char buffer[10000]; + GLsizei length = 0; + buffer[0] = 0; + glGetProgramInfoLog(shader->Program, 10000, &length, buffer); + //Printf("Shader compile failed: %s", buffer); + + *outShader = nullptr; + return false; + } + + shader->ConstantLocations[PSCONST_Desaturation] = glGetUniformLocation(shader->Program, "Desaturation"); + shader->ConstantLocations[PSCONST_PaletteMod] = glGetUniformLocation(shader->Program, "PaletteMod"); + shader->ConstantLocations[PSCONST_Weights] = glGetUniformLocation(shader->Program, "Weights"); + shader->ConstantLocations[PSCONST_Gamma] = glGetUniformLocation(shader->Program, "Gamma"); + shader->ConstantLocations[PSCONST_ScreenSize] = glGetUniformLocation(shader->Program, "ScreenSize"); + shader->ImageLocation = glGetUniformLocation(shader->Program, "Image"); + shader->PaletteLocation = glGetUniformLocation(shader->Program, "Palette"); + shader->NewScreenLocation = glGetUniformLocation(shader->Program, "NewScreen"); + shader->BurnLocation = glGetUniformLocation(shader->Program, "Burn"); + + *outShader = shader.release(); + return true; +} + +bool OpenGLSWFrameBuffer::CreateVertexBuffer(int size, HWVertexBuffer **outVertexBuffer) +{ + auto obj = std::make_unique(); + + obj->Size = size; + + GLint oldBinding = 0; + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &oldBinding); + + glGenVertexArrays(1, (GLuint*)&obj->VertexArray); + glGenBuffers(1, (GLuint*)&obj->Buffer); + glBindVertexArray(obj->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, obj->Buffer); + FGLDebug::LabelObject(GL_BUFFER, obj->Buffer, "VertexBuffer"); + glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_STREAM_DRAW); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glEnableVertexAttribArray(2); + glEnableVertexAttribArray(3); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, x)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color0)); + glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color1)); + glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, tu)); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(oldBinding); + + *outVertexBuffer = obj.release(); + return true; +} + +bool OpenGLSWFrameBuffer::CreateIndexBuffer(int size, HWIndexBuffer **outIndexBuffer) +{ + auto obj = std::make_unique(); + + obj->Size = size; + + GLint oldBinding = 0; + glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &oldBinding); + + glGenBuffers(1, (GLuint*)&obj->Buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, obj->Buffer); + FGLDebug::LabelObject(GL_BUFFER, obj->Buffer, "IndexBuffer"); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_STREAM_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oldBinding); + + *outIndexBuffer = obj.release(); + return true; +} + +bool OpenGLSWFrameBuffer::CreateTexture(const FString &name, int width, int height, int levels, int format, HWTexture **outTexture) +{ + auto obj = std::make_unique(); + + obj->Format = format; + + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + + glGenTextures(1, (GLuint*)&obj->Texture); + glBindTexture(GL_TEXTURE_2D, obj->Texture); + GLenum srcformat; + switch (format) + { + case GL_R8: srcformat = GL_RED; break; + case GL_RGBA8: srcformat = GL_BGRA; break; + case GL_RGBA16F: srcformat = GL_RGBA; break; + case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: srcformat = GL_RGB; break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: srcformat = GL_RGBA; break; + case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: srcformat = GL_RGBA; break; + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: srcformat = GL_RGBA; break; + default: + I_FatalError("Unknown format passed to CreateTexture"); + return false; + } + glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, srcformat, GL_UNSIGNED_BYTE, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + FGLDebug::LabelObject(GL_TEXTURE, obj->Texture, name); + + glBindTexture(GL_TEXTURE_2D, oldBinding); + + *outTexture = obj.release(); + return true; +} + +OpenGLSWFrameBuffer::HWTexture *OpenGLSWFrameBuffer::CopyCurrentScreen() +{ + auto obj = std::make_unique(); + obj->Format = GL_RGBA16F; + + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + + glGenTextures(1, (GLuint*)&obj->Texture); + glBindTexture(GL_TEXTURE_2D, obj->Texture); + + glCopyTexImage2D(GL_TEXTURE_2D, 0, obj->Format, 0, 0, Width, Height, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + FGLDebug::LabelObject(GL_TEXTURE, obj->Texture, "CopyCurrentScreen"); + + glBindTexture(GL_TEXTURE_2D, oldBinding); + + return obj.release(); +} + +void OpenGLSWFrameBuffer::SetGammaRamp(const GammaRamp *ramp) +{ +} + +void OpenGLSWFrameBuffer::SetPixelShaderConstantF(int uniformIndex, const float *data, int vec4fcount) +{ + assert(uniformIndex < NumPSCONST && vec4fcount == 1); // This emulation of d3d9 only works for very simple stuff + for (int i = 0; i < 4; i++) + ShaderConstants[uniformIndex * 4 + i] = data[i]; + if (CurrentShader && CurrentShader->ConstantLocations[uniformIndex] != -1) + glUniform4fv(CurrentShader->ConstantLocations[uniformIndex], vec4fcount, data); +} + +void OpenGLSWFrameBuffer::SetHWPixelShader(HWPixelShader *shader) +{ + if (shader != CurrentShader) + { + if (shader) + { + glUseProgram(shader->Program); + for (int i = 0; i < NumPSCONST; i++) + { + if (shader->ConstantLocations[i] != -1) + glUniform4fv(shader->ConstantLocations[i], 1, &ShaderConstants[i * 4]); + } + } + else + { + glUseProgram(0); + } + } + CurrentShader = shader; +} + +void OpenGLSWFrameBuffer::SetStreamSource(HWVertexBuffer *vertexBuffer) +{ + if (vertexBuffer) + glBindVertexArray(vertexBuffer->VertexArray); + else + glBindVertexArray(0); +} + +void OpenGLSWFrameBuffer::SetIndices(HWIndexBuffer *indexBuffer) +{ + if (indexBuffer) + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->Buffer); + else + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} + +void OpenGLSWFrameBuffer::DrawTriangleFans(int count, const FBVERTEX *vertices) +{ + count = 2 + count; + + GLint oldBinding = 0; + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &oldBinding); + + if (!StreamVertexBuffer) + { + StreamVertexBuffer = std::make_unique(); + glGenVertexArrays(1, (GLuint*)&StreamVertexBuffer->VertexArray); + glGenBuffers(1, (GLuint*)&StreamVertexBuffer->Buffer); + glBindVertexArray(StreamVertexBuffer->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBuffer->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(FBVERTEX), vertices, GL_STREAM_DRAW); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glEnableVertexAttribArray(2); + glEnableVertexAttribArray(3); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, x)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color0)); + glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color1)); + glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, tu)); + } + else + { + glBindVertexArray(StreamVertexBuffer->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBuffer->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(FBVERTEX), vertices, GL_STREAM_DRAW); + } + + glDrawArrays(GL_TRIANGLE_FAN, 0, count); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(oldBinding); +} + +void OpenGLSWFrameBuffer::DrawTriangleFans(int count, const BURNVERTEX *vertices) +{ + count = 2 + count; + + GLint oldBinding = 0; + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &oldBinding); + + if (!StreamVertexBufferBurn) + { + StreamVertexBufferBurn = std::make_unique(); + glGenVertexArrays(1, (GLuint*)&StreamVertexBufferBurn->VertexArray); + glGenBuffers(1, (GLuint*)&StreamVertexBufferBurn->Buffer); + glBindVertexArray(StreamVertexBufferBurn->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBufferBurn->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(BURNVERTEX), vertices, GL_STREAM_DRAW); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(BURNVERTEX), (const GLvoid*)offsetof(BURNVERTEX, x)); + glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(BURNVERTEX), (const GLvoid*)offsetof(BURNVERTEX, tu0)); + } + else + { + glBindVertexArray(StreamVertexBufferBurn->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBufferBurn->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(BURNVERTEX), vertices, GL_STREAM_DRAW); + } + + glDrawArrays(GL_TRIANGLE_FAN, 0, count); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(oldBinding); +} + +void OpenGLSWFrameBuffer::DrawPoints(int count, const FBVERTEX *vertices) +{ + GLint oldBinding = 0; + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &oldBinding); + + if (!StreamVertexBuffer) + { + StreamVertexBuffer = std::make_unique(); + glGenVertexArrays(1, (GLuint*)&StreamVertexBuffer->VertexArray); + glGenBuffers(1, (GLuint*)&StreamVertexBuffer->Buffer); + glBindVertexArray(StreamVertexBuffer->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBuffer->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(FBVERTEX), vertices, GL_STREAM_DRAW); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(1); + glEnableVertexAttribArray(2); + glEnableVertexAttribArray(3); + glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, x)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color0)); + glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, color1)); + glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(FBVERTEX), (const GLvoid*)offsetof(FBVERTEX, tu)); + } + else + { + glBindVertexArray(StreamVertexBuffer->VertexArray); + glBindBuffer(GL_ARRAY_BUFFER, StreamVertexBuffer->Buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(FBVERTEX), vertices, GL_STREAM_DRAW); + } + + glDrawArrays(GL_POINTS, 0, count); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(oldBinding); +} + +void OpenGLSWFrameBuffer::DrawLineList(int count) +{ + glDrawArrays(GL_LINES, 0, count * 2); +} + +void OpenGLSWFrameBuffer::DrawTriangleList(int minIndex, int numVertices, int startIndex, int primitiveCount) +{ + glDrawRangeElements(GL_TRIANGLES, minIndex, minIndex + numVertices - 1, primitiveCount * 3, GL_UNSIGNED_SHORT, (const void*)(startIndex * sizeof(uint16_t))); +} + +void OpenGLSWFrameBuffer::Present() +{ + int clientWidth = GetClientWidth(); + int clientHeight = GetClientHeight(); + if (clientWidth > 0 && clientHeight > 0) + { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, clientWidth, clientHeight); + + float scale = MIN(clientWidth / (float)Width, clientHeight / (float)Height); + int letterboxWidth = (int)round(Width * scale); + int letterboxHeight = (int)round(Height * scale); + int letterboxX = (clientWidth - letterboxWidth) / 2; + int letterboxY = (clientHeight - letterboxHeight) / 2; + + DrawLetterbox(letterboxX, letterboxY, letterboxWidth, letterboxHeight); + glViewport(letterboxX, letterboxY, letterboxWidth, letterboxHeight); + + FBVERTEX verts[4]; + CalcFullscreenCoords(verts, false, 0, 0xFFFFFFFF); + SetTexture(0, OutputFB->Texture); + SetPixelShader(Shaders[SHADER_GammaCorrection]); + SetAlphaBlend(0); + EnableAlphaTest(false); + DrawTriangleFans(2, verts); + } + + SwapBuffers(); + Debug->Update(); + + float screensize[4] = { (float)Width, (float)Height, 1.0f, 1.0f }; + SetPixelShaderConstantF(PSCONST_ScreenSize, screensize, 1); + + glBindFramebuffer(GL_FRAMEBUFFER, OutputFB->Framebuffer); + glViewport(0, 0, Width, Height); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: SetInitialState +// +// Called after initial device creation and reset, when everything is set +// to OpenGL's defaults. +// +//========================================================================== + +void OpenGLSWFrameBuffer::SetInitialState() +{ + AlphaBlendEnabled = false; + AlphaBlendOp = GL_FUNC_ADD; + AlphaSrcBlend = 0; + AlphaDestBlend = 0; + + CurPixelShader = nullptr; + memset(Constant, 0, sizeof(Constant)); + + for (unsigned i = 0; i < countof(Texture); ++i) + { + Texture[i] = nullptr; + SamplerWrapS[i] = GL_CLAMP_TO_EDGE; + SamplerWrapT[i] = GL_CLAMP_TO_EDGE; + } + + NeedGammaUpdate = true; + NeedPalUpdate = true; + + // This constant is used for grayscaling weights (.xyz) and color inversion (.w) + float weights[4] = { 77 / 256.f, 143 / 256.f, 37 / 256.f, 1 }; + SetPixelShaderConstantF(PSCONST_Weights, weights, 1); + + float screensize[4] = { (float)Width, (float)Height, 1.0f, 1.0f }; + SetPixelShaderConstantF(PSCONST_ScreenSize, screensize, 1); + + AlphaTestEnabled = false; + + CurBorderColor = 0; + + // Clear to black, just in case it wasn't done already. + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CreateResources +// +//========================================================================== + +bool OpenGLSWFrameBuffer::CreateResources() +{ + Atlases = nullptr; + if (!LoadShaders()) + { + return false; + } + + if (!CreateFrameBuffer("OutputFB", Width, Height, &OutputFB)) + return false; + glBindFramebuffer(GL_FRAMEBUFFER, OutputFB->Framebuffer); + + if (!CreateFBTexture() || + !CreatePaletteTexture()) + { + return false; + } + if (!CreateVertexes()) + { + return false; + } + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: LoadShaders +// +// Returns true if all required shaders were loaded. (Gamma and burn wipe +// are the only ones not considered "required".) +// +//========================================================================== + +bool OpenGLSWFrameBuffer::LoadShaders() +{ + int lumpvert = Wads.CheckNumForFullName("shaders/glsl/swshader.vp"); + int lumpfrag = Wads.CheckNumForFullName("shaders/glsl/swshader.fp"); + if (lumpvert < 0 || lumpfrag < 0) + return false; + + FString vertsource = Wads.ReadLump(lumpvert).GetString(); + FString fragsource = Wads.ReadLump(lumpfrag).GetString(); + + FString shaderdir, shaderpath; + unsigned int i; + + for (i = 0; i < NUM_SHADERS; ++i) + { + shaderpath = shaderdir; + if (!CreatePixelShader(vertsource, fragsource, ShaderDefines[i], &Shaders[i]) && i < SHADER_BurnWipe) + { + break; + } + + glUseProgram(Shaders[i]->Program); + if (Shaders[i]->ImageLocation != -1) glUniform1i(Shaders[i]->ImageLocation, 0); + if (Shaders[i]->PaletteLocation != -1) glUniform1i(Shaders[i]->PaletteLocation, 1); + if (Shaders[i]->NewScreenLocation != -1) glUniform1i(Shaders[i]->NewScreenLocation, 0); + if (Shaders[i]->BurnLocation != -1) glUniform1i(Shaders[i]->BurnLocation, 1); + glUseProgram(0); + } + if (i == NUM_SHADERS) + { // Success! + return true; + } + // Failure. Release whatever managed to load (which is probably nothing.) + for (i = 0; i < NUM_SHADERS; ++i) + { + SafeRelease(Shaders[i]); + } + return false; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: ReleaseResources +// +//========================================================================== + +void OpenGLSWFrameBuffer::ReleaseResources() +{ +#ifdef WIN32 + I_SaveWindowedPos(); +#endif + KillNativeTexs(); + KillNativePals(); + ReleaseDefaultPoolItems(); + SafeRelease(ScreenshotTexture); + SafeRelease(PaletteTexture); + for (int i = 0; i < NUM_SHADERS; ++i) + { + SafeRelease(Shaders[i]); + } + if (ScreenWipe != nullptr) + { + delete ScreenWipe; + ScreenWipe = nullptr; + } + Atlas *pack, *next; + for (pack = Atlases; pack != nullptr; pack = next) + { + next = pack->Next; + delete pack; + } + GatheringWipeScreen = false; +} + +void OpenGLSWFrameBuffer::ReleaseDefaultPoolItems() +{ + SafeRelease(FBTexture); + SafeRelease(FinalWipeScreen); + SafeRelease(InitialWipeScreen); + SafeRelease(VertexBuffer); + SafeRelease(IndexBuffer); + SafeRelease(OutputFB); +} + +bool OpenGLSWFrameBuffer::Reset() +{ + ReleaseDefaultPoolItems(); + + if (!CreateFrameBuffer("OutputFB", Width, Height, &OutputFB) || !CreateFBTexture() || !CreateVertexes()) + { + return false; + } + + glBindFramebuffer(GL_FRAMEBUFFER, OutputFB->Framebuffer); + glViewport(0, 0, Width, Height); + + SetInitialState(); + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: KillNativePals +// +// Frees all native palettes. +// +//========================================================================== + +void OpenGLSWFrameBuffer::KillNativePals() +{ + while (Palettes != nullptr) + { + delete Palettes; + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: KillNativeTexs +// +// Frees all native textures. +// +//========================================================================== + +void OpenGLSWFrameBuffer::KillNativeTexs() +{ + while (Textures != nullptr) + { + delete Textures; + } +} + +bool OpenGLSWFrameBuffer::CreateFBTexture() +{ + return CreateTexture("FBTexture", Width, Height, 1, IsBgra() ? GL_RGBA8 : GL_R8, &FBTexture); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CreatePaletteTexture +// +//========================================================================== + +bool OpenGLSWFrameBuffer::CreatePaletteTexture() +{ + return CreateTexture("PaletteTexture", 256, 1, 1, GL_RGBA8, &PaletteTexture); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CreateVertexes +// +//========================================================================== + +bool OpenGLSWFrameBuffer::CreateVertexes() +{ + VertexPos = -1; + IndexPos = -1; + QuadBatchPos = -1; + BatchType = BATCH_None; + if (!CreateVertexBuffer(sizeof(FBVERTEX)*NUM_VERTS, &VertexBuffer)) + { + return false; + } + if (!CreateIndexBuffer(sizeof(uint16_t)*NUM_INDEXES, &IndexBuffer)) + { + return false; + } + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CalcFullscreenCoords +// +//========================================================================== + +void OpenGLSWFrameBuffer::CalcFullscreenCoords(FBVERTEX verts[4], bool viewarea_only, uint32_t color0, uint32_t color1) const +{ + float mxl, mxr, myt, myb, tmxl, tmxr, tmyt, tmyb; + + if (viewarea_only) + { // Just calculate vertices for the viewarea/BlendingRect + mxl = float(BlendingRect.left); + mxr = float(BlendingRect.right); + myt = float(BlendingRect.top); + myb = float(BlendingRect.bottom); + tmxl = float(BlendingRect.left) / float(Width); + tmxr = float(BlendingRect.right) / float(Width); + tmyt = float(BlendingRect.top) / float(Height); + tmyb = float(BlendingRect.bottom) / float(Height); + } + else + { // Calculate vertices for the whole screen + mxl = 0.0f; + mxr = float(Width); + myt = 0.0f; + myb = float(Height); + tmxl = 0; + tmxr = 1.0f; + tmyt = 0; + tmyb = 1.0f; + } + + //{ mxl, myt, 0, 1, 0, 0xFFFFFFFF, tmxl, tmyt }, + //{ mxr, myt, 0, 1, 0, 0xFFFFFFFF, tmxr, tmyt }, + //{ mxr, myb, 0, 1, 0, 0xFFFFFFFF, tmxr, tmyb }, + //{ mxl, myb, 0, 1, 0, 0xFFFFFFFF, tmxl, tmyb }, + + verts[0].x = mxl; + verts[0].y = myt; + verts[0].z = 0; + verts[0].rhw = 1; + verts[0].color0 = color0; + verts[0].color1 = color1; + verts[0].tu = tmxl; + verts[0].tv = tmyt; + + verts[1].x = mxr; + verts[1].y = myt; + verts[1].z = 0; + verts[1].rhw = 1; + verts[1].color0 = color0; + verts[1].color1 = color1; + verts[1].tu = tmxr; + verts[1].tv = tmyt; + + verts[2].x = mxr; + verts[2].y = myb; + verts[2].z = 0; + verts[2].rhw = 1; + verts[2].color0 = color0; + verts[2].color1 = color1; + verts[2].tu = tmxr; + verts[2].tv = tmyb; + + verts[3].x = mxl; + verts[3].y = myb; + verts[3].z = 0; + verts[3].rhw = 1; + verts[3].color0 = color0; + verts[3].color1 = color1; + verts[3].tu = tmxl; + verts[3].tv = tmyb; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: GetPageCount +// +//========================================================================== + +int OpenGLSWFrameBuffer::GetPageCount() +{ + return 1; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: IsValid +// +//========================================================================== + +bool OpenGLSWFrameBuffer::IsValid() +{ + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Lock +// +//========================================================================== + +bool OpenGLSWFrameBuffer::Lock(bool buffered) +{ + if (LockCount++ > 0) + { + return false; + } + assert(!In2D); + Accel2D = vid_hw2d; + if (UseMappedMemBuffer) + { + if (!MappedMemBuffer) + { + BindFBBuffer(); + + MappedMemBuffer = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE); + Pitch = Width; + if (MappedMemBuffer == nullptr) + return true; + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + } + Buffer = (uint8_t*)MappedMemBuffer; + } + else + { + Buffer = MemBuffer; + } + return false; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Unlock +// +//========================================================================== + +void OpenGLSWFrameBuffer::Unlock() +{ + if (LockCount == 0) + { + return; + } + + if (UpdatePending && LockCount == 1) + { + Update(); + } + else if (--LockCount == 0) + { + Buffer = nullptr; + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Update +// +// When In2D == 0: Copy buffer to screen and present +// When In2D == 1: Copy buffer to screen but do not present +// When In2D == 2: Set up for 2D drawing but do not draw anything +// When In2D == 3: Present and set In2D to 0 +// +//========================================================================== + +void OpenGLSWFrameBuffer::Update() +{ + if (In2D == 3) + { + if (InScene) + { + DrawRateStuff(); + DrawPackedTextures(gl_showpacks); + EndBatch(); // Make sure all batched primitives are drawn. + Flip(); + } + In2D = 0; + return; + } + + if (LockCount != 1) + { + I_FatalError("Framebuffer must have exactly 1 lock to be updated"); + if (LockCount > 0) + { + UpdatePending = true; + --LockCount; + } + return; + } + + if (In2D == 0) + { + DrawRateStuff(); + } + + if (NeedGammaUpdate) + { + float psgamma[4]; + float igamma; + + NeedGammaUpdate = false; + igamma = 1 / Gamma; + if (IsFullscreen()) + { + GammaRamp ramp; + + for (int i = 0; i < 256; ++i) + { + ramp.blue[i] = ramp.green[i] = ramp.red[i] = uint16_t(65535.f * powf(i / 255.f, igamma)); + } + SetGammaRamp(&ramp); + } + psgamma[2] = psgamma[1] = psgamma[0] = igamma; + psgamma[3] = 0.5; // For SM14 version + SetPixelShaderConstantF(PSCONST_Gamma, psgamma, 1); + } + + if (NeedPalUpdate) + { + UploadPalette(); + NeedPalUpdate = false; + } + +#ifdef WIN32 + BlitCycles.Reset(); + BlitCycles.Clock(); +#endif + + LockCount = 0; + Draw3DPart(In2D <= 1); + if (In2D == 0) + { + Flip(); + } + +#ifdef WIN32 + BlitCycles.Unclock(); + //LOG1 ("cycles = %d\n", BlitCycles); +#endif + + Buffer = nullptr; + UpdatePending = false; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Flip +// +//========================================================================== + +void OpenGLSWFrameBuffer::Flip() +{ + assert(InScene); + + Present(); + InScene = false; + + if (!IsFullscreen()) + { + int clientWidth = ClampWidth(GetClientWidth()); + int clientHeight = ClampHeight(GetClientHeight()); + if (clientWidth > 0 && clientHeight > 0 && (Width != clientWidth || Height != clientHeight)) + { + Resize(clientWidth, clientHeight); + + TrueHeight = Height; + PixelDoubling = 0; + Reset(); + + V_OutputResized(Width, Height); + } + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: PaintToWindow +// +//========================================================================== + +#ifdef WIN32 + +bool OpenGLSWFrameBuffer::PaintToWindow() +{ + if (LockCount != 0) + { + return false; + } + Draw3DPart(true); + return true; +} + +#endif + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Draw3DPart +// +// The software 3D part, to be exact. +// +//========================================================================== + +void OpenGLSWFrameBuffer::BindFBBuffer() +{ + int usage = UseMappedMemBuffer ? GL_DYNAMIC_DRAW : GL_STREAM_DRAW; + + int pixelsize = IsBgra() ? 4 : 1; + int size = Width * Height * pixelsize; + + if (FBTexture->Buffers[0] == 0) + { + glGenBuffers(2, (GLuint*)FBTexture->Buffers); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, FBTexture->Buffers[1]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, size, nullptr, usage); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, FBTexture->Buffers[0]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, size, nullptr, usage); + } + else + { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, FBTexture->Buffers[FBTexture->CurrentBuffer]); + } +} + +void OpenGLSWFrameBuffer::Draw3DPart(bool copy3d) +{ + if (copy3d) + { + BindFBBuffer(); + FBTexture->CurrentBuffer = (FBTexture->CurrentBuffer + 1) & 1; + + if (!UseMappedMemBuffer) + { + int pixelsize = IsBgra() ? 4 : 1; + int size = Width * Height * pixelsize; + + uint8_t *dest = (uint8_t*)MapBuffer(GL_PIXEL_UNPACK_BUFFER, size); + if (dest) + { + if (Pitch == Width) + { + memcpy(dest, MemBuffer, Width * Height * pixelsize); + } + else + { + uint8_t *src = MemBuffer; + for (int y = 0; y < Height; y++) + { + memcpy(dest, src, Width * pixelsize); + dest += Width * pixelsize; + src += Pitch * pixelsize; + } + } + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + } + } + else if (MappedMemBuffer) + { + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + MappedMemBuffer = nullptr; + } + + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + glBindTexture(GL_TEXTURE_2D, FBTexture->Texture); + if (IsBgra()) + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, Width, Height, GL_BGRA, GL_UNSIGNED_BYTE, 0); + else + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, Width, Height, GL_RED, GL_UNSIGNED_BYTE, 0); + glBindTexture(GL_TEXTURE_2D, oldBinding); + + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + } + InScene = true; + if (vid_hwaalines) + glEnable(GL_LINE_SMOOTH); + else + glDisable(GL_LINE_SMOOTH); + + SetTexture(0, FBTexture); + SetPaletteTexture(PaletteTexture, 256, BorderColor); + memset(Constant, 0, sizeof(Constant)); + SetAlphaBlend(0); + EnableAlphaTest(false); + if (IsBgra()) + SetPixelShader(Shaders[SHADER_NormalColor]); + else + SetPixelShader(Shaders[SHADER_NormalColorPal]); + if (copy3d) + { + FBVERTEX verts[4]; + uint32_t color0, color1; + if (Accel2D) + { + auto &map = swrenderer::realfixedcolormap; + if (map == nullptr) + { + color0 = 0; + color1 = 0xFFFFFFF; + } + else + { + color0 = ColorValue(map->ColorizeStart[0] / 2, map->ColorizeStart[1] / 2, map->ColorizeStart[2] / 2, 0); + color1 = ColorValue(map->ColorizeEnd[0] / 2, map->ColorizeEnd[1] / 2, map->ColorizeEnd[2] / 2, 1); + if (IsBgra()) + SetPixelShader(Shaders[SHADER_SpecialColormap]); + else + SetPixelShader(Shaders[SHADER_SpecialColormapPal]); + } + } + else + { + color0 = FlashColor0; + color1 = FlashColor1; + } + CalcFullscreenCoords(verts, Accel2D, color0, color1); + DrawTriangleFans(2, verts); + } + if (IsBgra()) + SetPixelShader(Shaders[SHADER_NormalColor]); + else + SetPixelShader(Shaders[SHADER_NormalColorPal]); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawLetterbox +// +// Draws the black bars at the top and bottom of the screen for letterboxed +// modes. +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawLetterbox(int x, int y, int width, int height) +{ + int clientWidth = GetClientWidth(); + int clientHeight = GetClientHeight(); + if (clientWidth == 0 || clientHeight == 0) + return; + + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glEnable(GL_SCISSOR_TEST); + if (y > 0) + { + glScissor(0, 0, clientWidth, y); + glClear(GL_COLOR_BUFFER_BIT); + } + if (clientHeight - y - height > 0) + { + glScissor(0, y + height, clientWidth, clientHeight - y - height); + glClear(GL_COLOR_BUFFER_BIT); + } + if (x > 0) + { + glScissor(0, y, x, height); + glClear(GL_COLOR_BUFFER_BIT); + } + if (clientWidth - x - width > 0) + { + glScissor(x + width, y, clientWidth - x - width, height); + glClear(GL_COLOR_BUFFER_BIT); + } + glDisable(GL_SCISSOR_TEST); +} + +void OpenGLSWFrameBuffer::UploadPalette() +{ + if (PaletteTexture->Buffers[0] == 0) + { + glGenBuffers(2, (GLuint*)PaletteTexture->Buffers); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, PaletteTexture->Buffers[0]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, 256 * 4, nullptr, GL_STREAM_DRAW); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, PaletteTexture->Buffers[1]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, 256 * 4, nullptr, GL_STREAM_DRAW); + } + else + { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, PaletteTexture->Buffers[PaletteTexture->CurrentBuffer]); + PaletteTexture->CurrentBuffer = (PaletteTexture->CurrentBuffer + 1) & 1; + } + + uint8_t *pix = (uint8_t*)MapBuffer(GL_PIXEL_UNPACK_BUFFER, 256 * 4); + if (pix) + { + int i; + + for (i = 0; i < 256; ++i, pix += 4) + { + pix[0] = SourcePalette[i].b; + pix[1] = SourcePalette[i].g; + pix[2] = SourcePalette[i].r; + pix[3] = (i == 0 ? 0 : 255); + // To let masked textures work, the first palette entry's alpha is 0. + } + pix += 4; + for (; i < 255; ++i, pix += 4) + { + pix[0] = SourcePalette[i].b; + pix[1] = SourcePalette[i].g; + pix[2] = SourcePalette[i].r; + pix[3] = 255; + } + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + glBindTexture(GL_TEXTURE_2D, PaletteTexture->Texture); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 256, 1, GL_BGRA, GL_UNSIGNED_BYTE, 0); + glBindTexture(GL_TEXTURE_2D, oldBinding); + BorderColor = ColorXRGB(SourcePalette[255].r, SourcePalette[255].g, SourcePalette[255].b); + } + + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); +} + +PalEntry *OpenGLSWFrameBuffer::GetPalette() +{ + return SourcePalette; +} + +void OpenGLSWFrameBuffer::UpdatePalette() +{ + NeedPalUpdate = true; +} + +bool OpenGLSWFrameBuffer::SetGamma(float gamma) +{ + Gamma = gamma; + NeedGammaUpdate = true; + return true; +} + +bool OpenGLSWFrameBuffer::SetFlash(PalEntry rgb, int amount) +{ + FlashColor = rgb; + FlashAmount = amount; + + // Fill in the constants for the pixel shader to do linear interpolation between the palette and the flash: + float r = rgb.r / 255.f, g = rgb.g / 255.f, b = rgb.b / 255.f, a = amount / 256.f; + FlashColor0 = ColorValue(r * a, g * a, b * a, 0); + a = 1 - a; + FlashColor1 = ColorValue(a, a, a, 1); + return true; +} + +void OpenGLSWFrameBuffer::GetFlash(PalEntry &rgb, int &amount) +{ + rgb = FlashColor; + amount = FlashAmount; +} + +void OpenGLSWFrameBuffer::GetFlashedPalette(PalEntry pal[256]) +{ + memcpy(pal, SourcePalette, 256 * sizeof(PalEntry)); + if (FlashAmount) + { + DoBlending(pal, pal, 256, FlashColor.r, FlashColor.g, FlashColor.b, FlashAmount); + } +} + +void OpenGLSWFrameBuffer::SetVSync(bool vsync) +{ + // Switch to the default frame buffer because Nvidia's driver associates the vsync state with the bound FB object. + GLint oldDrawFramebufferBinding = 0, oldReadFramebufferBinding = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &oldDrawFramebufferBinding); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &oldReadFramebufferBinding); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + + Super::SetVSync(vsync); + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, oldDrawFramebufferBinding); + glBindFramebuffer(GL_READ_FRAMEBUFFER, oldReadFramebufferBinding); +} + +void OpenGLSWFrameBuffer::NewRefreshRate() +{ +} + +void OpenGLSWFrameBuffer::SetBlendingRect(int x1, int y1, int x2, int y2) +{ + BlendingRect.left = x1; + BlendingRect.top = y1; + BlendingRect.right = x2; + BlendingRect.bottom = y2; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: GetScreenshotBuffer +// +// Returns a pointer into a surface holding the current screen data. +// +//========================================================================== + +void OpenGLSWFrameBuffer::GetScreenshotBuffer(const uint8_t *&buffer, int &pitch, ESSType &color_type) +{ + Super::GetScreenshotBuffer(buffer, pitch, color_type); + /* + LockedRect lrect; + + if (!Accel2D) + { + Super::GetScreenshotBuffer(buffer, pitch, color_type); + return; + } + buffer = nullptr; + if ((ScreenshotTexture = GetCurrentScreen()) != nullptr) + { + if (!ScreenshotTexture->GetSurfaceLevel(0, &ScreenshotSurface)) + { + delete ScreenshotTexture; + ScreenshotTexture = nullptr; + } + else if (!ScreenshotSurface->LockRect(&lrect, nullptr, false)) + { + delete ScreenshotSurface; + ScreenshotSurface = nullptr; + delete ScreenshotTexture; + ScreenshotTexture = nullptr; + } + else + { + buffer = (const uint8_t *)lrect.pBits; + pitch = lrect.Pitch; + color_type = SS_BGRA; + } + } + */ +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: ReleaseScreenshotBuffer +// +//========================================================================== + +void OpenGLSWFrameBuffer::ReleaseScreenshotBuffer() +{ + if (LockCount > 0) + { + Super::ReleaseScreenshotBuffer(); + } + SafeRelease(ScreenshotTexture); +} + +/**************************************************************************/ +/* 2D Stuff */ +/**************************************************************************/ + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawPackedTextures +// +// DEBUG: Draws the texture atlases to the screen, starting with the +// 1-based packnum. Ignores atlases that are flagged for use by one +// texture only. +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawPackedTextures(int packnum) +{ + uint32_t empty_colors[8] = + { + 0x50FF0000, 0x5000FF00, 0x500000FF, 0x50FFFF00, + 0x50FF00FF, 0x5000FFFF, 0x50FF8000, 0x500080FF + }; + Atlas *pack; + int x = 8, y = 8; + + if (packnum <= 0) + { + return; + } + pack = Atlases; + // Find the first texture atlas that is an actual atlas. + while (pack != nullptr && pack->OneUse) + { // Skip textures that aren't used as atlases + pack = pack->Next; + } + // Skip however many atlases we would have otherwise drawn + // until we've skipped of them. + while (pack != nullptr && packnum != 1) + { + if (!pack->OneUse) + { // Skip textures that aren't used as atlases + packnum--; + } + pack = pack->Next; + } + // Draw atlases until we run out of room on the screen. + while (pack != nullptr) + { + if (pack->OneUse) + { // Skip textures that aren't used as atlases + pack = pack->Next; + continue; + } + + AddColorOnlyRect(x - 1, y - 1, 258, 258, ColorXRGB(255, 255, 0)); + int back = 0; + for (PackedTexture *box = pack->UsedList; box != nullptr; box = box->Next) + { + AddColorOnlyQuad( + x + box->Area.left * 256 / pack->Width, + y + box->Area.top * 256 / pack->Height, + (box->Area.right - box->Area.left) * 256 / pack->Width, + (box->Area.bottom - box->Area.top) * 256 / pack->Height, empty_colors[back]); + back = (back + 1) & 7; + } + // AddColorOnlyQuad(x, y-LBOffsetI, 256, 256, ColorARGB(180,0,0,0)); + + CheckQuadBatch(); + + BufferedTris *quad = &QuadExtra[QuadBatchPos]; + FBVERTEX *vert = &VertexData[VertexPos]; + + quad->ClearSetup(); + if (pack->Format == GL_R8/* && !tex->IsGray*/) + { + quad->Flags = BQF_WrapUV | BQF_GamePalette/* | BQF_DisableAlphaTest*/; + quad->ShaderNum = BQS_PalTex; + } + else + { + quad->Flags = BQF_WrapUV/* | BQF_DisableAlphaTest*/; + quad->ShaderNum = BQS_Plain; + } + quad->Palette = nullptr; + quad->Texture = pack->Tex; + quad->NumVerts = 4; + quad->NumTris = 2; + + float x0 = float(x); + float y0 = float(y); + float x1 = x0 + 256.f; + float y1 = y0 + 256.f; + + vert[0].x = x0; + vert[0].y = y0; + vert[0].z = 0; + vert[0].rhw = 1; + vert[0].color0 = 0; + vert[0].color1 = 0xFFFFFFFF; + vert[0].tu = 0; + vert[0].tv = 0; + + vert[1].x = x1; + vert[1].y = y0; + vert[1].z = 0; + vert[1].rhw = 1; + vert[1].color0 = 0; + vert[1].color1 = 0xFFFFFFFF; + vert[1].tu = 1; + vert[1].tv = 0; + + vert[2].x = x1; + vert[2].y = y1; + vert[2].z = 0; + vert[2].rhw = 1; + vert[2].color0 = 0; + vert[2].color1 = 0xFFFFFFFF; + vert[2].tu = 1; + vert[2].tv = 1; + + vert[3].x = x0; + vert[3].y = y1; + vert[3].z = 0; + vert[3].rhw = 1; + vert[3].color0 = 0; + vert[3].color1 = 0xFFFFFFFF; + vert[3].tu = 0; + vert[3].tv = 1; + + IndexData[IndexPos] = VertexPos; + IndexData[IndexPos + 1] = VertexPos + 1; + IndexData[IndexPos + 2] = VertexPos + 2; + IndexData[IndexPos + 3] = VertexPos; + IndexData[IndexPos + 4] = VertexPos + 2; + IndexData[IndexPos + 5] = VertexPos + 3; + + QuadBatchPos++; + VertexPos += 4; + IndexPos += 6; + + x += 256 + 8; + if (x > Width - 256) + { + x = 8; + y += 256 + 8; + if (y > Height - 256) + { + return; + } + } + pack = pack->Next; + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: AllocPackedTexture +// +// Finds space to pack an image inside a texture atlas and returns it. +// Large images and those that need to wrap always get their own textures. +// +//========================================================================== + +OpenGLSWFrameBuffer::PackedTexture *OpenGLSWFrameBuffer::AllocPackedTexture(int w, int h, bool wrapping, int format) +{ + Atlas *pack; + Rect box; + bool padded; + + // The - 2 to account for padding + if (w > 256 - 2 || h > 256 - 2 || wrapping) + { // Create a new texture atlas. + pack = new Atlas(this, w, h, format); + pack->OneUse = true; + box = pack->Packer.Insert(w, h); + padded = false; + } + else + { // Try to find space in an existing texture atlas. + w += 2; // Add padding + h += 2; + for (pack = Atlases; pack != nullptr; pack = pack->Next) + { + // Use the first atlas it fits in. + if (pack->Format == format) + { + box = pack->Packer.Insert(w, h); + if (box.width != 0) + { + break; + } + } + } + if (pack == nullptr) + { // Create a new texture atlas. + pack = new Atlas(this, DEF_ATLAS_WIDTH, DEF_ATLAS_HEIGHT, format); + box = pack->Packer.Insert(w, h); + } + padded = true; + } + assert(box.width != 0 && box.height != 0); + return pack->AllocateImage(box, padded); +} + +//========================================================================== +// +// Atlas Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Atlas::Atlas(OpenGLSWFrameBuffer *fb, int w, int h, int format) + : Packer(w, h, true) +{ + Tex = nullptr; + Format = format; + UsedList = nullptr; + OneUse = false; + Width = 0; + Height = 0; + Next = nullptr; + + // Attach to the end of the atlas list + Atlas **prev = &fb->Atlases; + while (*prev != nullptr) + { + prev = &((*prev)->Next); + } + *prev = this; + + fb->CreateTexture("Atlas", w, h, 1, format, &Tex); + Width = w; + Height = h; +} + +//========================================================================== +// +// Atlas Destructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Atlas::~Atlas() +{ + PackedTexture *box, *next; + + SafeRelease(Tex); + for (box = UsedList; box != nullptr; box = next) + { + next = box->Next; + delete box; + } +} + +//========================================================================== +// +// Atlas :: AllocateImage +// +// Moves the box from the empty list to the used list, sizing it to the +// requested dimensions and adding additional boxes to the empty list if +// needed. +// +// The passed box *MUST* be in this texture atlas's empty list. +// +//========================================================================== + +OpenGLSWFrameBuffer::PackedTexture *OpenGLSWFrameBuffer::Atlas::AllocateImage(const Rect &rect, bool padded) +{ + PackedTexture *box = new PackedTexture; + + box->Owner = this; + box->Area.left = rect.x; + box->Area.top = rect.y; + box->Area.right = rect.x + rect.width; + box->Area.bottom = rect.y + rect.height; + + box->Left = float(box->Area.left + padded) / Width; + box->Right = float(box->Area.right - padded) / Width; + box->Top = float(box->Area.top + padded) / Height; + box->Bottom = float(box->Area.bottom - padded) / Height; + + box->Padded = padded; + + // Add it to the used list. + box->Next = UsedList; + if (box->Next != nullptr) + { + box->Next->Prev = &box->Next; + } + UsedList = box; + box->Prev = &UsedList; + + return box; +} + +//========================================================================== +// +// Atlas :: FreeBox +// +// Removes a box from the used list and deletes it. Space is returned to the +// waste list. Once all boxes for this atlas are freed, the entire bin +// packer is reinitialized for maximum efficiency. +// +//========================================================================== + +void OpenGLSWFrameBuffer::Atlas::FreeBox(OpenGLSWFrameBuffer::PackedTexture *box) +{ + *(box->Prev) = box->Next; + if (box->Next != nullptr) + { + box->Next->Prev = box->Prev; + } + Rect waste; + waste.x = box->Area.left; + waste.y = box->Area.top; + waste.width = box->Area.right - box->Area.left; + waste.height = box->Area.bottom - box->Area.top; + box->Owner->Packer.AddWaste(waste); + delete box; + if (UsedList == nullptr) + { + Packer.Init(Width, Height, true); + } +} + +//========================================================================== +// +// OpenGLTex Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::OpenGLTex::OpenGLTex(FTexture *tex, OpenGLSWFrameBuffer *fb, bool wrapping) +{ + // Attach to the texture list for the OpenGLSWFrameBuffer + Next = fb->Textures; + if (Next != nullptr) + { + Next->Prev = &Next; + } + Prev = &fb->Textures; + fb->Textures = this; + + GameTex = tex; + Box = nullptr; + IsGray = false; + + Create(fb, wrapping); +} + +//========================================================================== +// +// OpenGLTex Destructor +// +//========================================================================== + +OpenGLSWFrameBuffer::OpenGLTex::~OpenGLTex() +{ + if (Box != nullptr) + { + Box->Owner->FreeBox(Box); + Box = nullptr; + } + // Detach from the texture list + *Prev = Next; + if (Next != nullptr) + { + Next->Prev = Prev; + } + // Remove link from the game texture + if (GameTex != nullptr) + { + GameTex->Native = nullptr; + } +} + +//========================================================================== +// +// OpenGLTex :: CheckWrapping +// +// Returns true if the texture is compatible with the specified wrapping +// mode. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::OpenGLTex::CheckWrapping(bool wrapping) +{ + // If it doesn't need to wrap, then it works. + if (!wrapping) + { + return true; + } + // If it needs to wrap, then it can't be packed inside another texture. + return Box->Owner->OneUse; +} + +//========================================================================== +// +// OpenGLTex :: Create +// +// Creates an HWTexture for the texture and copies the image data +// to it. Note that unlike FTexture, this image is row-major. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::OpenGLTex::Create(OpenGLSWFrameBuffer *fb, bool wrapping) +{ + assert(Box == nullptr); + if (Box != nullptr) + { + Box->Owner->FreeBox(Box); + } + + Box = fb->AllocPackedTexture(GameTex->GetWidth(), GameTex->GetHeight(), wrapping, GetTexFormat()); + + if (Box == nullptr) + { + return false; + } + if (!Update()) + { + Box->Owner->FreeBox(Box); + Box = nullptr; + return false; + } + return true; +} + +//========================================================================== +// +// OpenGLTex :: Update +// +// Copies image data from the underlying FTexture to the OpenGL texture. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::OpenGLTex::Update() +{ + LTRBRect rect; + uint8_t *dest; + + assert(Box != nullptr); + assert(Box->Owner != nullptr); + assert(Box->Owner->Tex != nullptr); + assert(GameTex != nullptr); + + int format = Box->Owner->Tex->Format; + + rect = Box->Area; + + if (Box->Owner->Tex->Buffers[0] == 0) + glGenBuffers(2, (GLuint*)Box->Owner->Tex->Buffers); + + int bytesPerPixel = 4; + switch (format) + { + case GL_R8: bytesPerPixel = 1; break; + case GL_RGBA8: bytesPerPixel = 4; break; + default: return false; + } + + int buffersize = (rect.right - rect.left) * (rect.bottom - rect.top) * bytesPerPixel; + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, Box->Owner->Tex->Buffers[Box->Owner->Tex->CurrentBuffer]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, buffersize, nullptr, GL_STREAM_DRAW); + Box->Owner->Tex->CurrentBuffer = (Box->Owner->Tex->CurrentBuffer + 1) & 1; + + int pitch = (rect.right - rect.left) * bytesPerPixel; + uint8_t *bits = (uint8_t *)MapBuffer(GL_PIXEL_UNPACK_BUFFER, buffersize); + dest = bits; + if (!dest) + { + return false; + } + if (Box->Padded) + { + dest += pitch + (format == GL_R8 ? 1 : 4); + } + GameTex->FillBuffer(dest, pitch, GameTex->GetHeight(), ToTexFmt(format)); + if (Box->Padded) + { + // Clear top padding row. + dest = bits; + int numbytes = GameTex->GetWidth() + 2; + if (format != GL_R8) + { + numbytes <<= 2; + } + memset(dest, 0, numbytes); + dest += pitch; + // Clear left and right padding columns. + if (format == GL_R8) + { + for (int y = Box->Area.bottom - Box->Area.top - 2; y > 0; --y) + { + dest[0] = 0; + dest[numbytes - 1] = 0; + dest += pitch; + } + } + else + { + for (int y = Box->Area.bottom - Box->Area.top - 2; y > 0; --y) + { + *(uint32_t *)dest = 0; + *(uint32_t *)(dest + numbytes - 4) = 0; + dest += pitch; + } + } + // Clear bottom padding row. + memset(dest, 0, numbytes); + } + + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + glBindTexture(GL_TEXTURE_2D, Box->Owner->Tex->Texture); + if (format == GL_RGBA8) + glTexSubImage2D(GL_TEXTURE_2D, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, GL_BGRA, GL_UNSIGNED_BYTE, 0); + else + glTexSubImage2D(GL_TEXTURE_2D, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, GL_RED, GL_UNSIGNED_BYTE, 0); + glBindTexture(GL_TEXTURE_2D, oldBinding); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + return true; +} + +//========================================================================== +// +// OpenGLTex :: GetTexFormat +// +// Returns the texture format that would best fit this texture. +// +//========================================================================== + +int OpenGLSWFrameBuffer::OpenGLTex::GetTexFormat() +{ + FTextureFormat fmt = GameTex->GetFormat(); + + IsGray = false; + + switch (fmt) + { + case TEX_Pal: return GL_R8; + case TEX_Gray: IsGray = true; return GL_R8; + case TEX_RGB: return GL_RGBA8; + case TEX_DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; + case TEX_DXT2: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + case TEX_DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; + case TEX_DXT4: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; // Doesn't exist in OpenGL. Closest match is DXT5. + case TEX_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + default: I_FatalError("GameTex->GetFormat() returned invalid format."); + } + return GL_R8; +} + +//========================================================================== +// +// OpenGLTex :: ToTexFmt +// +// Converts an OpenGL internal format constant to something the FTexture system +// understands. +// +//========================================================================== + +FTextureFormat OpenGLSWFrameBuffer::OpenGLTex::ToTexFmt(int fmt) +{ + switch (fmt) + { + case GL_R8: return IsGray ? TEX_Gray : TEX_Pal; + case GL_RGBA8: return TEX_RGB; + case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return TEX_DXT1; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return TEX_DXT2; + case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: return TEX_DXT3; + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return TEX_DXT5; + default: + assert(0); // LOL WUT? + return TEX_Pal; + } +} + +//========================================================================== +// +// OpenGLPal Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::OpenGLPal::OpenGLPal(FRemapTable *remap, OpenGLSWFrameBuffer *fb) + : Tex(nullptr), Remap(remap) +{ + int count; + + // Attach to the palette list for the OpenGLSWFrameBuffer + Next = fb->Palettes; + if (Next != nullptr) + { + Next->Prev = &Next; + } + Prev = &fb->Palettes; + fb->Palettes = this; + + int pow2count; + + // Round up to the nearest power of 2. + for (pow2count = 1; pow2count < remap->NumEntries; pow2count <<= 1) + { + } + count = pow2count; + DoColorSkip = false; + + BorderColor = 0; + RoundedPaletteSize = count; + if (fb->CreateTexture("Pal", count, 1, 1, GL_RGBA8, &Tex)) + { + if (!Update()) + { + delete Tex; + Tex = nullptr; + } + } +} + +//========================================================================== +// +// OpenGLPal Destructor +// +//========================================================================== + +OpenGLSWFrameBuffer::OpenGLPal::~OpenGLPal() +{ + SafeRelease(Tex); + // Detach from the palette list + *Prev = Next; + if (Next != nullptr) + { + Next->Prev = Prev; + } + // Remove link from the remap table + if (Remap != nullptr) + { + Remap->Native = nullptr; + } +} + +//========================================================================== +// +// OpenGLPal :: Update +// +// Copies the palette to the texture. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::OpenGLPal::Update() +{ + uint32_t *buff; + const PalEntry *pal; + int skipat, i; + + assert(Tex != nullptr); + + if (Tex->Buffers[0] == 0) + { + glGenBuffers(2, (GLuint*)Tex->Buffers); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, Tex->Buffers[0]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, RoundedPaletteSize * 4, nullptr, GL_STREAM_DRAW); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, Tex->Buffers[1]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, RoundedPaletteSize * 4, nullptr, GL_STREAM_DRAW); + } + else + { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, Tex->Buffers[Tex->CurrentBuffer]); + Tex->CurrentBuffer = (Tex->CurrentBuffer + 1) & 1; + } + + int numEntries = MIN(Remap->NumEntries, RoundedPaletteSize); + + buff = (uint32_t *)MapBuffer(GL_PIXEL_UNPACK_BUFFER, numEntries * 4); + if (buff == nullptr) + { + return false; + } + pal = Remap->Palette; + + // See explanation in UploadPalette() for skipat rationale. + skipat = MIN(numEntries, DoColorSkip ? 256 - 8 : 256); + + for (i = 0; i < skipat; ++i) + { + buff[i] = ColorARGB(pal[i].a, pal[i].r, pal[i].g, pal[i].b); + } + for (++i; i < numEntries; ++i) + { + buff[i] = ColorARGB(pal[i].a, pal[i - 1].r, pal[i - 1].g, pal[i - 1].b); + } + if (numEntries > 1) + { + i = numEntries - 1; + BorderColor = ColorARGB(pal[i].a, pal[i - 1].r, pal[i - 1].g, pal[i - 1].b); + } + + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + glBindTexture(GL_TEXTURE_2D, Tex->Texture); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, numEntries, 1, GL_BGRA, GL_UNSIGNED_BYTE, 0); + glBindTexture(GL_TEXTURE_2D, oldBinding); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Begin2D +// +// Begins 2D mode drawing operations. In particular, DrawTexture is +// rerouted to use Direct3D instead of the software renderer. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::Begin2D(bool copy3d) +{ + if (!Accel2D) + { + return false; + } + if (In2D) + { + return true; + } + In2D = 2 - copy3d; + Update(); + In2D = 3; + + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawBlendingRect +// +// Call after Begin2D to blend the 3D view. +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawBlendingRect() +{ + if (!In2D || !Accel2D) + { + return; + } + Dim(FlashColor, FlashAmount / 256.f, viewwindowx, viewwindowy, viewwidth, viewheight); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CreateTexture +// +// Returns a native texture that wraps a FTexture. +// +//========================================================================== + +FNativeTexture *OpenGLSWFrameBuffer::CreateTexture(FTexture *gametex, bool wrapping) +{ + OpenGLTex *tex = new OpenGLTex(gametex, this, wrapping); + if (tex->Box == nullptr) + { + delete tex; + return nullptr; + } + return tex; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CreatePalette +// +// Returns a native texture that contains a palette. +// +//========================================================================== + +FNativePalette *OpenGLSWFrameBuffer::CreatePalette(FRemapTable *remap) +{ + OpenGLPal *tex = new OpenGLPal(remap, this); + if (tex->Tex == nullptr) + { + delete tex; + return nullptr; + } + return tex; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Clear +// +// Fills the specified region with a color. +// +//========================================================================== + +void OpenGLSWFrameBuffer::Clear(int left, int top, int right, int bottom, int palcolor, uint32 color) +{ + if (In2D < 2) + { + Super::Clear(left, top, right, bottom, palcolor, color); + return; + } + if (!InScene) + { + return; + } + if (palcolor >= 0 && color == 0) + { + color = GPalette.BaseColors[palcolor]; + } + else if (APART(color) < 255) + { + Dim(color, APART(color) / 255.f, left, top, right - left, bottom - top); + return; + } + AddColorOnlyQuad(left, top, right - left, bottom - top, color | 0xFF000000); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Dim +// +//========================================================================== + +void OpenGLSWFrameBuffer::Dim(PalEntry color, float amount, int x1, int y1, int w, int h) +{ + if (amount <= 0) + { + return; + } + if (In2D < 2) + { + Super::Dim(color, amount, x1, y1, w, h); + return; + } + if (!InScene) + { + return; + } + if (amount > 1) + { + amount = 1; + } + AddColorOnlyQuad(x1, y1, w, h, color | (int(amount * 255) << 24)); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: BeginLineBatch +// +//========================================================================== + +void OpenGLSWFrameBuffer::BeginLineBatch() +{ + if (In2D < 2 || !InScene || BatchType == BATCH_Lines) + { + return; + } + EndQuadBatch(); // Make sure all quads have been drawn first. + VertexData = VertexBuffer->Lock(); + VertexPos = 0; + BatchType = BATCH_Lines; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: EndLineBatch +// +//========================================================================== + +void OpenGLSWFrameBuffer::EndLineBatch() +{ + if (In2D < 2 || !InScene || BatchType != BATCH_Lines) + { + return; + } + VertexBuffer->Unlock(); + if (VertexPos > 0) + { + SetPixelShader(Shaders[SHADER_VertexColor]); + SetAlphaBlend(GL_FUNC_ADD, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + SetStreamSource(VertexBuffer); + DrawLineList(VertexPos / 2); + } + VertexPos = -1; + BatchType = BATCH_None; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawLine +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawLine(int x0, int y0, int x1, int y1, int palcolor, uint32 color) +{ + if (In2D < 2) + { + Super::DrawLine(x0, y0, x1, y1, palcolor, color); + return; + } + if (!InScene) + { + return; + } + if (BatchType != BATCH_Lines) + { + BeginLineBatch(); + } + if (VertexPos == NUM_VERTS) + { // Flush the buffer and refill it. + EndLineBatch(); + BeginLineBatch(); + } + // Add the endpoints to the vertex buffer. + VertexData[VertexPos].x = float(x0); + VertexData[VertexPos].y = float(y0); + VertexData[VertexPos].z = 0; + VertexData[VertexPos].rhw = 1; + VertexData[VertexPos].color0 = color; + VertexData[VertexPos].color1 = 0; + VertexData[VertexPos].tu = 0; + VertexData[VertexPos].tv = 0; + + VertexData[VertexPos + 1].x = float(x1); + VertexData[VertexPos + 1].y = float(y1); + VertexData[VertexPos + 1].z = 0; + VertexData[VertexPos + 1].rhw = 1; + VertexData[VertexPos + 1].color0 = color; + VertexData[VertexPos + 1].color1 = 0; + VertexData[VertexPos + 1].tu = 0; + VertexData[VertexPos + 1].tv = 0; + + VertexPos += 2; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawPixel +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawPixel(int x, int y, int palcolor, uint32 color) +{ + if (In2D < 2) + { + Super::DrawPixel(x, y, palcolor, color); + return; + } + if (!InScene) + { + return; + } + FBVERTEX pt = + { + float(x), float(y), 0, 1, color + }; + EndBatch(); // Draw out any batched operations. + SetPixelShader(Shaders[SHADER_VertexColor]); + SetAlphaBlend(GL_FUNC_ADD, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawPoints(1, &pt); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: DrawTextureV +// +// If not in 2D mode, just call the normal software version. +// If in 2D mode, then use Direct3D calls to perform the drawing. +// +//========================================================================== + +void OpenGLSWFrameBuffer::DrawTextureParms(FTexture *img, DrawParms &parms) +{ + if (In2D < 2) + { + Super::DrawTextureParms(img, parms); + return; + } + if (!InScene) + { + return; + } + + OpenGLTex *tex = static_cast(img->GetNative(false)); + + if (tex == nullptr) + { + assert(tex != nullptr); + return; + } + + CheckQuadBatch(); + + double xscale = parms.destwidth / parms.texwidth; + double yscale = parms.destheight / parms.texheight; + double x0 = parms.x - parms.left * xscale; + double y0 = parms.y - parms.top * yscale; + double x1 = x0 + parms.destwidth; + double y1 = y0 + parms.destheight; + float u0 = tex->Box->Left; + float v0 = tex->Box->Top; + float u1 = tex->Box->Right; + float v1 = tex->Box->Bottom; + double uscale = 1.f / tex->Box->Owner->Width; + bool scissoring = false; + FBVERTEX *vert; + + if (parms.flipX) + { + swapvalues(u0, u1); + } + if (parms.windowleft > 0 || parms.windowright < parms.texwidth) + { + double wi = MIN(parms.windowright, parms.texwidth); + x0 += parms.windowleft * xscale; + u0 = float(u0 + parms.windowleft * uscale); + x1 -= (parms.texwidth - wi) * xscale; + u1 = float(u1 - (parms.texwidth - wi) * uscale); + } + +#if 0 + float vscale = 1.f / tex->Box->Owner->Height / yscale; + if (y0 < parms.uclip) + { + v0 += (float(parms.uclip) - y0) * vscale; + y0 = float(parms.uclip); + } + if (y1 > parms.dclip) + { + v1 -= (y1 - float(parms.dclip)) * vscale; + y1 = float(parms.dclip); + } + if (x0 < parms.lclip) + { + u0 += float(parms.lclip - x0) * uscale / xscale * 2; + x0 = float(parms.lclip); + } + if (x1 > parms.rclip) + { + u1 -= (x1 - parms.rclip) * uscale / xscale * 2; + x1 = float(parms.rclip); + } +#else + // Use a scissor test because the math above introduces some jitter + // that is noticeable at low resolutions. Unfortunately, this means this + // quad has to be in a batch by itself. + if (y0 < parms.uclip || y1 > parms.dclip || x0 < parms.lclip || x1 > parms.rclip) + { + scissoring = true; + if (QuadBatchPos > 0) + { + EndQuadBatch(); + BeginQuadBatch(); + } + glEnable(GL_SCISSOR_TEST); + glScissor(parms.lclip, parms.uclip, parms.rclip - parms.lclip, parms.dclip - parms.uclip); + } +#endif + parms.bilinear = false; + + uint32_t color0, color1; + BufferedTris *quad = &QuadExtra[QuadBatchPos]; + + if (!SetStyle(tex, parms, color0, color1, *quad)) + { + goto done; + } + + quad->Texture = tex->Box->Owner->Tex; + if (parms.bilinear) + { + quad->Flags |= BQF_Bilinear; + } + quad->NumTris = 2; + quad->NumVerts = 4; + + vert = &VertexData[VertexPos]; + + // Fill the vertex buffer. + vert[0].x = float(x0); + vert[0].y = float(y0); + vert[0].z = 0; + vert[0].rhw = 1; + vert[0].color0 = color0; + vert[0].color1 = color1; + vert[0].tu = u0; + vert[0].tv = v0; + + vert[1].x = float(x1); + vert[1].y = float(y0); + vert[1].z = 0; + vert[1].rhw = 1; + vert[1].color0 = color0; + vert[1].color1 = color1; + vert[1].tu = u1; + vert[1].tv = v0; + + vert[2].x = float(x1); + vert[2].y = float(y1); + vert[2].z = 0; + vert[2].rhw = 1; + vert[2].color0 = color0; + vert[2].color1 = color1; + vert[2].tu = u1; + vert[2].tv = v1; + + vert[3].x = float(x0); + vert[3].y = float(y1); + vert[3].z = 0; + vert[3].rhw = 1; + vert[3].color0 = color0; + vert[3].color1 = color1; + vert[3].tu = u0; + vert[3].tv = v1; + + // Fill the vertex index buffer. + IndexData[IndexPos] = VertexPos; + IndexData[IndexPos + 1] = VertexPos + 1; + IndexData[IndexPos + 2] = VertexPos + 2; + IndexData[IndexPos + 3] = VertexPos; + IndexData[IndexPos + 4] = VertexPos + 2; + IndexData[IndexPos + 5] = VertexPos + 3; + + // Batch the quad. + QuadBatchPos++; + VertexPos += 4; + IndexPos += 6; +done: + if (scissoring) + { + EndQuadBatch(); + glDisable(GL_SCISSOR_TEST); + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: FlatFill +// +// Fills an area with a repeating copy of the texture. +// +//========================================================================== + +void OpenGLSWFrameBuffer::FlatFill(int left, int top, int right, int bottom, FTexture *src, bool local_origin) +{ + if (In2D < 2) + { + Super::FlatFill(left, top, right, bottom, src, local_origin); + return; + } + if (!InScene) + { + return; + } + OpenGLTex *tex = static_cast(src->GetNative(true)); + if (tex == nullptr) + { + return; + } + float x0 = float(left); + float y0 = float(top); + float x1 = float(right); + float y1 = float(bottom); + float itw = 1.f / float(src->GetWidth()); + float ith = 1.f / float(src->GetHeight()); + float xo = local_origin ? x0 : 0; + float yo = local_origin ? y0 : 0; + float u0 = (x0 - xo) * itw; + float v0 = (y0 - yo) * ith; + float u1 = (x1 - xo) * itw; + float v1 = (y1 - yo) * ith; + + CheckQuadBatch(); + + BufferedTris *quad = &QuadExtra[QuadBatchPos]; + FBVERTEX *vert = &VertexData[VertexPos]; + + quad->ClearSetup(); + if (tex->GetTexFormat() == GL_R8 && !tex->IsGray) + { + quad->Flags = BQF_WrapUV | BQF_GamePalette; // | BQF_DisableAlphaTest; + quad->ShaderNum = BQS_PalTex; + } + else + { + quad->Flags = BQF_WrapUV; // | BQF_DisableAlphaTest; + quad->ShaderNum = BQS_Plain; + } + quad->Palette = nullptr; + quad->Texture = tex->Box->Owner->Tex; + quad->NumVerts = 4; + quad->NumTris = 2; + + vert[0].x = x0; + vert[0].y = y0; + vert[0].z = 0; + vert[0].rhw = 1; + vert[0].color0 = 0; + vert[0].color1 = 0xFFFFFFFF; + vert[0].tu = u0; + vert[0].tv = v0; + + vert[1].x = x1; + vert[1].y = y0; + vert[1].z = 0; + vert[1].rhw = 1; + vert[1].color0 = 0; + vert[1].color1 = 0xFFFFFFFF; + vert[1].tu = u1; + vert[1].tv = v0; + + vert[2].x = x1; + vert[2].y = y1; + vert[2].z = 0; + vert[2].rhw = 1; + vert[2].color0 = 0; + vert[2].color1 = 0xFFFFFFFF; + vert[2].tu = u1; + vert[2].tv = v1; + + vert[3].x = x0; + vert[3].y = y1; + vert[3].z = 0; + vert[3].rhw = 1; + vert[3].color0 = 0; + vert[3].color1 = 0xFFFFFFFF; + vert[3].tu = u0; + vert[3].tv = v1; + + IndexData[IndexPos] = VertexPos; + IndexData[IndexPos + 1] = VertexPos + 1; + IndexData[IndexPos + 2] = VertexPos + 2; + IndexData[IndexPos + 3] = VertexPos; + IndexData[IndexPos + 4] = VertexPos + 2; + IndexData[IndexPos + 5] = VertexPos + 3; + + QuadBatchPos++; + VertexPos += 4; + IndexPos += 6; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: FillSimplePoly +// +// Here, "simple" means that a simple triangle fan can draw it. +// +//========================================================================== + +void OpenGLSWFrameBuffer::FillSimplePoly(FTexture *texture, FVector2 *points, int npoints, + double originx, double originy, double scalex, double scaley, + DAngle rotation, FDynamicColormap *colormap, int lightlevel, int bottomclip) +{ + // Use an equation similar to player sprites to determine shade + double fadelevel = clamp((LIGHT2SHADE(lightlevel) / 65536. - 12) / NUMCOLORMAPS, 0.0, 1.0); + + BufferedTris *quad; + FBVERTEX *verts; + OpenGLTex *tex; + float uscale, vscale; + int i, ipos; + uint32_t color0, color1; + float ox, oy; + float cosrot, sinrot; + bool dorotate = rotation != 0; + + if (npoints < 3) + { // This is no polygon. + return; + } + if (In2D < 2) + { + Super::FillSimplePoly(texture, points, npoints, originx, originy, scalex, scaley, rotation, colormap, lightlevel, bottomclip); + return; + } + if (!InScene) + { + return; + } + tex = static_cast(texture->GetNative(true)); + if (tex == nullptr) + { + return; + } + + cosrot = (float)cos(rotation.Radians()); + sinrot = (float)sin(rotation.Radians()); + + CheckQuadBatch(npoints - 2, npoints); + quad = &QuadExtra[QuadBatchPos]; + verts = &VertexData[VertexPos]; + + color0 = 0; + color1 = 0xFFFFFFFF; + + quad->ClearSetup(); + if (tex->GetTexFormat() == GL_R8 && !tex->IsGray) + { + quad->Flags = BQF_WrapUV | BQF_GamePalette | BQF_DisableAlphaTest; + quad->ShaderNum = BQS_PalTex; + if (colormap != nullptr) + { + if (colormap->Desaturate != 0) + { + quad->Flags |= BQF_Desaturated; + } + quad->ShaderNum = BQS_InGameColormap; + quad->Desat = colormap->Desaturate; + color0 = ColorARGB(255, colormap->Color.r, colormap->Color.g, colormap->Color.b); + color1 = ColorARGB(uint32_t((1 - fadelevel) * 255), + uint32_t(colormap->Fade.r * fadelevel), + uint32_t(colormap->Fade.g * fadelevel), + uint32_t(colormap->Fade.b * fadelevel)); + } + } + else + { + quad->Flags = BQF_WrapUV | BQF_DisableAlphaTest; + quad->ShaderNum = BQS_Plain; + } + quad->Palette = nullptr; + quad->Texture = tex->Box->Owner->Tex; + quad->NumVerts = npoints; + quad->NumTris = npoints - 2; + + uscale = float(1.f / (texture->GetScaledWidth() * scalex)); + vscale = float(1.f / (texture->GetScaledHeight() * scaley)); + ox = float(originx); + oy = float(originy); + + for (i = 0; i < npoints; ++i) + { + verts[i].x = points[i].X; + verts[i].y = points[i].Y; + verts[i].z = 0; + verts[i].rhw = 1; + verts[i].color0 = color0; + verts[i].color1 = color1; + float u = points[i].X - ox; + float v = points[i].Y - oy; + if (dorotate) + { + float t = u; + u = t * cosrot - v * sinrot; + v = v * cosrot + t * sinrot; + } + verts[i].tu = u * uscale; + verts[i].tv = v * vscale; + } + for (ipos = IndexPos, i = 2; i < npoints; ++i, ipos += 3) + { + IndexData[ipos] = VertexPos; + IndexData[ipos + 1] = VertexPos + i - 1; + IndexData[ipos + 2] = VertexPos + i; + } + + QuadBatchPos++; + VertexPos += npoints; + IndexPos = ipos; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: AddColorOnlyQuad +// +// Adds a single-color, untextured quad to the batch. +// +//========================================================================== + +void OpenGLSWFrameBuffer::AddColorOnlyQuad(int left, int top, int width, int height, uint32_t color) +{ + BufferedTris *quad; + FBVERTEX *verts; + + CheckQuadBatch(); + quad = &QuadExtra[QuadBatchPos]; + verts = &VertexData[VertexPos]; + + float x = float(left); + float y = float(top); + + quad->ClearSetup(); + quad->ShaderNum = BQS_ColorOnly; + if ((color & 0xFF000000) != 0xFF000000) + { + quad->BlendOp = GL_FUNC_ADD; + quad->SrcBlend = GL_SRC_ALPHA; + quad->DestBlend = GL_ONE_MINUS_SRC_ALPHA; + } + quad->Palette = nullptr; + quad->Texture = nullptr; + quad->NumVerts = 4; + quad->NumTris = 2; + + verts[0].x = x; + verts[0].y = y; + verts[0].z = 0; + verts[0].rhw = 1; + verts[0].color0 = color; + verts[0].color1 = 0; + verts[0].tu = 0; + verts[0].tv = 0; + + verts[1].x = x + width; + verts[1].y = y; + verts[1].z = 0; + verts[1].rhw = 1; + verts[1].color0 = color; + verts[1].color1 = 0; + verts[1].tu = 0; + verts[1].tv = 0; + + verts[2].x = x + width; + verts[2].y = y + height; + verts[2].z = 0; + verts[2].rhw = 1; + verts[2].color0 = color; + verts[2].color1 = 0; + verts[2].tu = 0; + verts[2].tv = 0; + + verts[3].x = x; + verts[3].y = y + height; + verts[3].z = 0; + verts[3].rhw = 1; + verts[3].color0 = color; + verts[3].color1 = 0; + verts[3].tu = 0; + verts[3].tv = 0; + + IndexData[IndexPos] = VertexPos; + IndexData[IndexPos + 1] = VertexPos + 1; + IndexData[IndexPos + 2] = VertexPos + 2; + IndexData[IndexPos + 3] = VertexPos; + IndexData[IndexPos + 4] = VertexPos + 2; + IndexData[IndexPos + 5] = VertexPos + 3; + + QuadBatchPos++; + VertexPos += 4; + IndexPos += 6; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: AddColorOnlyRect +// +// Like AddColorOnlyQuad, except it's hollow. +// +//========================================================================== + +void OpenGLSWFrameBuffer::AddColorOnlyRect(int left, int top, int width, int height, uint32_t color) +{ + AddColorOnlyQuad(left, top, width - 1, 1, color); // top + AddColorOnlyQuad(left + width - 1, top, 1, height - 1, color); // right + AddColorOnlyQuad(left + 1, top + height - 1, width - 1, 1, color); // bottom + AddColorOnlyQuad(left, top + 1, 1, height - 1, color); // left +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: CheckQuadBatch +// +// Make sure there's enough room in the batch for one more set of triangles. +// +//========================================================================== + +void OpenGLSWFrameBuffer::CheckQuadBatch(int numtris, int numverts) +{ + if (BatchType == BATCH_Lines) + { + EndLineBatch(); + } + else if (QuadBatchPos == MAX_QUAD_BATCH || + VertexPos + numverts > NUM_VERTS || + IndexPos + numtris * 3 > NUM_INDEXES) + { + EndQuadBatch(); + } + if (QuadBatchPos < 0) + { + BeginQuadBatch(); + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: BeginQuadBatch +// +// Locks the vertex buffer for quads and sets the cursor to 0. +// +//========================================================================== + +void OpenGLSWFrameBuffer::BeginQuadBatch() +{ + if (In2D < 2 || !InScene || QuadBatchPos >= 0) + { + return; + } + EndLineBatch(); // Make sure all lines have been drawn first. + VertexData = VertexBuffer->Lock(); + IndexData = IndexBuffer->Lock(); + VertexPos = 0; + IndexPos = 0; + QuadBatchPos = 0; + BatchType = BATCH_Quads; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: EndQuadBatch +// +// Draws all the quads that have been batched up. +// +//========================================================================== + +void OpenGLSWFrameBuffer::EndQuadBatch() +{ + if (In2D < 2 || !InScene || BatchType != BATCH_Quads) + { + return; + } + BatchType = BATCH_None; + VertexBuffer->Unlock(); + IndexBuffer->Unlock(); + if (QuadBatchPos == 0) + { + QuadBatchPos = -1; + VertexPos = -1; + IndexPos = -1; + return; + } + SetStreamSource(VertexBuffer); + SetIndices(IndexBuffer); + bool uv_wrapped = false; + bool uv_should_wrap; + int indexpos, vertpos; + + indexpos = vertpos = 0; + for (int i = 0; i < QuadBatchPos; ) + { + const BufferedTris *quad = &QuadExtra[i]; + int j; + + int startindex = indexpos; + int startvertex = vertpos; + + indexpos += quad->NumTris * 3; + vertpos += quad->NumVerts; + + // Quads with matching parameters should be done with a single + // DrawPrimitive call. + for (j = i + 1; j < QuadBatchPos; ++j) + { + const BufferedTris *q2 = &QuadExtra[j]; + if (quad->Texture != q2->Texture || + !quad->IsSameSetup(*q2) || + quad->Palette != q2->Palette) + { + break; + } + if (quad->ShaderNum == BQS_InGameColormap && (quad->Flags & BQF_Desaturated) && quad->Desat != q2->Desat) + { + break; + } + indexpos += q2->NumTris * 3; + vertpos += q2->NumVerts; + } + + // Set the palette (if one) + if ((quad->Flags & BQF_Paletted) == BQF_GamePalette) + { + SetPaletteTexture(PaletteTexture, 256, BorderColor); + } + else if ((quad->Flags & BQF_Paletted) == BQF_CustomPalette) + { + assert(quad->Palette != nullptr); + SetPaletteTexture(quad->Palette->Tex, quad->Palette->RoundedPaletteSize, quad->Palette->BorderColor); + } + + // Set the alpha blending + SetAlphaBlend(quad->BlendOp, quad->SrcBlend, quad->DestBlend); + + // Set the alpha test + EnableAlphaTest(!(quad->Flags & BQF_DisableAlphaTest)); + + // Set the pixel shader + if (quad->ShaderNum == BQS_PalTex) + { + SetPixelShader(Shaders[(quad->Flags & BQF_InvertSource) ? + SHADER_NormalColorPalInv : SHADER_NormalColorPal]); + } + else if (quad->ShaderNum == BQS_Plain) + { + SetPixelShader(Shaders[(quad->Flags & BQF_InvertSource) ? + SHADER_NormalColorInv : SHADER_NormalColor]); + } + else if (quad->ShaderNum == BQS_RedToAlpha) + { + SetPixelShader(Shaders[(quad->Flags & BQF_InvertSource) ? + SHADER_RedToAlphaInv : SHADER_RedToAlpha]); + } + else if (quad->ShaderNum == BQS_ColorOnly) + { + SetPixelShader(Shaders[SHADER_VertexColor]); + } + else if (quad->ShaderNum == BQS_SpecialColormap) + { + int select; + + select = !!(quad->Flags & BQF_Paletted); + SetPixelShader(Shaders[SHADER_SpecialColormap + select]); + } + else if (quad->ShaderNum == BQS_InGameColormap) + { + int select; + + select = !!(quad->Flags & BQF_Desaturated); + select |= !!(quad->Flags & BQF_InvertSource) << 1; + select |= !!(quad->Flags & BQF_Paletted) << 2; + if (quad->Flags & BQF_Desaturated) + { + SetConstant(PSCONST_Desaturation, quad->Desat / 255.f, (255 - quad->Desat) / 255.f, 0, 0); + } + SetPixelShader(Shaders[SHADER_InGameColormap + select]); + } + + // Set the texture clamp addressing mode + uv_should_wrap = !!(quad->Flags & BQF_WrapUV); + if (uv_wrapped != uv_should_wrap) + { + uint32_t mode = uv_should_wrap ? GL_REPEAT : GL_CLAMP_TO_EDGE; + uv_wrapped = uv_should_wrap; + SetSamplerWrapS(0, mode); + SetSamplerWrapT(0, mode); + } + + // Set the texture + if (quad->Texture != nullptr) + { + SetTexture(0, quad->Texture); + } + + // Draw the quad + DrawTriangleList( + startvertex, // MinIndex + vertpos - startvertex, // NumVertices + startindex, // StartIndex + (indexpos - startindex) / 3 // PrimitiveCount + /*4 * i, 4 * (j - i), 6 * i, 2 * (j - i)*/); + i = j; + } + if (uv_wrapped) + { + SetSamplerWrapS(0, GL_CLAMP_TO_EDGE); + SetSamplerWrapT(0, GL_CLAMP_TO_EDGE); + } + QuadBatchPos = -1; + VertexPos = -1; + IndexPos = -1; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: EndBatch +// +// Draws whichever type of primitive is currently being batched. +// +//========================================================================== + +void OpenGLSWFrameBuffer::EndBatch() +{ + if (BatchType == BATCH_Quads) + { + EndQuadBatch(); + } + else if (BatchType == BATCH_Lines) + { + EndLineBatch(); + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: SetStyle +// +// Patterned after R_SetPatchStyle. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::SetStyle(OpenGLTex *tex, DrawParms &parms, uint32_t &color0, uint32_t &color1, BufferedTris &quad) +{ + int fmt = tex->GetTexFormat(); + FRenderStyle style = parms.style; + float alpha; + bool stencilling; + + if (style.Flags & STYLEF_TransSoulsAlpha) + { + alpha = transsouls; + } + else if (style.Flags & STYLEF_Alpha1) + { + alpha = 1; + } + else + { + alpha = clamp(parms.Alpha, 0.f, 1.f); + } + + style.CheckFuzz(); + if (style.BlendOp == STYLEOP_Shadow) + { + style = LegacyRenderStyles[STYLE_TranslucentStencil]; + alpha = 0.3f; + parms.fillcolor = 0; + } + + // FIXME: Fuzz effect is not written + if (style.BlendOp == STYLEOP_FuzzOrAdd || style.BlendOp == STYLEOP_Fuzz) + { + style.BlendOp = STYLEOP_Add; + } + else if (style.BlendOp == STYLEOP_FuzzOrSub) + { + style.BlendOp = STYLEOP_Sub; + } + else if (style.BlendOp == STYLEOP_FuzzOrRevSub) + { + style.BlendOp = STYLEOP_RevSub; + } + + stencilling = false; + quad.Palette = nullptr; + quad.Flags = 0; + quad.Desat = 0; + + switch (style.BlendOp) + { + default: + case STYLEOP_Add: quad.BlendOp = GL_FUNC_ADD; break; + case STYLEOP_Sub: quad.BlendOp = GL_FUNC_SUBTRACT; break; + case STYLEOP_RevSub: quad.BlendOp = GL_FUNC_REVERSE_SUBTRACT; break; + case STYLEOP_None: return false; + } + quad.SrcBlend = GetStyleAlpha(style.SrcAlpha); + quad.DestBlend = GetStyleAlpha(style.DestAlpha); + + if (style.Flags & STYLEF_InvertOverlay) + { + // Only the overlay color is inverted, not the overlay alpha. + parms.colorOverlay = ColorARGB(APART(parms.colorOverlay), + 255 - RPART(parms.colorOverlay), 255 - GPART(parms.colorOverlay), + 255 - BPART(parms.colorOverlay)); + } + + SetColorOverlay(parms.colorOverlay, alpha, color0, color1); + + if (style.Flags & STYLEF_ColorIsFixed) + { + if (style.Flags & STYLEF_InvertSource) + { // Since the source color is a constant, we can invert it now + // without spending time doing it in the shader. + parms.fillcolor = ColorXRGB(255 - RPART(parms.fillcolor), + 255 - GPART(parms.fillcolor), 255 - BPART(parms.fillcolor)); + } + // Set up the color mod to replace the color from the image data. + color0 = (color0 & ColorRGBA(0, 0, 0, 255)) | (parms.fillcolor & ColorRGBA(255, 255, 255, 0)); + color1 &= ColorRGBA(0, 0, 0, 255); + + if (style.Flags & STYLEF_RedIsAlpha) + { + // Note that if the source texture is paletted, the palette is ignored. + quad.Flags = 0; + quad.ShaderNum = BQS_RedToAlpha; + } + else if (fmt == GL_R8) + { + quad.Flags = BQF_GamePalette; + quad.ShaderNum = BQS_PalTex; + } + else + { + quad.Flags = 0; + quad.ShaderNum = BQS_Plain; + } + } + else + { + if (style.Flags & STYLEF_RedIsAlpha) + { + quad.Flags = 0; + quad.ShaderNum = BQS_RedToAlpha; + } + else if (fmt == GL_R8) + { + if (parms.remap != nullptr) + { + quad.Flags = BQF_CustomPalette; + quad.Palette = reinterpret_cast(parms.remap->GetNative()); + quad.ShaderNum = BQS_PalTex; + } + else if (tex->IsGray) + { + quad.Flags = 0; + quad.ShaderNum = BQS_Plain; + } + else + { + quad.Flags = BQF_GamePalette; + quad.ShaderNum = BQS_PalTex; + } + } + else + { + quad.Flags = 0; + quad.ShaderNum = BQS_Plain; + } + if (style.Flags & STYLEF_InvertSource) + { + quad.Flags |= BQF_InvertSource; + } + + if (parms.specialcolormap != nullptr) + { // Emulate an invulnerability or similar colormap. + float *start, *end; + start = parms.specialcolormap->ColorizeStart; + end = parms.specialcolormap->ColorizeEnd; + if (quad.Flags & BQF_InvertSource) + { + quad.Flags &= ~BQF_InvertSource; + swapvalues(start, end); + } + quad.ShaderNum = BQS_SpecialColormap; + color0 = ColorRGBA(uint32_t(start[0] / 2 * 255), uint32_t(start[1] / 2 * 255), uint32_t(start[2] / 2 * 255), color0 >> 24); + color1 = ColorRGBA(uint32_t(end[0] / 2 * 255), uint32_t(end[1] / 2 * 255), uint32_t(end[2] / 2 * 255), color1 >> 24); + } + else if (parms.colormapstyle != nullptr) + { // Emulate the fading from an in-game colormap (colorized, faded, and desaturated) + if (parms.colormapstyle->Desaturate != 0) + { + quad.Flags |= BQF_Desaturated; + } + quad.ShaderNum = BQS_InGameColormap; + quad.Desat = parms.colormapstyle->Desaturate; + color0 = ColorARGB(color1 >> 24, + parms.colormapstyle->Color.r, + parms.colormapstyle->Color.g, + parms.colormapstyle->Color.b); + double fadelevel = parms.colormapstyle->FadeLevel; + color1 = ColorARGB(uint32_t((1 - fadelevel) * 255), + uint32_t(parms.colormapstyle->Fade.r * fadelevel), + uint32_t(parms.colormapstyle->Fade.g * fadelevel), + uint32_t(parms.colormapstyle->Fade.b * fadelevel)); + } + } + + // For unmasked images, force the alpha from the image data to be ignored. + if (!parms.masked && quad.ShaderNum != BQS_InGameColormap) + { + color0 = (color0 & ColorRGBA(255, 255, 255, 0)) | ColorValue(0, 0, 0, alpha); + color1 &= ColorRGBA(255, 255, 255, 0); + + // If our alpha is one and we are doing normal adding, then we can turn the blend off completely. + if (quad.BlendOp == GL_FUNC_ADD && + ((alpha == 1 && quad.SrcBlend == GL_SRC_ALPHA) || quad.SrcBlend == GL_ONE) && + ((alpha == 1 && quad.DestBlend == GL_ONE_MINUS_SRC_ALPHA) || quad.DestBlend == GL_ZERO)) + { + quad.BlendOp = 0; + } + quad.Flags |= BQF_DisableAlphaTest; + } + return true; +} + +int OpenGLSWFrameBuffer::GetStyleAlpha(int type) +{ + switch (type) + { + case STYLEALPHA_Zero: return GL_ZERO; + case STYLEALPHA_One: return GL_ONE; + case STYLEALPHA_Src: return GL_SRC_ALPHA; + case STYLEALPHA_InvSrc: return GL_ONE_MINUS_SRC_ALPHA; + default: return GL_ZERO; + } +} + + +void OpenGLSWFrameBuffer::SetColorOverlay(uint32_t color, float alpha, uint32_t &color0, uint32_t &color1) +{ + if (APART(color) != 0) + { + int a = APART(color) * 256 / 255; + color0 = ColorRGBA( + (RPART(color) * a) >> 8, + (GPART(color) * a) >> 8, + (BPART(color) * a) >> 8, + 0); + a = 256 - a; + color1 = ColorRGBA(a, a, a, int(alpha * 255)); + } + else + { + color0 = 0; + color1 = ColorValue(1, 1, 1, alpha); + } +} + +void OpenGLSWFrameBuffer::EnableAlphaTest(bool enabled) +{ + if (enabled != AlphaTestEnabled) + { + AlphaTestEnabled = enabled; + //glEnable(GL_ALPHA_TEST); // To do: move to shader as this is only in the compatibility profile + } +} + +void OpenGLSWFrameBuffer::SetAlphaBlend(int op, int srcblend, int destblend) +{ + if (op == 0) + { // Disable alpha blend + if (AlphaBlendEnabled) + { + AlphaBlendEnabled = false; + glDisable(GL_BLEND); + } + } + else + { // Enable alpha blend + assert(srcblend != 0); + assert(destblend != 0); + + if (!AlphaBlendEnabled) + { + AlphaBlendEnabled = true; + glEnable(GL_BLEND); + } + if (AlphaBlendOp != op) + { + AlphaBlendOp = op; + glBlendEquation(op); + } + if (AlphaSrcBlend != srcblend || AlphaDestBlend != destblend) + { + AlphaSrcBlend = srcblend; + AlphaDestBlend = destblend; + glBlendFunc(srcblend, destblend); + } + } +} + +void OpenGLSWFrameBuffer::SetConstant(int cnum, float r, float g, float b, float a) +{ + if (Constant[cnum][0] != r || + Constant[cnum][1] != g || + Constant[cnum][2] != b || + Constant[cnum][3] != a) + { + Constant[cnum][0] = r; + Constant[cnum][1] = g; + Constant[cnum][2] = b; + Constant[cnum][3] = a; + SetPixelShaderConstantF(cnum, Constant[cnum], 1); + } +} + +void OpenGLSWFrameBuffer::SetPixelShader(HWPixelShader *shader) +{ + if (CurPixelShader != shader) + { + CurPixelShader = shader; + SetHWPixelShader(shader); + } +} + +void OpenGLSWFrameBuffer::SetTexture(int tnum, HWTexture *texture) +{ + assert(unsigned(tnum) < countof(Texture)); + if (texture) + { + if (Texture[tnum] != texture || SamplerWrapS[tnum] != texture->WrapS || SamplerWrapT[tnum] != texture->WrapT) + { + Texture[tnum] = texture; + glActiveTexture(GL_TEXTURE0 + tnum); + glBindTexture(GL_TEXTURE_2D, texture->Texture); + if (Texture[tnum]->WrapS != SamplerWrapS[tnum]) + { + Texture[tnum]->WrapS = SamplerWrapS[tnum]; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, SamplerWrapS[tnum]); + } + if (Texture[tnum]->WrapT != SamplerWrapT[tnum]) + { + Texture[tnum]->WrapT = SamplerWrapT[tnum]; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, SamplerWrapT[tnum]); + } + } + } + else if (Texture[tnum] != texture) + { + Texture[tnum] = texture; + glActiveTexture(GL_TEXTURE0 + tnum); + glBindTexture(GL_TEXTURE_2D, 0); + } +} + +void OpenGLSWFrameBuffer::SetSamplerWrapS(int tnum, int mode) +{ + assert(unsigned(tnum) < countof(Texture)); + if (Texture[tnum] && SamplerWrapS[tnum] != mode) + { + SamplerWrapS[tnum] = mode; + Texture[tnum]->WrapS = mode; + glActiveTexture(GL_TEXTURE0 + tnum); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, SamplerWrapS[tnum]); + } +} + +void OpenGLSWFrameBuffer::SetSamplerWrapT(int tnum, int mode) +{ + assert(unsigned(tnum) < countof(Texture)); + if (Texture[tnum] && SamplerWrapT[tnum] != mode) + { + SamplerWrapT[tnum] = mode; + Texture[tnum]->WrapT = mode; + glActiveTexture(GL_TEXTURE0 + tnum); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, SamplerWrapT[tnum]); + } +} + +void OpenGLSWFrameBuffer::SetPaletteTexture(HWTexture *texture, int count, uint32_t border_color) +{ + // The pixel shader receives color indexes in the range [0.0,1.0]. + // The palette texture is also addressed in the range [0.0,1.0], + // HOWEVER the coordinate 1.0 is the right edge of the texture and + // not actually the texture itself. We need to scale and shift + // the palette indexes so they lie exactly in the center of each + // texel. For a normal palette with 256 entries, that means the + // range we use should be [0.5,255.5], adjusted so the coordinate + // is still within [0.0,1.0]. + // + // The constant register c2 is used to hold the multiplier in the + // x part and the adder in the y part. + float fcount = 1 / float(count); + SetConstant(PSCONST_PaletteMod, 255 * fcount, 0.5f * fcount, 0, 0); + SetTexture(1, texture); +} diff --git a/src/gl/system/gl_swframebuffer.h b/src/gl/system/gl_swframebuffer.h new file mode 100644 index 000000000..a4ba4e426 --- /dev/null +++ b/src/gl/system/gl_swframebuffer.h @@ -0,0 +1,501 @@ +#ifndef __GL_SWFRAMEBUFFER +#define __GL_SWFRAMEBUFFER + +#ifdef _WIN32 +#include "win32iface.h" +#include "win32gliface.h" +#endif + +#include "SkylineBinPack.h" + +#include + +class FGLDebug; + +#ifdef _WIN32 +class OpenGLSWFrameBuffer : public Win32GLFrameBuffer +{ + typedef Win32GLFrameBuffer Super; + DECLARE_CLASS(OpenGLSWFrameBuffer, Win32GLFrameBuffer) +#else +#include "sdlglvideo.h" +class OpenGLSWFrameBuffer : public SDLGLFB +{ +// typedef SDLGLFB Super; //[C]commented, DECLARE_CLASS defines this in linux + DECLARE_CLASS(OpenGLSWFrameBuffer, SDLGLFB) +#endif + + +public: + + explicit OpenGLSWFrameBuffer() {} + OpenGLSWFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen, bool bgra); + ~OpenGLSWFrameBuffer(); + + + bool IsValid() override; + bool Lock(bool buffered) override; + void Unlock() override; + void Update() override; + PalEntry *GetPalette() override; + void GetFlashedPalette(PalEntry palette[256]) override; + void UpdatePalette() override; + bool SetGamma(float gamma) override; + bool SetFlash(PalEntry rgb, int amount) override; + void GetFlash(PalEntry &rgb, int &amount) override; + int GetPageCount() override; + void SetVSync(bool vsync) override; + void NewRefreshRate() override; + void GetScreenshotBuffer(const uint8_t *&buffer, int &pitch, ESSType &color_type) override; + void ReleaseScreenshotBuffer() override; + void SetBlendingRect(int x1, int y1, int x2, int y2) override; + bool Begin2D(bool copy3d) override; + void DrawBlendingRect() override; + FNativeTexture *CreateTexture(FTexture *gametex, bool wrapping) override; + FNativePalette *CreatePalette(FRemapTable *remap) override; + void DrawTextureParms(FTexture *img, DrawParms &parms) override; + void Clear(int left, int top, int right, int bottom, int palcolor, uint32 color) override; + void Dim(PalEntry color, float amount, int x1, int y1, int w, int h) override; + void FlatFill(int left, int top, int right, int bottom, FTexture *src, bool local_origin) override; + void DrawLine(int x0, int y0, int x1, int y1, int palColor, uint32 realcolor) override; + void DrawPixel(int x, int y, int palcolor, uint32 rgbcolor) override; + void FillSimplePoly(FTexture *tex, FVector2 *points, int npoints, double originx, double originy, double scalex, double scaley, DAngle rotation, FDynamicColormap *colormap, int lightlevel, int bottomclip) override; + bool WipeStartScreen(int type) override; + void WipeEndScreen() override; + bool WipeDo(int ticks) override; + void WipeCleanup() override; + +#ifdef WIN32 + void PaletteChanged() override { } + int QueryNewPalette() override { return 0; } + void Blank() override { } + bool PaintToWindow() override; + bool Is8BitMode() override { return false; } + int GetTrueHeight() override { return TrueHeight; } +#endif + +private: + struct FBVERTEX + { + float x, y, z, rhw; + uint32_t color0, color1; + float tu, tv; + }; + + struct BURNVERTEX + { + float x, y, z, rhw; + float tu0, tv0; + float tu1, tv1; + }; + + enum + { + PSCONST_Desaturation, + PSCONST_PaletteMod, + PSCONST_Weights, + PSCONST_Gamma, + PSCONST_ScreenSize, + NumPSCONST + }; + + struct GammaRamp + { + uint16_t red[256], green[256], blue[256]; + }; + + struct LTRBRect + { + int left, top, right, bottom; + }; + + class HWTexture + { + public: + HWTexture() { Buffers[0] = 0; Buffers[1] = 0; } + ~HWTexture(); + + int Texture = 0; + int Buffers[2]; + int CurrentBuffer = 0; + int WrapS = 0; + int WrapT = 0; + int Format = 0; + }; + + class HWFrameBuffer + { + public: + ~HWFrameBuffer(); + + int Framebuffer = 0; + HWTexture *Texture = nullptr; + }; + + + class HWVertexBuffer + { + public: + ~HWVertexBuffer(); + + FBVERTEX *Lock(); + void Unlock(); + + int VertexArray = 0; + int Buffer = 0; + int Size = 0; + }; + + class HWIndexBuffer + { + public: + ~HWIndexBuffer(); + + uint16_t *Lock(); + void Unlock(); + + int Buffer = 0; + int Size = 0; + + private: + int LockedOldBinding = 0; + }; + + class HWPixelShader + { + public: + ~HWPixelShader(); + + int Program = 0; + int VertexShader = 0; + int FragmentShader = 0; + + int ConstantLocations[NumPSCONST]; + int ImageLocation = -1; + int PaletteLocation = -1; + int NewScreenLocation = -1; + int BurnLocation = -1; + }; + + bool CreateFrameBuffer(const FString &name, int width, int height, HWFrameBuffer **outFramebuffer); + bool CreatePixelShader(FString vertexsrc, FString fragmentsrc, const FString &defines, HWPixelShader **outShader); + bool CreateVertexBuffer(int size, HWVertexBuffer **outVertexBuffer); + bool CreateIndexBuffer(int size, HWIndexBuffer **outIndexBuffer); + bool CreateTexture(const FString &name, int width, int height, int levels, int format, HWTexture **outTexture); + void SetGammaRamp(const GammaRamp *ramp); + void SetPixelShaderConstantF(int uniformIndex, const float *data, int vec4fcount); + void SetHWPixelShader(HWPixelShader *shader); + void SetStreamSource(HWVertexBuffer *vertexBuffer); + void SetIndices(HWIndexBuffer *indexBuffer); + void DrawTriangleFans(int count, const FBVERTEX *vertices); + void DrawTriangleFans(int count, const BURNVERTEX *vertices); + void DrawPoints(int count, const FBVERTEX *vertices); + void DrawLineList(int count); + void DrawTriangleList(int minIndex, int numVertices, int startIndex, int primitiveCount); + void Present(); + + void BindFBBuffer(); + void *MappedMemBuffer = nullptr; + bool UseMappedMemBuffer = true; + + static uint32_t ColorARGB(uint32_t a, uint32_t r, uint32_t g, uint32_t b) { return ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b) & 0xff); } + static uint32_t ColorRGBA(uint32_t r, uint32_t g, uint32_t b, uint32_t a) { return ColorARGB(a, r, g, b); } + static uint32_t ColorXRGB(uint32_t r, uint32_t g, uint32_t b) { return ColorARGB(0xff, r, g, b); } + static uint32_t ColorValue(float r, float g, float b, float a) { return ColorRGBA((uint32_t)(r * 255.0f), (uint32_t)(g * 255.0f), (uint32_t)(b * 255.0f), (uint32_t)(a * 255.0f)); } + + static void *MapBuffer(int target, int size); + + // The number of points for the vertex buffer. + enum { NUM_VERTS = 10240 }; + + // The number of indices for the index buffer. + enum { NUM_INDEXES = ((NUM_VERTS * 6) / 4) }; + + // The number of quads we can batch together. + enum { MAX_QUAD_BATCH = (NUM_INDEXES / 6) }; + + // The default size for a texture atlas. + enum { DEF_ATLAS_WIDTH = 512 }; + enum { DEF_ATLAS_HEIGHT = 512 }; + + // TYPES ------------------------------------------------------------------- + + struct Atlas; + + struct PackedTexture + { + Atlas *Owner; + + PackedTexture **Prev, *Next; + + // Pixels this image covers + LTRBRect Area; + + // Texture coordinates for this image + float Left, Top, Right, Bottom; + + // Texture has extra space on the border? + bool Padded; + }; + + struct Atlas + { + Atlas(OpenGLSWFrameBuffer *fb, int width, int height, int format); + ~Atlas(); + + PackedTexture *AllocateImage(const Rect &rect, bool padded); + void FreeBox(PackedTexture *box); + + SkylineBinPack Packer; + Atlas *Next; + HWTexture *Tex; + int Format; + PackedTexture *UsedList; // Boxes that contain images + int Width, Height; + bool OneUse; + }; + + class OpenGLTex : public FNativeTexture + { + public: + OpenGLTex(FTexture *tex, OpenGLSWFrameBuffer *fb, bool wrapping); + ~OpenGLTex(); + + FTexture *GameTex; + PackedTexture *Box; + + OpenGLTex **Prev; + OpenGLTex *Next; + + bool IsGray; + + bool Create(OpenGLSWFrameBuffer *fb, bool wrapping); + bool Update(); + bool CheckWrapping(bool wrapping); + int GetTexFormat(); + FTextureFormat ToTexFmt(int fmt); + }; + + class OpenGLPal : public FNativePalette + { + public: + OpenGLPal(FRemapTable *remap, OpenGLSWFrameBuffer *fb); + ~OpenGLPal(); + + OpenGLPal **Prev; + OpenGLPal *Next; + + HWTexture *Tex; + uint32_t BorderColor; + bool DoColorSkip; + + bool Update(); + + FRemapTable *Remap; + int RoundedPaletteSize; + }; + + // Flags for a buffered quad + enum + { + BQF_GamePalette = 1, + BQF_CustomPalette = 7, + BQF_Paletted = 7, + BQF_Bilinear = 8, + BQF_WrapUV = 16, + BQF_InvertSource = 32, + BQF_DisableAlphaTest = 64, + BQF_Desaturated = 128, + }; + + // Shaders for a buffered quad + enum + { + BQS_PalTex, + BQS_Plain, + BQS_RedToAlpha, + BQS_ColorOnly, + BQS_SpecialColormap, + BQS_InGameColormap, + }; + + struct BufferedTris + { + uint8_t Flags; + uint8_t ShaderNum; + int BlendOp; + int SrcBlend; + int DestBlend; + + uint8_t Desat; + OpenGLPal *Palette; + HWTexture *Texture; + uint16_t NumVerts; // Number of _unique_ vertices used by this set. + uint16_t NumTris; // Number of triangles used by this set. + + void ClearSetup() + { + Flags = 0; + ShaderNum = 0; + BlendOp = 0; + SrcBlend = 0; + DestBlend = 0; + } + + bool IsSameSetup(const BufferedTris &other) const + { + return Flags == other.Flags && ShaderNum == other.ShaderNum && BlendOp == other.BlendOp && SrcBlend == other.SrcBlend && DestBlend == other.DestBlend; + } + }; + + enum + { + SHADER_NormalColor, + SHADER_NormalColorPal, + SHADER_NormalColorInv, + SHADER_NormalColorPalInv, + + SHADER_RedToAlpha, + SHADER_RedToAlphaInv, + + SHADER_VertexColor, + + SHADER_SpecialColormap, + SHADER_SpecialColormapPal, + + SHADER_InGameColormap, + SHADER_InGameColormapDesat, + SHADER_InGameColormapInv, + SHADER_InGameColormapInvDesat, + SHADER_InGameColormapPal, + SHADER_InGameColormapPalDesat, + SHADER_InGameColormapPalInv, + SHADER_InGameColormapPalInvDesat, + + SHADER_BurnWipe, + SHADER_GammaCorrection, + + NUM_SHADERS + }; + static const char *const ShaderDefines[NUM_SHADERS]; + + void Flip(); + void SetInitialState(); + bool CreateResources(); + void ReleaseResources(); + bool LoadShaders(); + bool CreateFBTexture(); + bool CreatePaletteTexture(); + bool CreateVertexes(); + void UploadPalette(); + void CalcFullscreenCoords(FBVERTEX verts[4], bool viewarea_only, uint32_t color0, uint32_t color1) const; + bool Reset(); + HWTexture *CopyCurrentScreen(); + void ReleaseDefaultPoolItems(); + void KillNativePals(); + void KillNativeTexs(); + PackedTexture *AllocPackedTexture(int width, int height, bool wrapping, int format); + void DrawPackedTextures(int packnum); + void DrawLetterbox(int x, int y, int width, int height); + void Draw3DPart(bool copy3d); + bool SetStyle(OpenGLTex *tex, DrawParms &parms, uint32_t &color0, uint32_t &color1, BufferedTris &quad); + static int GetStyleAlpha(int type); + static void SetColorOverlay(uint32_t color, float alpha, uint32_t &color0, uint32_t &color1); + void AddColorOnlyQuad(int left, int top, int width, int height, uint32_t color); + void AddColorOnlyRect(int left, int top, int width, int height, uint32_t color); + void CheckQuadBatch(int numtris = 2, int numverts = 4); + void BeginQuadBatch(); + void EndQuadBatch(); + void BeginLineBatch(); + void EndLineBatch(); + void EndBatch(); + + // State + void EnableAlphaTest(bool enabled); + void SetAlphaBlend(int op, int srcblend = 0, int destblend = 0); + void SetConstant(int cnum, float r, float g, float b, float a); + void SetPixelShader(HWPixelShader *shader); + void SetTexture(int tnum, HWTexture *texture); + void SetSamplerWrapS(int tnum, int mode); + void SetSamplerWrapT(int tnum, int mode); + void SetPaletteTexture(HWTexture *texture, int count, uint32_t border_color); + + template static void SafeRelease(T &x) { if (x != nullptr) { delete x; x = nullptr; } } + + std::shared_ptr Debug; + + std::unique_ptr StreamVertexBuffer, StreamVertexBufferBurn; + float ShaderConstants[NumPSCONST * 4]; + HWPixelShader *CurrentShader = nullptr; + + HWFrameBuffer *OutputFB = nullptr; + + bool AlphaTestEnabled = false; + bool AlphaBlendEnabled = false; + int AlphaBlendOp = 0; + int AlphaSrcBlend = 0; + int AlphaDestBlend = 0; + float Constant[3][4]; + uint32_t CurBorderColor; + HWPixelShader *CurPixelShader; + HWTexture *Texture[5]; + int SamplerWrapS[5], SamplerWrapT[5]; + + PalEntry SourcePalette[256]; + uint32_t BorderColor; + uint32_t FlashColor0, FlashColor1; + PalEntry FlashColor; + int FlashAmount; + int TrueHeight; + int PixelDoubling; + float Gamma; + bool UpdatePending; + bool NeedPalUpdate; + bool NeedGammaUpdate; + bool VSync; + LTRBRect BlendingRect; + int In2D; + bool InScene; + bool GatheringWipeScreen; + bool AALines; + uint8_t BlockNum; + OpenGLPal *Palettes = nullptr; + OpenGLTex *Textures = nullptr; + Atlas *Atlases = nullptr; + + HWTexture *FBTexture = nullptr; + HWTexture *PaletteTexture = nullptr; + HWTexture *ScreenshotTexture = nullptr; + + HWVertexBuffer *VertexBuffer = nullptr; + FBVERTEX *VertexData = nullptr; + HWIndexBuffer *IndexBuffer = nullptr; + uint16_t *IndexData = nullptr; + BufferedTris *QuadExtra = nullptr; + int VertexPos; + int IndexPos; + int QuadBatchPos; + enum { BATCH_None, BATCH_Quads, BATCH_Lines } BatchType; + + HWPixelShader *Shaders[NUM_SHADERS]; + + HWTexture *InitialWipeScreen = nullptr, *FinalWipeScreen = nullptr; + + class Wiper + { + public: + virtual ~Wiper(); + virtual bool Run(int ticks, OpenGLSWFrameBuffer *fb) = 0; + + void DrawScreen(OpenGLSWFrameBuffer *fb, HWTexture *tex, int blendop = 0, uint32_t color0 = 0, uint32_t color1 = 0xFFFFFFF); + }; + + class Wiper_Melt; friend class Wiper_Melt; + class Wiper_Burn; friend class Wiper_Burn; + class Wiper_Crossfade; friend class Wiper_Crossfade; + + Wiper *ScreenWipe; +}; + + +#endif //__GL_SWFRAMEBUFFER diff --git a/src/gl/system/gl_swwipe.cpp b/src/gl/system/gl_swwipe.cpp new file mode 100644 index 000000000..44c2203b4 --- /dev/null +++ b/src/gl/system/gl_swwipe.cpp @@ -0,0 +1,588 @@ +/* +** gl_swwipe.cpp +** Implements the different screen wipes using OpenGL calls. +** +**--------------------------------------------------------------------------- +** Copyright 1998-2008 Randy Heit +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +// HEADER FILES ------------------------------------------------------------ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "m_swap.h" +#include "v_video.h" +#include "doomstat.h" +#include "m_png.h" +#include "m_crc32.h" +#include "vectors.h" +#include "v_palette.h" +#include "templates.h" + +#include "c_dispatch.h" +#include "templates.h" +#include "i_system.h" +#include "i_video.h" +#include "i_input.h" +#include "v_pfx.h" +#include "stats.h" +#include "doomerrors.h" +#include "r_main.h" +#include "r_data/r_translate.h" +#include "f_wipe.h" +#include "sbar.h" +#include "w_wad.h" +#include "r_data/colormaps.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_swframebuffer.h" +#include "gl/data/gl_data.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_templates.h" +#include "gl/gl_functions.h" +#include "gl_debug.h" +#include "m_random.h" + +class OpenGLSWFrameBuffer::Wiper_Crossfade : public OpenGLSWFrameBuffer::Wiper +{ +public: + Wiper_Crossfade(); + bool Run(int ticks, OpenGLSWFrameBuffer *fb); + +private: + int Clock; +}; + +class OpenGLSWFrameBuffer::Wiper_Melt : public OpenGLSWFrameBuffer::Wiper +{ +public: + Wiper_Melt(); + bool Run(int ticks, OpenGLSWFrameBuffer *fb); + +private: + // Match the strip sizes that oldschool Doom used. + static const int WIDTH = 160, HEIGHT = 200; + int y[WIDTH]; +}; + +class OpenGLSWFrameBuffer::Wiper_Burn : public OpenGLSWFrameBuffer::Wiper +{ +public: + Wiper_Burn(OpenGLSWFrameBuffer *fb); + ~Wiper_Burn(); + bool Run(int ticks, OpenGLSWFrameBuffer *fb); + +private: + static const int WIDTH = 64, HEIGHT = 64; + uint8_t BurnArray[WIDTH * (HEIGHT + 5)]; + HWTexture *BurnTexture; + int Density; + int BurnTime; +}; + +//========================================================================== +// +// OpenGLSWFrameBuffer :: WipeStartScreen +// +// Called before the current screen has started rendering. This needs to +// save what was drawn the previous frame so that it can be animated into +// what gets drawn this frame. +// +// In fullscreen mode, we use GetFrontBufferData() to grab the data that +// is visible on screen right now. +// +// In windowed mode, we can't do that because we'll get the whole desktop. +// Instead, we can conveniently use the TempRenderTexture, which is normally +// used for gamma-correcting copying the image to the back buffer. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::WipeStartScreen(int type) +{ + if (!Accel2D) + { + return Super::WipeStartScreen(type); + } + + switch (type) + { + case wipe_Melt: + ScreenWipe = new Wiper_Melt; + break; + + case wipe_Burn: + ScreenWipe = new Wiper_Burn(this); + break; + + case wipe_Fade: + ScreenWipe = new Wiper_Crossfade; + break; + + default: + return false; + } + + InitialWipeScreen = CopyCurrentScreen(); + + // Make even fullscreen model render to the TempRenderTexture, so + // we can have a copy of the new screen readily available. + GatheringWipeScreen = true; + return true; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: WipeEndScreen +// +// The screen we want to animate to has just been drawn. This function is +// called in place of Update(), so it has not been Presented yet. +// +//========================================================================== + +void OpenGLSWFrameBuffer::WipeEndScreen() +{ + if (!Accel2D) + { + Super::WipeEndScreen(); + return; + } + + // Don't do anything if there is no starting point. + if (InitialWipeScreen == NULL) + { + return; + } + + // If the whole screen was drawn without 2D accel, get it in to + // video memory now. + if (!In2D) + { + Begin2D(true); + } + + EndBatch(); // Make sure all batched primitives have been drawn. + + FinalWipeScreen = CopyCurrentScreen(); + + // At this point, InitialWipeScreen holds the screen we are wiping from. + // FinalWipeScreen holds the screen we are wiping to, which may be the + // same texture as TempRenderTexture. +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: WipeDo +// +// Perform the actual wipe animation. The number of tics since the last +// time this function was called is passed in. Returns true when the wipe +// is over. The first time this function has been called, the screen is +// still locked from before and EndScene() still has not been called. +// Successive times need to call BeginScene(). +// +//========================================================================== + +bool OpenGLSWFrameBuffer::WipeDo(int ticks) +{ + if (!Accel2D) + { + return Super::WipeDo(ticks); + } + + // Sanity checks. + if (InitialWipeScreen == NULL || FinalWipeScreen == NULL) + { + return true; + } + if (GatheringWipeScreen) + { // This is the first time we've been called for this wipe. + GatheringWipeScreen = false; + } + else + { // This is the second or later time we've been called for this wipe. + InScene = true; + } + + In2D = 3; + + EnableAlphaTest(false); + bool done = ScreenWipe->Run(ticks, this); + return done; +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: WipeCleanup +// +// Release any resources that were specifically created for the wipe. +// +//========================================================================== + +void OpenGLSWFrameBuffer::WipeCleanup() +{ + if (ScreenWipe != NULL) + { + delete ScreenWipe; + ScreenWipe = NULL; + } + SafeRelease( InitialWipeScreen ); + SafeRelease( FinalWipeScreen ); + GatheringWipeScreen = false; + if (!Accel2D) + { + Super::WipeCleanup(); + return; + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Wiper::~Wiper() +{ +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper :: DrawScreen +// +// Draw either the initial or target screen completely to the screen. +// +//========================================================================== + +void OpenGLSWFrameBuffer::Wiper::DrawScreen(OpenGLSWFrameBuffer *fb, HWTexture *tex, + int blendop, uint32_t color0, uint32_t color1) +{ + FBVERTEX verts[4]; + + fb->CalcFullscreenCoords(verts, false, color0, color1); + fb->SetTexture(0, tex); + fb->SetAlphaBlend(blendop, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + fb->SetPixelShader(fb->Shaders[SHADER_NormalColor]); + fb->DrawTriangleFans(2, verts); +} + +// WIPE: CROSSFADE --------------------------------------------------------- + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Crossfade Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Wiper_Crossfade::Wiper_Crossfade() +: Clock(0) +{ +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Crossfade :: Run +// +// Fades the old screen into the new one over 32 ticks. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::Wiper_Crossfade::Run(int ticks, OpenGLSWFrameBuffer *fb) +{ + Clock += ticks; + + // Put the initial screen back to the buffer. + DrawScreen(fb, fb->InitialWipeScreen); + + // Draw the new screen on top of it. + DrawScreen(fb, fb->FinalWipeScreen, GL_FUNC_ADD, ColorValue(0,0,0,Clock / 32.f), ColorRGBA(255,255,255,0)); + + return Clock >= 32; +} + +// WIPE: MELT -------------------------------------------------------------- + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Melt Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Wiper_Melt::Wiper_Melt() +{ + int i, r; + + // setup initial column positions + // (y<0 => not ready to scroll yet) + y[0] = -(M_Random() & 15); + for (i = 1; i < WIDTH; ++i) + { + r = (M_Random()%3) - 1; + y[i] = clamp(y[i-1] + r, -15, 0); + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Melt :: Run +// +// Fades the old screen into the new one over 32 ticks. +// +//========================================================================== + +bool OpenGLSWFrameBuffer::Wiper_Melt::Run(int ticks, OpenGLSWFrameBuffer *fb) +{ + // Draw the new screen on the bottom. + DrawScreen(fb, fb->FinalWipeScreen); + + int i, dy; + int fbwidth = fb->Width; + int fbheight = fb->Height; + bool done = true; + + // Copy the old screen in vertical strips on top of the new one. + while (ticks--) + { + done = true; + for (i = 0; i < WIDTH; i++) + { + if (y[i] < 0) + { + y[i]++; + done = false; + } + else if (y[i] < HEIGHT) + { + dy = (y[i] < 16) ? y[i]+1 : 8; + y[i] = MIN(y[i] + dy, HEIGHT); + done = false; + } + if (ticks == 0) + { // Only draw for the final tick. + LTRBRect rect; + struct Point { int x, y; } dpt; + + dpt.x = i * fbwidth / WIDTH; + dpt.y = MAX(0, y[i] * fbheight / HEIGHT); + rect.left = dpt.x; + rect.top = 0; + rect.right = (i + 1) * fbwidth / WIDTH; + rect.bottom = fbheight - dpt.y; + if (rect.bottom > rect.top) + { + fb->CheckQuadBatch(); + + BufferedTris *quad = &fb->QuadExtra[fb->QuadBatchPos]; + FBVERTEX *vert = &fb->VertexData[fb->VertexPos]; + WORD *index = &fb->IndexData[fb->IndexPos]; + + quad->ClearSetup(); + quad->Flags = BQF_DisableAlphaTest; + quad->ShaderNum = BQS_Plain; + quad->Palette = NULL; + quad->Texture = fb->InitialWipeScreen; + quad->NumVerts = 4; + quad->NumTris = 2; + + // Fill the vertex buffer. + float u0 = rect.left / float(fb->Width); + float v0 = 0; + float u1 = rect.right / float(fb->Width); + float v1 = (rect.bottom - rect.top) / float(fb->Height); + + float x0 = float(rect.left); + float x1 = float(rect.right); + float y0 = float(dpt.y); + float y1 = float(fbheight); + + vert[0].x = x0; + vert[0].y = y0; + vert[0].z = 0; + vert[0].rhw = 1; + vert[0].color0 = 0; + vert[0].color1 = 0xFFFFFFF; + vert[0].tu = u0; + vert[0].tv = v0; + + vert[1].x = x1; + vert[1].y = y0; + vert[1].z = 0; + vert[1].rhw = 1; + vert[1].color0 = 0; + vert[1].color1 = 0xFFFFFFF; + vert[1].tu = u1; + vert[1].tv = v0; + + vert[2].x = x1; + vert[2].y = y1; + vert[2].z = 0; + vert[2].rhw = 1; + vert[2].color0 = 0; + vert[2].color1 = 0xFFFFFFF; + vert[2].tu = u1; + vert[2].tv = v1; + + vert[3].x = x0; + vert[3].y = y1; + vert[3].z = 0; + vert[3].rhw = 1; + vert[3].color0 = 0; + vert[3].color1 = 0xFFFFFFF; + vert[3].tu = u0; + vert[3].tv = v1; + + // Fill the vertex index buffer. + index[0] = fb->VertexPos; + index[1] = fb->VertexPos + 1; + index[2] = fb->VertexPos + 2; + index[3] = fb->VertexPos; + index[4] = fb->VertexPos + 2; + index[5] = fb->VertexPos + 3; + + // Batch the quad. + fb->QuadBatchPos++; + fb->VertexPos += 4; + fb->IndexPos += 6; + } + } + } + } + fb->EndQuadBatch(); + return done; +} + +// WIPE: BURN -------------------------------------------------------------- + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Burn Constructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Wiper_Burn::Wiper_Burn(OpenGLSWFrameBuffer *fb) +{ + Density = 4; + BurnTime = 0; + memset(BurnArray, 0, sizeof(BurnArray)); + if (fb->Shaders[SHADER_BurnWipe] == NULL || !fb->CreateTexture("BurnWipe", WIDTH, HEIGHT, 1, GL_R8, &BurnTexture)) + { + BurnTexture = NULL; + } +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Burn Destructor +// +//========================================================================== + +OpenGLSWFrameBuffer::Wiper_Burn::~Wiper_Burn() +{ + SafeRelease( BurnTexture ); +} + +//========================================================================== +// +// OpenGLSWFrameBuffer :: Wiper_Burn :: Run +// +//========================================================================== + +bool OpenGLSWFrameBuffer::Wiper_Burn::Run(int ticks, OpenGLSWFrameBuffer *fb) +{ + bool done; + + BurnTime += ticks; + ticks *= 2; + + // Make the fire burn + done = false; + while (!done && ticks--) + { + Density = wipe_CalcBurn(BurnArray, WIDTH, HEIGHT, Density); + done = (Density < 0); + } + + // Update the burn texture with the new burn data + + if (BurnTexture->Buffers[0] == 0) + { + glGenBuffers(2, (GLuint*)BurnTexture->Buffers); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, BurnTexture->Buffers[0]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, WIDTH * HEIGHT, nullptr, GL_STREAM_DRAW); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, BurnTexture->Buffers[1]); + glBufferData(GL_PIXEL_UNPACK_BUFFER, WIDTH * HEIGHT, nullptr, GL_STREAM_DRAW); + } + else + { + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, BurnTexture->Buffers[BurnTexture->CurrentBuffer]); + BurnTexture->CurrentBuffer = (BurnTexture->CurrentBuffer + 1) & 1; + } + + uint8_t *dest = (uint8_t*)glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, WIDTH * HEIGHT, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + if (dest) + { + memcpy(dest, BurnArray, WIDTH * HEIGHT); + glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); + + GLint oldBinding = 0; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldBinding); + glBindTexture(GL_TEXTURE_2D, BurnTexture->Texture); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, WIDTH, HEIGHT, GL_RED, GL_UNSIGNED_BYTE, 0); + glBindTexture(GL_TEXTURE_2D, oldBinding); + + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + } + + // Put the initial screen back to the buffer. + DrawScreen(fb, fb->InitialWipeScreen); + + // Burn the new screen on top of it. + float right = float(fb->Width); + float bot = float(fb->Height); + + BURNVERTEX verts[4] = + { + { 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0, 0 }, + { right, 0.f, 0.f, 1.f, 1.f, 0.f, 1, 0 }, + { right, bot, 0.f, 1.f, 1.f, 1.f, 1, 1 }, + { 0.f, bot, 0.f, 1.f, 0.f, 1.f, 0, 1 } + }; + + fb->SetTexture(0, fb->FinalWipeScreen); + fb->SetTexture(1, BurnTexture); + fb->SetAlphaBlend(GL_FUNC_ADD, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + fb->SetPixelShader(fb->Shaders[SHADER_BurnWipe]); + glActiveTexture(GL_TEXTURE1); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + fb->DrawTriangleFans(2, verts); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glActiveTexture(GL_TEXTURE0); + + // The fire may not always stabilize, so the wipe is forced to end + // after an arbitrary maximum time. + return done || (BurnTime > 40); +} diff --git a/src/gl/system/gl_system.h b/src/gl/system/gl_system.h new file mode 100644 index 000000000..e5abe2ec5 --- /dev/null +++ b/src/gl/system/gl_system.h @@ -0,0 +1,117 @@ +#ifndef __GL_PCH_H +#define __GL_PCH_H +#ifdef _WIN32 +//#define __RPCNDR_H__ // this header causes problems! +//#define __wtypes_h__ +#define WIN32_LEAN_AND_MEAN +#define _WIN32_WINDOWS 0x410 +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 // Support the mouse wheel and session notification. +#define _WIN32_IE 0x0500 +#endif +#define DIRECTINPUT_VERSION 0x800 +#define DIRECTDRAW_VERSION 0x0300 + +#define DWORD WINDOWS_DWORD // I don't want to depend on this throughout the GL code! + +#ifdef _MSC_VER +#pragma warning(disable : 4995) // MIPS +#endif + +#include +#include +#include +#ifndef __WINE__ +#include +#endif +#include +//#include +//#include +//#include +//#include +#endif + +#undef DWORD +#ifndef CALLBACK +#define CALLBACK +#endif +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#if !defined(__APPLE__) && !defined(__FreeBSD__) +#include +#endif +#include + +#ifdef _MSC_VER +#define F_OK 0 /* Check for file existence */ +#define W_OK 2 /* Check for write permission */ +#define R_OK 4 /* Check for read permission */ +#include +#else +#include +#endif +#include +#include +#include + +//GL headers +#include "gl_load.h" + +#if defined(__APPLE__) + #include +#endif + +#ifdef _WIN32 +#define DWORD WINDOWS_DWORD // I don't want to depend on this throughout the GL code! +//#include "gl/api/wglext.h" +#ifndef __WINE__ +#undef DWORD +#endif +#else +typedef unsigned char byte; +typedef float FLOAT; +template +inline T max( T a, T b) { return (((a)>(b)) ? (a) : (b)); } +#define _access(a,b) access(a,b) +#endif + + +#ifdef LoadMenu +#undef LoadMenu +#endif +#ifdef DrawText +#undef DrawText +#endif +#ifdef GetCharWidth +#undef GetCharWidth +#endif + +#undef S_NORMAL +#undef OPAQUE + + +#ifdef _MSC_VER +#pragma warning(disable : 4244) // MIPS +#pragma warning(disable : 4136) // X86 +#pragma warning(disable : 4051) // ALPHA + +#pragma warning(disable : 4018) // signed/unsigned mismatch +#pragma warning(disable : 4305) // truncate from double to float +#endif + +#ifdef WIN32 +#undef WIN32 +#endif +#endif //__GL_PCH_H diff --git a/src/gl/system/gl_threads.cpp b/src/gl/system/gl_threads.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/src/gl/system/gl_wipe.cpp b/src/gl/system/gl_wipe.cpp new file mode 100644 index 000000000..642f20fb1 --- /dev/null +++ b/src/gl/system/gl_wipe.cpp @@ -0,0 +1,562 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2008-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** Screen wipe stuff +** +*/ + +#include "gl/system/gl_system.h" +#include "files.h" +#include "f_wipe.h" +#include "m_random.h" +#include "w_wad.h" +#include "v_palette.h" +#include "templates.h" +#include "vectors.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/renderer/gl_renderstate.h" +#include "gl/renderer/gl_renderbuffers.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_cvars.h" +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_material.h" +#include "gl/textures/gl_samplers.h" +#include "gl/utility/gl_templates.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_2ddrawer.h" + +#ifndef _WIN32 +struct POINT { + SDWORD x; + SDWORD y; +}; +struct RECT { + SDWORD left; + SDWORD top; + SDWORD right; + SDWORD bottom; +}; +#endif + +//=========================================================================== +// +// Screen wipes +// +//=========================================================================== + +// TYPES ------------------------------------------------------------------- + +class OpenGLFrameBuffer::Wiper_Crossfade : public OpenGLFrameBuffer::Wiper +{ +public: + Wiper_Crossfade(); + bool Run(int ticks, OpenGLFrameBuffer *fb); + +private: + int Clock; +}; + +class OpenGLFrameBuffer::Wiper_Melt : public OpenGLFrameBuffer::Wiper +{ +public: + Wiper_Melt(); + int MakeVBO(int ticks, OpenGLFrameBuffer *fb, bool &done); + bool Run(int ticks, OpenGLFrameBuffer *fb); + +private: + static const int WIDTH = 320, HEIGHT = 200; + int y[WIDTH]; +}; + +class OpenGLFrameBuffer::Wiper_Burn : public OpenGLFrameBuffer::Wiper +{ +public: + Wiper_Burn(); + ~Wiper_Burn(); + bool Run(int ticks, OpenGLFrameBuffer *fb); + +private: + static const int WIDTH = 64, HEIGHT = 64; + BYTE BurnArray[WIDTH * (HEIGHT + 5)]; + FHardwareTexture *BurnTexture; + int Density; + int BurnTime; +}; + +//========================================================================== +// +// OpenGLFrameBuffer :: WipeStartScreen +// +// Called before the current screen has started rendering. This needs to +// save what was drawn the previous frame so that it can be animated into +// what gets drawn this frame. +// +//========================================================================== + +bool OpenGLFrameBuffer::WipeStartScreen(int type) +{ + switch (type) + { + case wipe_Burn: + ScreenWipe = new Wiper_Burn; + break; + + case wipe_Fade: + ScreenWipe = new Wiper_Crossfade; + break; + + case wipe_Melt: + ScreenWipe = new Wiper_Melt; + break; + + default: + return false; + } + + const auto &viewport = GLRenderer->mScreenViewport; + wipestartscreen = new FHardwareTexture(viewport.width, viewport.height, true); + wipestartscreen->CreateTexture(NULL, viewport.width, viewport.height, 0, false, 0, "WipeStartScreen"); + GLRenderer->mSamplerManager->Bind(0, CLAMP_NOFILTER, -1); + GLRenderer->mSamplerManager->Bind(1, CLAMP_NONE, -1); + glFinish(); + wipestartscreen->Bind(0, false, false); + + if (FGLRenderBuffers::IsEnabled()) + { + GLRenderer->mBuffers->BindCurrentFB(); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewport.left, viewport.top, viewport.width, viewport.height); + } + else + { + GLint readbuffer = 0; + glGetIntegerv(GL_READ_BUFFER, &readbuffer); + glReadBuffer(GL_FRONT); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewport.left, viewport.top, viewport.width, viewport.height); + glReadBuffer(readbuffer); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + return true; +} + +//========================================================================== +// +// OpenGLFrameBuffer :: WipeEndScreen +// +// The screen we want to animate to has just been drawn. +// +//========================================================================== + +void OpenGLFrameBuffer::WipeEndScreen() +{ + GLRenderer->m2DDrawer->Draw(); + GLRenderer->m2DDrawer->Clear(); + + const auto &viewport = GLRenderer->mScreenViewport; + wipeendscreen = new FHardwareTexture(viewport.width, viewport.height, true); + wipeendscreen->CreateTexture(NULL, viewport.width, viewport.height, 0, false, 0, "WipeEndScreen"); + GLRenderer->mSamplerManager->Bind(0, CLAMP_NOFILTER, -1); + glFinish(); + wipeendscreen->Bind(0, false, false); + + if (FGLRenderBuffers::IsEnabled()) + GLRenderer->mBuffers->BindCurrentFB(); + + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewport.left, viewport.top, viewport.width, viewport.height); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + Unlock(); +} + +//========================================================================== +// +// OpenGLFrameBuffer :: WipeDo +// +// Perform the actual wipe animation. The number of tics since the last +// time this function was called is passed in. Returns true when the wipe +// is over. The first time this function has been called, the screen is +// still locked from before and EndScene() still has not been called. +// Successive times need to call BeginScene(). +// +//========================================================================== + +bool OpenGLFrameBuffer::WipeDo(int ticks) +{ + bool done = true; + // Sanity checks. + if (wipestartscreen != nullptr && wipeendscreen != nullptr) + { + Lock(true); + + gl_RenderState.EnableTexture(true); + gl_RenderState.EnableFog(false); + glDisable(GL_DEPTH_TEST); + glDepthMask(false); + + if (FGLRenderBuffers::IsEnabled()) + { + GLRenderer->mBuffers->BindCurrentFB(); + const auto &bounds = GLRenderer->mScreenViewport; + glViewport(bounds.left, bounds.top, bounds.width, bounds.height); + } + + done = ScreenWipe->Run(ticks, this); + glDepthMask(true); + } + gl_RenderState.SetVertexBuffer(GLRenderer->mVBO); + return done; +} + +//========================================================================== +// +// OpenGLFrameBuffer :: WipeCleanup +// +// Release any resources that were specifically created for the wipe. +// +//========================================================================== + +void OpenGLFrameBuffer::WipeCleanup() +{ + if (ScreenWipe != NULL) + { + delete ScreenWipe; + ScreenWipe = NULL; + } + if (wipestartscreen != NULL) + { + delete wipestartscreen; + wipestartscreen = NULL; + } + if (wipeendscreen != NULL) + { + delete wipeendscreen; + wipeendscreen = NULL; + } + FMaterial::ClearLastTexture(); +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper Constructor +// +//========================================================================== +OpenGLFrameBuffer::Wiper::Wiper() +{ + mVertexBuf = new FSimpleVertexBuffer; +} + +OpenGLFrameBuffer::Wiper::~Wiper() +{ + delete mVertexBuf; +} + +void OpenGLFrameBuffer::Wiper::MakeVBO(OpenGLFrameBuffer *fb) +{ + FSimpleVertex make[4]; + FSimpleVertex *ptr = make; + + float ur = fb->GetWidth() / FHardwareTexture::GetTexDimension(fb->GetWidth()); + float vb = fb->GetHeight() / FHardwareTexture::GetTexDimension(fb->GetHeight()); + + ptr->Set(0, 0, 0, 0, vb); + ptr++; + ptr->Set(0, fb->Height, 0, 0, 0); + ptr++; + ptr->Set(fb->Width, 0, 0, ur, vb); + ptr++; + ptr->Set(fb->Width, fb->Height, 0, ur, 0); + mVertexBuf->set(make, 4); +} + +// WIPE: CROSSFADE --------------------------------------------------------- + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Crossfade Constructor +// +//========================================================================== + +OpenGLFrameBuffer::Wiper_Crossfade::Wiper_Crossfade() +: Clock(0) +{ +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Crossfade :: Run +// +// Fades the old screen into the new one over 32 ticks. +// +//========================================================================== + +bool OpenGLFrameBuffer::Wiper_Crossfade::Run(int ticks, OpenGLFrameBuffer *fb) +{ + Clock += ticks; + + MakeVBO(fb); + + gl_RenderState.SetTextureMode(TM_OPAQUE); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.ResetColor(); + gl_RenderState.Apply(); + fb->wipestartscreen->Bind(0, 0, false); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + float a = clamp(Clock / 32.f, 0.f, 1.f); + gl_RenderState.SetColorAlpha(0xffffff, a); + gl_RenderState.Apply(); + fb->wipeendscreen->Bind(0, 0, false); + mVertexBuf->EnableColorArray(false); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.5f); + gl_RenderState.SetTextureMode(TM_MODULATE); + + return Clock >= 32; +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Melt Constructor +// +//========================================================================== + +OpenGLFrameBuffer::Wiper_Melt::Wiper_Melt() +{ + int i, r; + + // setup initial column positions + // (y<0 => not ready to scroll yet) + y[0] = -(M_Random() & 15); + for (i = 1; i < WIDTH; ++i) + { + r = (M_Random()%3) - 1; + y[i] = clamp(y[i-1] + r, -15, 0); + } +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Melt :: Run +// +// Fades the old screen into the new one over 32 ticks. +// +//========================================================================== + +int OpenGLFrameBuffer::Wiper_Melt::MakeVBO(int ticks, OpenGLFrameBuffer *fb, bool &done) +{ + FSimpleVertex *make = new FSimpleVertex[321*4]; + FSimpleVertex *ptr = make; + int dy; + + float ur = fb->GetWidth() / FHardwareTexture::GetTexDimension(fb->GetWidth()); + float vb = fb->GetHeight() / FHardwareTexture::GetTexDimension(fb->GetHeight()); + + ptr->Set(0, 0, 0, 0, vb); + ptr++; + ptr->Set(0, fb->Height, 0, 0, 0); + ptr++; + ptr->Set(fb->Width, 0, 0, ur, vb); + ptr++; + ptr->Set(fb->Width, fb->Height, 0, ur, 0); + ptr++; + + // Copy the old screen in vertical strips on top of the new one. + while (ticks--) + { + done = true; + for (int i = 0; i < WIDTH; i++) + { + if (y[i] < 0) + { + y[i]++; + done = false; + } + else if (y[i] < HEIGHT) + { + dy = (y[i] < 16) ? y[i] + 1 : 8; + y[i] = MIN(y[i] + dy, HEIGHT); + done = false; + } + if (ticks == 0) + { + // Only draw for the final tick. + // No need for optimization. Wipes won't ever be drawn with anything else. + RECT rect; + POINT dpt; + + dpt.x = i * fb->Width / WIDTH; + dpt.y = MAX(0, y[i] * fb->Height / HEIGHT); + rect.left = dpt.x; + rect.top = 0; + rect.right = (i + 1) * fb->Width / WIDTH; + rect.bottom = fb->Height - dpt.y; + if (rect.bottom > rect.top) + { + float tw = (float)FHardwareTexture::GetTexDimension(fb->Width); + float th = (float)FHardwareTexture::GetTexDimension(fb->Height); + rect.bottom = fb->Height - rect.bottom; + rect.top = fb->Height - rect.top; + + ptr->Set(rect.left, rect.bottom, 0, rect.left / tw, rect.top / th); + ptr++; + ptr->Set(rect.left, rect.top, 0, rect.left / tw, rect.bottom / th); + ptr++; + ptr->Set(rect.right, rect.bottom, 0, rect.right / tw, rect.top / th); + ptr++; + ptr->Set(rect.right, rect.top, 0, rect.right / tw, rect.bottom / th); + ptr++; + } + } + } + } + int numverts = int(ptr - make); + mVertexBuf->set(make, numverts); + delete[] make; + return numverts; +} + +bool OpenGLFrameBuffer::Wiper_Melt::Run(int ticks, OpenGLFrameBuffer *fb) +{ + bool done = false; + int maxvert = MakeVBO(ticks, fb, done); + + // Draw the new screen on the bottom. + gl_RenderState.SetTextureMode(TM_OPAQUE); + gl_RenderState.ResetColor(); + gl_RenderState.Apply(); + fb->wipeendscreen->Bind(0, 0, false); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + fb->wipestartscreen->Bind(0, 0, false); + gl_RenderState.SetTextureMode(TM_MODULATE); + for (int i = 4; i < maxvert; i += 4) + { + glDrawArrays(GL_TRIANGLE_STRIP, i, 4); + } + return done; +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Burn Constructor +// +//========================================================================== + +OpenGLFrameBuffer::Wiper_Burn::Wiper_Burn() +{ + Density = 4; + BurnTime = 0; + memset(BurnArray, 0, sizeof(BurnArray)); + BurnTexture = NULL; +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Burn Destructor +// +//========================================================================== + +OpenGLFrameBuffer::Wiper_Burn::~Wiper_Burn() +{ + if (BurnTexture != NULL) + { + delete BurnTexture; + BurnTexture = NULL; + } +} + +//========================================================================== +// +// OpenGLFrameBuffer :: Wiper_Burn :: Run +// +//========================================================================== + +bool OpenGLFrameBuffer::Wiper_Burn::Run(int ticks, OpenGLFrameBuffer *fb) +{ + bool done; + + MakeVBO(fb); + + BurnTime += ticks; + ticks *= 2; + + // Make the fire burn + done = false; + while (!done && ticks--) + { + Density = wipe_CalcBurn(BurnArray, WIDTH, HEIGHT, Density); + done = (Density < 0); + } + + if (BurnTexture != NULL) delete BurnTexture; + BurnTexture = new FHardwareTexture(WIDTH, HEIGHT, true); + + // Update the burn texture with the new burn data + BYTE rgb_buffer[WIDTH*HEIGHT*4]; + + const BYTE *src = BurnArray; + DWORD *dest = (DWORD *)rgb_buffer; + for (int y = HEIGHT; y != 0; --y) + { + for (int x = WIDTH; x != 0; --x) + { + BYTE s = clamp((*src++)*2, 0, 255); + *dest++ = MAKEARGB(s,255,255,255); + } + } + + float ur = fb->GetWidth() / FHardwareTexture::GetTexDimension(fb->GetWidth()); + float vb = fb->GetHeight() / FHardwareTexture::GetTexDimension(fb->GetHeight()); + + + // Put the initial screen back to the buffer. + gl_RenderState.SetTextureMode(TM_OPAQUE); + gl_RenderState.AlphaFunc(GL_GEQUAL, 0.f); + gl_RenderState.ResetColor(); + gl_RenderState.Apply(); + fb->wipestartscreen->Bind(0, 0, false); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + gl_RenderState.SetTextureMode(TM_MODULATE); + gl_RenderState.SetEffect(EFF_BURN); + gl_RenderState.ResetColor(); + gl_RenderState.Apply(); + + // Burn the new screen on top of it. + fb->wipeendscreen->Bind(0, 0, false); + + BurnTexture->CreateTexture(rgb_buffer, WIDTH, HEIGHT, 1, true, 0, "BurnTexture"); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + gl_RenderState.SetEffect(EFF_NONE); + + // The fire may not always stabilize, so the wipe is forced to end + // after an arbitrary maximum time. + return done || (BurnTime > 40); +} diff --git a/src/gl/textures/gl_bitmap.cpp b/src/gl/textures/gl_bitmap.cpp new file mode 100644 index 000000000..f5156c7a5 --- /dev/null +++ b/src/gl/textures/gl_bitmap.cpp @@ -0,0 +1,150 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_bitmap.cpp +** Bitmap class for texture composition +** +*/ + + +#include "v_palette.h" +#include "templates.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_bitmap.h" +#include "gl/system/gl_interface.h" + +//=========================================================================== +// +// multi-format pixel copy with colormap application +// requires one of the previously defined conversion classes to work +// +//=========================================================================== +template +void iCopyColors(unsigned char * pout, const unsigned char * pin, int count, int step, BYTE tr, BYTE tg, BYTE tb) +{ + int i; + unsigned char a; + + for(i=0;i, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors, + iCopyColors +}; + +//=========================================================================== +// +// True Color texture copy function +// This excludes all the cases that force downconversion to the +// base palette because they wouldn't be used anyway. +// +//=========================================================================== +void FGLBitmap::CopyPixelDataRGB(int originx, int originy, + const BYTE * patch, int srcwidth, int srcheight, int step_x, int step_y, + int rotate, int ct, FCopyInfo *inf, int r, int g, int b) +{ + if (ClipCopyPixelRect(&ClipRect, originx, originy, patch, srcwidth, srcheight, step_x, step_y, rotate)) + { + BYTE *buffer = GetPixels() + 4*originx + Pitch*originy; + for (int y=0;y 0) + { + PalEntry *ptrans = GLTranslationPalette::GetPalette(translation); + if (ptrans && !alphatrans) + { + for (i = 0; i < 256; i++) + { + penew[i] = (ptrans[i] & 0xffffff) | (palette[i] & 0xff000000); + } + } + else if (ptrans) + { + memcpy(penew, ptrans, 256 * sizeof(PalEntry)); + } + } + else + { + memcpy(penew, palette, 256*sizeof(PalEntry)); + } + + // convert the image according to the translated palette. + for (y=0;y +#else +#include +#endif + +#include "w_wad.h" +#include "m_png.h" +#include "sbar.h" +#include "gi.h" +#include "cmdlib.h" +#include "sc_man.h" +#include "doomstat.h" +#include "d_main.h" +#include "zstring.h" + +#ifndef _WIN32 +#define _access(a,b) access(a,b) +#endif + +static int Doom2Wad = -1; + +// quick'n dirty hack. Should be enough here... +static void SetDoom2Wad() +{ + if (Doom2Wad == -1) + { + FString iwad = Wads.GetWadFullName(1); + iwad.ToLower(); + if (iwad.IndexOf("plutonia") >= 0) Doom2Wad = 1; + else if (iwad.IndexOf("tnt") >= 0) Doom2Wad = 2; + else Doom2Wad = 0; + } +} +//========================================================================== +// +// Checks for the presence of a hires texture replacement in a Doomsday style PK3 +// +//========================================================================== +int CheckDDPK3(FTexture *tex) +{ + static const char * doom1texpath[]= { + "data/jdoom/textures/doom/%s.%s", "data/jdoom/textures/doom-ult/%s.%s", "data/jdoom/textures/doom1/%s.%s", "data/jdoom/textures/%s.%s", NULL }; + + static const char * doom2texpath[]= { + "data/jdoom/textures/doom2/%s.%s", "data/jdoom/textures/%s.%s", NULL }; + + static const char * pluttexpath[]= { + "data/jdoom/textures/doom2-plut/%s.%s", "data/jdoom/textures/plutonia/%s.%s", "data/jdoom/textures/%s.%s", NULL }; + + static const char * tnttexpath[]= { + "data/jdoom/textures/doom2-tnt/%s.%s", "data/jdoom/textures/tnt/%s.%s", "data/jdoom/textures/%s.%s", NULL }; + + static const char * heretictexpath[]= { + "data/jheretic/textures/%s.%s", NULL }; + + static const char * hexentexpath[]= { + "data/jhexen/textures/%s.%s", NULL }; + + static const char * strifetexpath[]= { + "data/jstrife/textures/%s.%s", NULL }; + + static const char * chextexpath[]= { + "data/jchex/textures/%s.%s", NULL }; + + static const char * doomflatpath[]= { + "data/jdoom/flats/%s.%s", NULL }; + + static const char * hereticflatpath[]= { + "data/jheretic/flats/%s.%s", NULL }; + + static const char * hexenflatpath[]= { + "data/jhexen/flats/%s.%s", NULL }; + + static const char * strifeflatpath[]= { + "data/jstrife/flats/%s.%s", NULL }; + + static const char * chexflatpath[]= { + "data/jchex/flats/%s.%s", NULL }; + + + FString checkName; + const char ** checklist; + BYTE useType=tex->UseType; + + if (useType==FTexture::TEX_SkinSprite || useType==FTexture::TEX_Decal || useType==FTexture::TEX_FontChar) + { + return -3; + } + + bool ispatch = (useType==FTexture::TEX_MiscPatch || useType==FTexture::TEX_Sprite) ; + + // for patches this doesn't work yet + if (ispatch) return -3; + + if (!gameinfo.ConfigName.CompareNoCase("Doom")) + { + if (!(gameinfo.flags & GI_MAPxx)) + { + checklist = useType==FTexture::TEX_Flat? doomflatpath : doom1texpath; + } + else + { + SetDoom2Wad(); + if (Doom2Wad == 1) + checklist = useType==FTexture::TEX_Flat? doomflatpath : pluttexpath; + else if (Doom2Wad == 2) + checklist = useType==FTexture::TEX_Flat? doomflatpath : tnttexpath; + else + checklist = useType==FTexture::TEX_Flat? doomflatpath : doom2texpath; + } + } + else if (!gameinfo.ConfigName.CompareNoCase("Heretic")) + { + checklist = useType==FTexture::TEX_Flat? hereticflatpath : heretictexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Hexen")) + { + checklist = useType==FTexture::TEX_Flat? hexenflatpath : hexentexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Strife")) + { + checklist = useType==FTexture::TEX_Flat? strifeflatpath : strifetexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Chex")) + { + checklist = useType==FTexture::TEX_Flat? chexflatpath : chextexpath; + } + else + return -3; + + while (*checklist) + { + static const char * extensions[] = { "PNG", "JPG", "TGA", "PCX", NULL }; + + for (const char ** extp=extensions; *extp; extp++) + { + checkName.Format(*checklist, tex->Name.GetChars(), *extp); + int lumpnum = Wads.CheckNumForFullName(checkName); + if (lumpnum >= 0) return lumpnum; + } + checklist++; + } + return -3; +} + + +//========================================================================== +// +// Checks for the presence of a hires texture replacement +// +//========================================================================== +int CheckExternalFile(FTexture *tex, bool & hascolorkey) +{ + static const char * doom1texpath[]= { + "%stextures/doom/doom1/%s.%s", "%stextures/doom/doom1/%s-ck.%s", + "%stextures/doom/%s.%s", "%stextures/doom/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * doom2texpath[]= { + "%stextures/doom/doom2/%s.%s", "%stextures/doom/doom2/%s-ck.%s", + "%stextures/doom/%s.%s", "%stextures/doom/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * pluttexpath[]= { + "%stextures/doom/plut/%s.%s", "%stextures/doom/plut/%s-ck.%s", + "%stextures/doom/doom2-plut/%s.%s", "%stextures/doom/doom2-plut/%s-ck.%s", + "%stextures/doom/%s.%s", "%stextures/doom/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * tnttexpath[]= { + "%stextures/doom/tnt/%s.%s", "%stextures/doom/tnt/%s-ck.%s", + "%stextures/doom/doom2-tnt/%s.%s", "%stextures/doom/doom2-tnt/%s-ck.%s", + "%stextures/doom/%s.%s", "%stextures/doom/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * heretictexpath[]= { + "%stextures/heretic/%s.%s", "%stextures/heretic/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * hexentexpath[]= { + "%stextures/hexen/%s.%s", "%stextures/hexen/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * strifetexpath[]= { + "%stextures/strife/%s.%s", "%stextures/strife/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * chextexpath[]= { + "%stextures/chex/%s.%s", "%stextures/chex/%s-ck.%s", "%stextures/%s.%s", "%stextures/%s-ck.%s", NULL + }; + + static const char * doom1flatpath[]= { + "%sflats/doom/doom1/%s.%s", "%stextures/doom/doom1/flat-%s.%s", + "%sflats/doom/%s.%s", "%stextures/doom/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * doom2flatpath[]= { + "%sflats/doom/doom2/%s.%s", "%stextures/doom/doom2/flat-%s.%s", + "%sflats/doom/%s.%s", "%stextures/doom/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * plutflatpath[]= { + "%sflats/doom/plut/%s.%s", "%stextures/doom/plut/flat-%s.%s", + "%sflats/doom/doom2-plut/%s.%s", "%stextures/doom/doom2-plut/flat-%s.%s", + "%sflats/doom/%s.%s", "%stextures/doom/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * tntflatpath[]= { + "%sflats/doom/tnt/%s.%s", "%stextures/doom/tnt/flat-%s.%s", + "%sflats/doom/doom2-tnt/%s.%s", "%stextures/doom/doom2-tnt/flat-%s.%s", + "%sflats/doom/%s.%s", "%stextures/doom/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * hereticflatpath[]= { + "%sflats/heretic/%s.%s", "%stextures/heretic/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * hexenflatpath[]= { + "%sflats/hexen/%s.%s", "%stextures/hexen/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * strifeflatpath[]= { + "%sflats/strife/%s.%s", "%stextures/strife/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * chexflatpath[]= { + "%sflats/chex/%s.%s", "%stextures/chex/flat-%s.%s", "%sflats/%s.%s", "%stextures/flat-%s.%s", NULL + }; + + static const char * doom1patchpath[]= { + "%spatches/doom/doom1/%s.%s", "%spatches/doom/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * doom2patchpath[]= { + "%spatches/doom/doom2/%s.%s", "%spatches/doom/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * plutpatchpath[]= { + "%spatches/doom/plut/%s.%s", "%spatches/doom/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * tntpatchpath[]= { + "%spatches/doom/tnt/%s.%s", "%spatches/doom/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * hereticpatchpath[]= { + "%spatches/heretic/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * hexenpatchpath[]= { + "%spatches/hexen/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * strifepatchpath[]= { + "%spatches/strife/%s.%s", "%spatches/%s.%s", NULL + }; + + static const char * chexpatchpath[]= { + "%spatches/chex/%s.%s", "%spatches/%s.%s", NULL + }; + + FString checkName; + const char ** checklist; + BYTE useType=tex->UseType; + + if (useType==FTexture::TEX_SkinSprite || useType==FTexture::TEX_Decal || useType==FTexture::TEX_FontChar) + { + return -3; + } + + bool ispatch = (useType==FTexture::TEX_MiscPatch || useType==FTexture::TEX_Sprite) ; + + // for patches this doesn't work yet + if (ispatch) return -3; + + if (!gameinfo.ConfigName.CompareNoCase("Doom")) + { + if (!(gameinfo.flags & GI_MAPxx)) + { + checklist = ispatch ? doom1patchpath : useType==FTexture::TEX_Flat? doom1flatpath : doom1texpath; + } + else + { + SetDoom2Wad(); + if (Doom2Wad == 1) + checklist = ispatch ? plutpatchpath : useType==FTexture::TEX_Flat? plutflatpath : pluttexpath; + else if (Doom2Wad == 2) + checklist = ispatch ? tntpatchpath : useType==FTexture::TEX_Flat? tntflatpath : tnttexpath; + else + checklist = ispatch ? doom2patchpath : useType==FTexture::TEX_Flat? doom2flatpath : doom2texpath; + } + } + else if (!gameinfo.ConfigName.CompareNoCase("Heretic")) + { + checklist = ispatch ? hereticpatchpath : useType==FTexture::TEX_Flat? hereticflatpath : heretictexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Hexen")) + { + checklist = ispatch ? hexenpatchpath : useType==FTexture::TEX_Flat? hexenflatpath : hexentexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Strife")) + { + checklist = ispatch ?strifepatchpath : useType==FTexture::TEX_Flat? strifeflatpath : strifetexpath; + } + else if (!gameinfo.ConfigName.CompareNoCase("Chex")) + { + checklist = ispatch ?chexpatchpath : useType==FTexture::TEX_Flat? chexflatpath : chextexpath; + } + else + return -3; + + while (*checklist) + { + static const char * extensions[] = { "PNG", "JPG", "TGA", "PCX", NULL }; + + for (const char ** extp=extensions; *extp; extp++) + { + checkName.Format(*checklist, progdir.GetChars(), tex->Name.GetChars(), *extp); + if (_access(checkName, 0) == 0) + { + hascolorkey = !!strstr(checkName, "-ck."); + return Wads.AddExternalFile(checkName); + } + } + checklist++; + } + return -3; +} + + diff --git a/src/gl/textures/gl_hqresize.cpp b/src/gl/textures/gl_hqresize.cpp new file mode 100644 index 000000000..253d91f4b --- /dev/null +++ b/src/gl/textures/gl_hqresize.cpp @@ -0,0 +1,419 @@ +/* +** gl_hqresize.cpp +** Contains high quality upsampling functions. +** So far Scale2x/3x/4x as described in http://scale2x.sourceforge.net/ +** are implemented. +** +**--------------------------------------------------------------------------- +** Copyright 2008 Benjamin Berkels +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "gl/system/gl_system.h" +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/textures/gl_texture.h" +#include "c_cvars.h" +#include "gl/hqnx/hqx.h" +#ifdef HAVE_MMX +#include "gl/hqnx_asm/hqnx_asm.h" +#endif +#include "gl/xbr/xbrz.h" +#include "gl/xbr/xbrz_old.h" + +#ifdef __APPLE__ +# include +# if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 +# define GZ_USE_LIBDISPATCH +# endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 +#endif // __APPLE__ + +#ifdef GZ_USE_LIBDISPATCH +# include +#endif // GZ_USE_LIBDISPATCH + +CUSTOM_CVAR(Int, gl_texture_hqresize, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (self < 0 || self > 16) + { + self = 0; + } + #ifndef HAVE_MMX + // This is to allow the menu option to work properly so that these filters can be skipped while cycling through them. + if (self == 7) self = 10; + if (self == 8) self = 10; + if (self == 9) self = 6; + #endif + GLRenderer->FlushTextures(); +} + +CUSTOM_CVAR(Int, gl_texture_hqresize_maxinputsize, 512, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (self > 1024) self = 1024; + GLRenderer->FlushTextures(); +} + +CUSTOM_CVAR(Int, gl_texture_hqresize_targets, 7, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + GLRenderer->FlushTextures(); +} + +CVAR (Flag, gl_texture_hqresize_textures, gl_texture_hqresize_targets, 1); +CVAR (Flag, gl_texture_hqresize_sprites, gl_texture_hqresize_targets, 2); +CVAR (Flag, gl_texture_hqresize_fonts, gl_texture_hqresize_targets, 4); + +#ifdef GZ_USE_LIBDISPATCH +CVAR(Bool, gl_texture_hqresize_multithread, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +CUSTOM_CVAR(Int, gl_texture_hqresize_mt_width, 16, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + if (self < 2) self = 2; + if (self > 1024) self = 1024; +} + +CUSTOM_CVAR(Int, gl_texture_hqresize_mt_height, 4, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) +{ + if (self < 2) self = 2; + if (self > 1024) self = 1024; +} +#endif // GZ_USE_LIBDISPATCH + + +static void scale2x ( uint32* inputBuffer, uint32* outputBuffer, int inWidth, int inHeight ) +{ + const int width = 2* inWidth; + const int height = 2 * inHeight; + + for ( int i = 0; i < inWidth; ++i ) + { + const int iMinus = (i > 0) ? (i-1) : 0; + const int iPlus = (i < inWidth - 1 ) ? (i+1) : i; + for ( int j = 0; j < inHeight; ++j ) + { + const int jMinus = (j > 0) ? (j-1) : 0; + const int jPlus = (j < inHeight - 1 ) ? (j+1) : j; + const uint32 A = inputBuffer[ iMinus +inWidth*jMinus]; + const uint32 B = inputBuffer[ iMinus +inWidth*j ]; + const uint32 C = inputBuffer[ iMinus +inWidth*jPlus]; + const uint32 D = inputBuffer[ i +inWidth*jMinus]; + const uint32 E = inputBuffer[ i +inWidth*j ]; + const uint32 F = inputBuffer[ i +inWidth*jPlus]; + const uint32 G = inputBuffer[ iPlus +inWidth*jMinus]; + const uint32 H = inputBuffer[ iPlus +inWidth*j ]; + const uint32 I = inputBuffer[ iPlus +inWidth*jPlus]; + if (B != H && D != F) { + outputBuffer[2*i + width*2*j ] = D == B ? D : E; + outputBuffer[2*i + width*(2*j+1)] = B == F ? F : E; + outputBuffer[2*i+1 + width*2*j ] = D == H ? D : E; + outputBuffer[2*i+1 + width*(2*j+1)] = H == F ? F : E; + } else { + outputBuffer[2*i + width*2*j ] = E; + outputBuffer[2*i + width*(2*j+1)] = E; + outputBuffer[2*i+1 + width*2*j ] = E; + outputBuffer[2*i+1 + width*(2*j+1)] = E; + } + } + } +} + +static void scale3x ( uint32* inputBuffer, uint32* outputBuffer, int inWidth, int inHeight ) +{ + const int width = 3* inWidth; + const int height = 3 * inHeight; + + for ( int i = 0; i < inWidth; ++i ) + { + const int iMinus = (i > 0) ? (i-1) : 0; + const int iPlus = (i < inWidth - 1 ) ? (i+1) : i; + for ( int j = 0; j < inHeight; ++j ) + { + const int jMinus = (j > 0) ? (j-1) : 0; + const int jPlus = (j < inHeight - 1 ) ? (j+1) : j; + const uint32 A = inputBuffer[ iMinus +inWidth*jMinus]; + const uint32 B = inputBuffer[ iMinus +inWidth*j ]; + const uint32 C = inputBuffer[ iMinus +inWidth*jPlus]; + const uint32 D = inputBuffer[ i +inWidth*jMinus]; + const uint32 E = inputBuffer[ i +inWidth*j ]; + const uint32 F = inputBuffer[ i +inWidth*jPlus]; + const uint32 G = inputBuffer[ iPlus +inWidth*jMinus]; + const uint32 H = inputBuffer[ iPlus +inWidth*j ]; + const uint32 I = inputBuffer[ iPlus +inWidth*jPlus]; + if (B != H && D != F) { + outputBuffer[3*i + width*3*j ] = D == B ? D : E; + outputBuffer[3*i + width*(3*j+1)] = (D == B && E != C) || (B == F && E != A) ? B : E; + outputBuffer[3*i + width*(3*j+2)] = B == F ? F : E; + outputBuffer[3*i+1 + width*3*j ] = (D == B && E != G) || (D == H && E != A) ? D : E; + outputBuffer[3*i+1 + width*(3*j+1)] = E; + outputBuffer[3*i+1 + width*(3*j+2)] = (B == F && E != I) || (H == F && E != C) ? F : E; + outputBuffer[3*i+2 + width*3*j ] = D == H ? D : E; + outputBuffer[3*i+2 + width*(3*j+1)] = (D == H && E != I) || (H == F && E != G) ? H : E; + outputBuffer[3*i+2 + width*(3*j+2)] = H == F ? F : E; + } else { + outputBuffer[3*i + width*3*j ] = E; + outputBuffer[3*i + width*(3*j+1)] = E; + outputBuffer[3*i + width*(3*j+2)] = E; + outputBuffer[3*i+1 + width*3*j ] = E; + outputBuffer[3*i+1 + width*(3*j+1)] = E; + outputBuffer[3*i+1 + width*(3*j+2)] = E; + outputBuffer[3*i+2 + width*3*j ] = E; + outputBuffer[3*i+2 + width*(3*j+1)] = E; + outputBuffer[3*i+2 + width*(3*j+2)] = E; + } + } + } +} + +static void scale4x ( uint32* inputBuffer, uint32* outputBuffer, int inWidth, int inHeight ) +{ + int width = 2* inWidth; + int height = 2 * inHeight; + uint32 * buffer2x = new uint32[width*height]; + + scale2x ( reinterpret_cast ( inputBuffer ), reinterpret_cast ( buffer2x ), inWidth, inHeight ); + width *= 2; + height *= 2; + scale2x ( reinterpret_cast ( buffer2x ), reinterpret_cast ( outputBuffer ), 2*inWidth, 2*inHeight ); + delete[] buffer2x; +} + + +static unsigned char *scaleNxHelper( void (*scaleNxFunction) ( uint32* , uint32* , int , int), + const int N, + unsigned char *inputBuffer, + const int inWidth, + const int inHeight, + int &outWidth, + int &outHeight ) +{ + outWidth = N * inWidth; + outHeight = N *inHeight; + unsigned char * newBuffer = new unsigned char[outWidth*outHeight*4]; + + scaleNxFunction ( reinterpret_cast ( inputBuffer ), reinterpret_cast ( newBuffer ), inWidth, inHeight ); + delete[] inputBuffer; + return newBuffer; +} + +#ifdef HAVE_MMX +static unsigned char *hqNxAsmHelper( void (*hqNxFunction) ( int*, unsigned char*, int, int, int ), + const int N, + unsigned char *inputBuffer, + const int inWidth, + const int inHeight, + int &outWidth, + int &outHeight ) +{ + outWidth = N * inWidth; + outHeight = N *inHeight; + + static int initdone = false; + + if (!initdone) + { + HQnX_asm::InitLUTs(); + initdone = true; + } + + HQnX_asm::CImage cImageIn; + cImageIn.SetImage(inputBuffer, inWidth, inHeight, 32); + cImageIn.Convert32To17(); + + unsigned char * newBuffer = new unsigned char[outWidth*outHeight*4]; + hqNxFunction( reinterpret_cast(cImageIn.m_pBitmap), newBuffer, cImageIn.m_Xres, cImageIn.m_Yres, outWidth*4 ); + delete[] inputBuffer; + return newBuffer; +} +#endif + +static unsigned char *hqNxHelper( void (*hqNxFunction) ( unsigned*, unsigned*, int, int ), + const int N, + unsigned char *inputBuffer, + const int inWidth, + const int inHeight, + int &outWidth, + int &outHeight ) +{ + static int initdone = false; + + if (!initdone) + { + hqxInit(); + initdone = true; + } + outWidth = N * inWidth; + outHeight = N *inHeight; + + unsigned char * newBuffer = new unsigned char[outWidth*outHeight*4]; + hqNxFunction( reinterpret_cast(inputBuffer), reinterpret_cast(newBuffer), inWidth, inHeight ); + delete[] inputBuffer; + return newBuffer; +} + + + +static unsigned char *xbrzHelper( void (*xbrzFunction) ( size_t, const uint32_t*, uint32_t*, int, int, xbrz::ColorFormat, const xbrz::ScalerCfg&, int, int ), + const int N, + unsigned char *inputBuffer, + const int inWidth, + const int inHeight, + int &outWidth, + int &outHeight ) +{ + outWidth = N * inWidth; + outHeight = N *inHeight; + + unsigned char * newBuffer = new unsigned char[outWidth*outHeight*4]; + +#ifdef GZ_USE_LIBDISPATCH + const int thresholdWidth = gl_texture_hqresize_mt_width; + const int thresholdHeight = gl_texture_hqresize_mt_height; + + if (gl_texture_hqresize_multithread + && inWidth > thresholdWidth + && inHeight > thresholdHeight) + { + const dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + dispatch_apply(inHeight / thresholdHeight + 1, queue, ^(size_t sliceY) + { + xbrzFunction(N, reinterpret_cast(inputBuffer), reinterpret_cast(newBuffer), + inWidth, inHeight, xbrz::ARGB, xbrz::ScalerCfg(), sliceY * thresholdHeight, (sliceY + 1) * thresholdHeight); + }); + } + else +#endif // GZ_USE_LIBDISPATCH + { + xbrzFunction(N, reinterpret_cast(inputBuffer), reinterpret_cast(newBuffer), + inWidth, inHeight, xbrz::ARGB, xbrz::ScalerCfg(), 0, std::numeric_limits::max()); + } + + delete[] inputBuffer; + return newBuffer; +} + +static void xbrzOldScale(size_t factor, const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, xbrz::ColorFormat colFmt, const xbrz::ScalerCfg& cfg, int yFirst, int yLast) +{ + static_assert(sizeof(xbrz::ScalerCfg) == sizeof(xbrz_old::ScalerCfg), "ScalerCfg classes have different layout"); + xbrz_old::scale(factor, src, trg, srcWidth, srcHeight, reinterpret_cast(cfg), yFirst, yLast); +} + + +//=========================================================================== +// +// [BB] Upsamples the texture in inputBuffer, frees inputBuffer and returns +// the upsampled buffer. +// +//=========================================================================== +unsigned char *gl_CreateUpsampledTextureBuffer ( const FTexture *inputTexture, unsigned char *inputBuffer, const int inWidth, const int inHeight, int &outWidth, int &outHeight, bool hasAlpha ) +{ + // [BB] Make sure that outWidth and outHeight denote the size of + // the returned buffer even if we don't upsample the input buffer. + outWidth = inWidth; + outHeight = inHeight; + + // [BB] Don't resample if the width or height of the input texture is bigger than gl_texture_hqresize_maxinputsize. + if ( ( inWidth > gl_texture_hqresize_maxinputsize ) || ( inHeight > gl_texture_hqresize_maxinputsize ) ) + return inputBuffer; + + // [BB] Don't try to upsample textures based off FCanvasTexture. + if ( inputTexture->bHasCanvas ) + return inputBuffer; + + // [BB] Don't upsample non-shader handled warped textures. Needs too much memory and time + if (gl.legacyMode && inputTexture->bWarped) + return inputBuffer; + + // already scaled? + if (inputTexture->Scale.X >= 2 && inputTexture->Scale.Y >= 2) + return inputBuffer; + + switch (inputTexture->UseType) + { + case FTexture::TEX_Sprite: + case FTexture::TEX_SkinSprite: + if (!(gl_texture_hqresize_targets & 2)) return inputBuffer; + break; + + case FTexture::TEX_FontChar: + if (!(gl_texture_hqresize_targets & 4)) return inputBuffer; + break; + + default: + if (!(gl_texture_hqresize_targets & 1)) return inputBuffer; + break; + } + + if (inputBuffer) + { + int type = gl_texture_hqresize; + outWidth = inWidth; + outHeight = inHeight; +#ifdef HAVE_MMX + // hqNx MMX does not preserve the alpha channel so fall back to C-version for such textures + if (hasAlpha && type > 6 && type <= 9) + { + type -= 3; + } +#endif + + switch (type) + { + case 1: + return scaleNxHelper( &scale2x, 2, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 2: + return scaleNxHelper( &scale3x, 3, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 3: + return scaleNxHelper( &scale4x, 4, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 4: + return hqNxHelper( &hq2x_32, 2, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 5: + return hqNxHelper( &hq3x_32, 3, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 6: + return hqNxHelper( &hq4x_32, 4, inputBuffer, inWidth, inHeight, outWidth, outHeight ); +#ifdef HAVE_MMX + case 7: + return hqNxAsmHelper( &HQnX_asm::hq2x_32, 2, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 8: + return hqNxAsmHelper( &HQnX_asm::hq3x_32, 3, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + case 9: + return hqNxAsmHelper( &HQnX_asm::hq4x_32, 4, inputBuffer, inWidth, inHeight, outWidth, outHeight ); +#endif + case 10: + case 11: + case 12: + return xbrzHelper(xbrz::scale, type - 8, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + + case 13: + case 14: + case 15: + return xbrzHelper(xbrzOldScale, type - 11, inputBuffer, inWidth, inHeight, outWidth, outHeight ); + + } + } + return inputBuffer; +} diff --git a/src/gl/textures/gl_hwtexture.cpp b/src/gl/textures/gl_hwtexture.cpp new file mode 100644 index 000000000..477d1986b --- /dev/null +++ b/src/gl/textures/gl_hwtexture.cpp @@ -0,0 +1,435 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gltexture.cpp +** Low level OpenGL texture handling. These classes are also +** containers for the various translations a texture can have. +** +*/ + +#include "gl/system/gl_system.h" +#include "templates.h" +#include "m_crc32.h" +#include "c_cvars.h" +#include "c_dispatch.h" +#include "v_palette.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/textures/gl_material.h" + + +extern TexFilter_s TexFilter[]; +extern int TexFormat[]; + + +//=========================================================================== +// +// Static texture data +// +//=========================================================================== +unsigned int FHardwareTexture::lastbound[FHardwareTexture::MAX_TEXTURES]; + +//=========================================================================== +// +// Quick'n dirty image rescaling. +// +// This will only be used when the source texture is larger than +// what the hardware can manage (extremely rare in Doom) +// +// Code taken from wxWidgets +// +//=========================================================================== + +struct BoxPrecalc +{ + int boxStart; + int boxEnd; +}; + +static void ResampleBoxPrecalc(TArray& boxes, int oldDim) +{ + int newDim = boxes.Size(); + const double scale_factor_1 = double(oldDim) / newDim; + const int scale_factor_2 = (int)(scale_factor_1 / 2); + + for (int dst = 0; dst < newDim; ++dst) + { + // Source pixel in the Y direction + const int src_p = int(dst * scale_factor_1); + + BoxPrecalc& precalc = boxes[dst]; + precalc.boxStart = clamp(int(src_p - scale_factor_1 / 2.0 + 1), 0, oldDim - 1); + precalc.boxEnd = clamp(MAX(precalc.boxStart + 1, int(src_p + scale_factor_2)), 0, oldDim - 1); + } +} + +void FHardwareTexture::Resize(int width, int height, unsigned char *src_data, unsigned char *dst_data) +{ + + // This function implements a simple pre-blur/box averaging method for + // downsampling that gives reasonably smooth results To scale the image + // down we will need to gather a grid of pixels of the size of the scale + // factor in each direction and then do an averaging of the pixels. + + TArray vPrecalcs(height); + TArray hPrecalcs(width); + + ResampleBoxPrecalc(vPrecalcs, texheight); + ResampleBoxPrecalc(hPrecalcs, texwidth); + + int averaged_pixels, averaged_alpha, src_pixel_index; + double sum_r, sum_g, sum_b, sum_a; + + for (int y = 0; y < height; y++) // Destination image - Y direction + { + // Source pixel in the Y direction + const BoxPrecalc& vPrecalc = vPrecalcs[y]; + + for (int x = 0; x < width; x++) // Destination image - X direction + { + // Source pixel in the X direction + const BoxPrecalc& hPrecalc = hPrecalcs[x]; + + // Box of pixels to average + averaged_pixels = 0; + averaged_alpha = 0; + sum_r = sum_g = sum_b = sum_a = 0.0; + + for (int j = vPrecalc.boxStart; j <= vPrecalc.boxEnd; ++j) + { + for (int i = hPrecalc.boxStart; i <= hPrecalc.boxEnd; ++i) + { + // Calculate the actual index in our source pixels + src_pixel_index = j * texwidth + i; + + int a = src_data[src_pixel_index * 4 + 3]; + if (a > 0) // do not use color from fully transparent pixels + { + sum_r += src_data[src_pixel_index * 4 + 0]; + sum_g += src_data[src_pixel_index * 4 + 1]; + sum_b += src_data[src_pixel_index * 4 + 2]; + sum_a += a; + averaged_pixels++; + } + averaged_alpha++; + + } + } + + // Calculate the average from the sum and number of averaged pixels + dst_data[0] = (unsigned char)xs_CRoundToInt(sum_r / averaged_pixels); + dst_data[1] = (unsigned char)xs_CRoundToInt(sum_g / averaged_pixels); + dst_data[2] = (unsigned char)xs_CRoundToInt(sum_b / averaged_pixels); + dst_data[3] = (unsigned char)xs_CRoundToInt(sum_a / averaged_alpha); + dst_data += 4; + } + } +} + + + +//=========================================================================== +// +// Loads the texture image into the hardware +// +// NOTE: For some strange reason I was unable to find the source buffer +// should be one line higher than the actual texture. I got extremely +// strange crashes deep inside the GL driver when I didn't do it! +// +//=========================================================================== + +unsigned int FHardwareTexture::CreateTexture(unsigned char * buffer, int w, int h, int texunit, bool mipmap, int translation, const FString &name) +{ + int rh,rw; + int texformat=TexFormat[gl_texture_format]; + bool deletebuffer=false; + + if (forcenocompression) + { + texformat = GL_RGBA8; + } + TranslatedTexture * glTex=GetTexID(translation); + if (glTex->glTexID==0) glGenTextures(1,&glTex->glTexID); + if (texunit != 0) glActiveTexture(GL_TEXTURE0+texunit); + glBindTexture(GL_TEXTURE_2D, glTex->glTexID); + FGLDebug::LabelObject(GL_TEXTURE, glTex->glTexID, name); + lastbound[texunit] = glTex->glTexID; + + if (!buffer) + { + w=texwidth; + h=abs(texheight); + rw = GetTexDimension (w); + rh = GetTexDimension (h); + + // The texture must at least be initialized if no data is present. + glTex->mipmapped = false; + buffer=(unsigned char *)calloc(4,rw * (rh+1)); + deletebuffer=true; + //texheight=-h; + } + else + { + rw = GetTexDimension (w); + rh = GetTexDimension (h); + + if (rw < w || rh < h) + { + // The texture is larger than what the hardware can handle so scale it down. + unsigned char * scaledbuffer=(unsigned char *)calloc(4,rw * (rh+1)); + if (scaledbuffer) + { + Resize(rw, rh, buffer, scaledbuffer); + deletebuffer=true; + buffer=scaledbuffer; + } + } + } + glTexImage2D(GL_TEXTURE_2D, 0, texformat, rw, rh, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); + + if (deletebuffer) free(buffer); + + if (mipmap && TexFilter[gl_texture_filter].mipmapping) + { + glGenerateMipmap(GL_TEXTURE_2D); + glTex->mipmapped = true; + } + + if (texunit != 0) glActiveTexture(GL_TEXTURE0); + return glTex->glTexID; +} + + +//=========================================================================== +// +// Creates a texture +// +//=========================================================================== +FHardwareTexture::FHardwareTexture(int _width, int _height, bool nocompression) +{ + forcenocompression = nocompression; + texwidth=_width; + texheight=_height; + + glDefTex.glTexID = 0; + glDefTex.translation = 0; + glDefTex.mipmapped = false; + glDepthID = 0; +} + + +//=========================================================================== +// +// Deletes a texture id and unbinds it from the texture units +// +//=========================================================================== +void FHardwareTexture::TranslatedTexture::Delete() +{ + if (glTexID != 0) + { + for(int i = 0; i < MAX_TEXTURES; i++) + { + if (lastbound[i] == glTexID) + { + lastbound[i] = 0; + } + } + glDeleteTextures(1, &glTexID); + glTexID = 0; + mipmapped = false; + } +} + +//=========================================================================== +// +// Frees all associated resources +// +//=========================================================================== +void FHardwareTexture::Clean(bool all) +{ + int cm_arraysize = CM_FIRSTSPECIALCOLORMAP + SpecialColormaps.Size(); + + if (all) + { + glDefTex.Delete(); + } + for(unsigned int i=0;i= 0; i--) + { + if (usedtranslations.CheckKey(glTex_Translated[i].translation) == nullptr) + { + glTex_Translated[i].Delete(); + glTex_Translated.Delete(i); + } + } +} + +//=========================================================================== +// +// Destroys the texture +// +//=========================================================================== +FHardwareTexture::~FHardwareTexture() +{ + Clean(true); +} + + +//=========================================================================== +// +// Gets a texture ID address and validates all required data +// +//=========================================================================== + +FHardwareTexture::TranslatedTexture *FHardwareTexture::GetTexID(int translation) +{ + if (translation == 0) + { + return &glDefTex; + } + + // normally there aren't more than very few different + // translations here so this isn't performance critical. + for (unsigned int i = 0; i < glTex_Translated.Size(); i++) + { + if (glTex_Translated[i].translation == translation) + { + return &glTex_Translated[i]; + } + } + + int add = glTex_Translated.Reserve(1); + glTex_Translated[add].translation = translation; + glTex_Translated[add].glTexID = 0; + glTex_Translated[add].mipmapped = false; + return &glTex_Translated[add]; +} + +//=========================================================================== +// +// Binds this patch +// +//=========================================================================== +unsigned int FHardwareTexture::Bind(int texunit, int translation, bool needmipmap) +{ + TranslatedTexture *pTex = GetTexID(translation); + + if (pTex->glTexID != 0) + { + if (lastbound[texunit] == pTex->glTexID) return pTex->glTexID; + lastbound[texunit] = pTex->glTexID; + if (texunit != 0) glActiveTexture(GL_TEXTURE0 + texunit); + glBindTexture(GL_TEXTURE_2D, pTex->glTexID); + // Check if we need mipmaps on a texture that was creted without them. + if (needmipmap && !pTex->mipmapped && TexFilter[gl_texture_filter].mipmapping) + { + glGenerateMipmap(GL_TEXTURE_2D); + pTex->mipmapped = true; + } + if (texunit != 0) glActiveTexture(GL_TEXTURE0); + return pTex->glTexID; + } + return 0; +} + +unsigned int FHardwareTexture::GetTextureHandle(int translation) +{ + TranslatedTexture *pTex = GetTexID(translation); + return pTex->glTexID; +} + +void FHardwareTexture::Unbind(int texunit) +{ + if (lastbound[texunit] != 0) + { + if (texunit != 0) glActiveTexture(GL_TEXTURE0+texunit); + glBindTexture(GL_TEXTURE_2D, 0); + if (texunit != 0) glActiveTexture(GL_TEXTURE0); + lastbound[texunit] = 0; + } +} + +void FHardwareTexture::UnbindAll() +{ + for(int texunit = 0; texunit < 16; texunit++) + { + Unbind(texunit); + } + FMaterial::ClearLastTexture(); +} + +//=========================================================================== +// +// Creates a depth buffer for this texture +// +//=========================================================================== + +int FHardwareTexture::GetDepthBuffer() +{ + if (glDepthID == 0) + { + glGenRenderbuffers(1, &glDepthID); + glBindRenderbuffer(GL_RENDERBUFFER, glDepthID); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, + GetTexDimension(texwidth), GetTexDimension(texheight)); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + } + return glDepthID; +} + + +//=========================================================================== +// +// Binds this texture's surfaces to the current framrbuffer +// +//=========================================================================== + +void FHardwareTexture::BindToFrameBuffer() +{ + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, glDefTex.glTexID, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, GetDepthBuffer()); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, GetDepthBuffer()); +} + diff --git a/src/gl/textures/gl_hwtexture.h b/src/gl/textures/gl_hwtexture.h new file mode 100644 index 000000000..59fc98169 --- /dev/null +++ b/src/gl/textures/gl_hwtexture.h @@ -0,0 +1,92 @@ + +#ifndef __GLTEXTURE_H +#define __GLTEXTURE_H + +#ifdef LoadImage +#undef LoadImage +#endif + +#define SHADED_TEXTURE -1 +#define DIRECT_PALETTE -2 + +#include "tarray.h" +#include "gl/system/gl_interface.h" + +class FCanvasTexture; +class AActor; +typedef TMap SpriteHits; + +// For error catching while changing parameters. +enum EInvalid +{ + Invalid = 0 +}; + +enum +{ + GLT_CLAMPX=1, + GLT_CLAMPY=2 +}; + +class FHardwareTexture +{ +public: + enum + { + MAX_TEXTURES = 16 + }; + +private: + struct TranslatedTexture + { + unsigned int glTexID; + int translation; + bool mipmapped; + + void Delete(); + }; + +public: + + static unsigned int lastbound[MAX_TEXTURES]; + + static int GetTexDimension(int value) + { + if (value > gl.max_texturesize) return gl.max_texturesize; + return value; + } + + static void InitGlobalState() { for (int i = 0; i < MAX_TEXTURES; i++) lastbound[i] = 0; } + +private: + + short texwidth, texheight; + bool forcenocompression; + + TranslatedTexture glDefTex; + TArray glTex_Translated; + unsigned int glDepthID; // only used by camera textures + + TranslatedTexture * GetTexID(int translation); + + int GetDepthBuffer(); + void Resize(int width, int height, unsigned char *src_data, unsigned char *dst_data); + +public: + FHardwareTexture(int w, int h, bool nocompress); + ~FHardwareTexture(); + + static void Unbind(int texunit); + static void UnbindAll(); + + void BindToFrameBuffer(); + + unsigned int Bind(int texunit, int translation, bool needmipmap); + unsigned int CreateTexture(unsigned char * buffer, int w, int h, int texunit, bool mipmap, int translation, const FString &name); + unsigned int GetTextureHandle(int translation); + + void Clean(bool all); + void CleanUnused(SpriteHits &usedtranslations); +}; + +#endif diff --git a/src/gl/textures/gl_material.cpp b/src/gl/textures/gl_material.cpp new file mode 100644 index 000000000..dd224b8e0 --- /dev/null +++ b/src/gl/textures/gl_material.cpp @@ -0,0 +1,887 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "w_wad.h" +#include "m_png.h" +#include "sbar.h" +#include "gi.h" +#include "cmdlib.h" +#include "c_dispatch.h" +#include "stats.h" +#include "r_utility.h" +#include "templates.h" +#include "sc_man.h" +#include "colormatcher.h" +#include "textures/warpbuffer.h" + +//#include "gl/gl_intern.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/renderer/gl_lightdata.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/data/gl_data.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_translate.h" +#include "gl/textures/gl_bitmap.h" +#include "gl/textures/gl_material.h" +#include "gl/textures/gl_samplers.h" +#include "gl/shaders/gl_shader.h" + +EXTERN_CVAR(Bool, gl_render_precise) +EXTERN_CVAR(Int, gl_lightmode) +EXTERN_CVAR(Bool, gl_precache) +EXTERN_CVAR(Bool, gl_texture_usehires) + +//=========================================================================== +// +// The GL texture maintenance class +// +//=========================================================================== + +//=========================================================================== +// +// Constructor +// +//=========================================================================== +FGLTexture::FGLTexture(FTexture * tx, bool expandpatches) +{ + assert(tx->gl_info.SystemTexture[expandpatches] == NULL); + tex = tx; + + mHwTexture = NULL; + HiresLump = -1; + hirestexture = NULL; + bHasColorkey = false; + bIsTransparent = -1; + bExpandFlag = expandpatches; + lastSampler = 254; + lastTranslation = -1; + tex->gl_info.SystemTexture[expandpatches] = this; +} + +//=========================================================================== +// +// Destructor +// +//=========================================================================== + +FGLTexture::~FGLTexture() +{ + Clean(true); + if (hirestexture) delete hirestexture; +} + +//========================================================================== +// +// Checks for the presence of a hires texture replacement and loads it +// +//========================================================================== +unsigned char *FGLTexture::LoadHiresTexture(FTexture *tex, int *width, int *height) +{ + if (bExpandFlag) return NULL; // doesn't work for expanded textures + + if (HiresLump==-1) + { + bHasColorkey = false; + HiresLump = CheckDDPK3(tex); + if (HiresLump < 0) HiresLump = CheckExternalFile(tex, bHasColorkey); + + if (HiresLump >=0) + { + hirestexture = FTexture::CreateTexture(HiresLump, FTexture::TEX_Any); + } + } + if (hirestexture != NULL) + { + int w=hirestexture->GetWidth(); + int h=hirestexture->GetHeight(); + + unsigned char * buffer=new unsigned char[w*(h+1)*4]; + memset(buffer, 0, w * (h+1) * 4); + + FGLBitmap bmp(buffer, w*4, w, h); + + int trans = hirestexture->CopyTrueColorPixels(&bmp, 0, 0); + hirestexture->CheckTrans(buffer, w*h, trans); + bIsTransparent = hirestexture->gl_info.mIsTransparent; + + if (bHasColorkey) + { + // This is a crappy Doomsday color keyed image + // We have to remove the key manually. :( + DWORD * dwdata=(DWORD*)buffer; + for (int i=(w*h);i>0;i--) + { + if (dwdata[i]==0xffffff00 || dwdata[i]==0xffff00ff) dwdata[i]=0; + } + } + *width = w; + *height = h; + return buffer; + } + return NULL; +} + +//=========================================================================== +// +// Deletes all allocated resources +// +//=========================================================================== + +void FGLTexture::Clean(bool all) +{ + if (mHwTexture != nullptr) + { + if (!all) mHwTexture->Clean(false); + else + { + delete mHwTexture; + mHwTexture = nullptr; + } + + lastSampler = 253; + lastTranslation = -1; + } +} + + +void FGLTexture::CleanUnused(SpriteHits &usedtranslations) +{ + if (mHwTexture != nullptr) + { + mHwTexture->CleanUnused(usedtranslations); + lastSampler = 253; + lastTranslation = -1; + } +} + + +//=========================================================================== +// +// Initializes the buffer for the texture data +// +//=========================================================================== + +unsigned char * FGLTexture::CreateTexBuffer(int translation, int & w, int & h, FTexture *hirescheck, bool createexpanded, bool alphatrans) +{ + unsigned char * buffer; + int W, H; + + + // Textures that are already scaled in the texture lump will not get replaced + // by hires textures + if (gl_texture_usehires && hirescheck != NULL && !alphatrans) + { + buffer = LoadHiresTexture (hirescheck, &w, &h); + if (buffer) + { + return buffer; + } + } + + int exx = bExpandFlag && createexpanded; + + W = w = tex->GetWidth() + 2 * exx; + H = h = tex->GetHeight() + 2 * exx; + + + buffer=new unsigned char[W*(H+1)*4]; + memset(buffer, 0, W * (H+1) * 4); + + FGLBitmap bmp(buffer, W*4, W, H); + bmp.SetTranslationInfo(translation, alphatrans); + + if (tex->bComplex) + { + FBitmap imgCreate; + + // The texture contains special processing so it must be composited using the + // base bitmap class and then be converted as a whole. + if (imgCreate.Create(W, H)) + { + memset(imgCreate.GetPixels(), 0, W * H * 4); + int trans = tex->CopyTrueColorPixels(&imgCreate, exx, exx); + bmp.CopyPixelDataRGB(0, 0, imgCreate.GetPixels(), W, H, 4, W * 4, 0, CF_BGRA); + tex->CheckTrans(buffer, W*H, trans); + bIsTransparent = tex->gl_info.mIsTransparent; + } + } + else if (translation<=0) + { + int trans = tex->CopyTrueColorPixels(&bmp, exx, exx); + tex->CheckTrans(buffer, W*H, trans); + bIsTransparent = tex->gl_info.mIsTransparent; + } + else + { + // When using translations everything must be mapped to the base palette. + // Since FTexture's method is doing exactly that by calling GetPixels let's use that here + // to do all the dirty work for us. ;) + tex->FTexture::CopyTrueColorPixels(&bmp, exx, exx); + bIsTransparent = 0; + } + + // if we just want the texture for some checks there's no need for upsampling. + if (!createexpanded) return buffer; + + // [BB] The hqnx upsampling (not the scaleN one) destroys partial transparency, don't upsamle textures using it. + // [BB] Potentially upsample the buffer. + return gl_CreateUpsampledTextureBuffer ( tex, buffer, W, H, w, h, !!bIsTransparent); +} + + +//=========================================================================== +// +// Create hardware texture for world use +// +//=========================================================================== + +FHardwareTexture *FGLTexture::CreateHwTexture() +{ + if (tex->UseType==FTexture::TEX_Null) return NULL; // Cannot register a NULL texture + if (mHwTexture == NULL) + { + mHwTexture = new FHardwareTexture(tex->GetWidth() + bExpandFlag*2, tex->GetHeight() + bExpandFlag*2, tex->gl_info.bNoCompress); + } + return mHwTexture; +} + +//=========================================================================== +// +// Binds a texture to the renderer +// +//=========================================================================== + +const FHardwareTexture *FGLTexture::Bind(int texunit, int clampmode, int translation, FTexture *hirescheck) +{ + int usebright = false; + bool alphatrans = false; + + if (translation <= 0) translation = -translation; + else + { + alphatrans = (gl.legacyMode && translation == TRANSLATION(TRANSLATION_Standard, 8)); + translation = GLTranslationPalette::GetInternalTranslation(translation); + } + + bool needmipmap = (clampmode <= CLAMP_XY); + + FHardwareTexture *hwtex = CreateHwTexture(); + + if (hwtex) + { + // Texture has become invalid + if ((!tex->bHasCanvas && (!tex->bWarped || gl.legacyMode)) && tex->CheckModified()) + { + Clean(true); + hwtex = CreateHwTexture(); + } + + // Bind it to the system. + if (!hwtex->Bind(texunit, translation, needmipmap)) + { + + int w=0, h=0; + + // Create this texture + unsigned char * buffer = NULL; + + if (!tex->bHasCanvas) + { + buffer = CreateTexBuffer(translation, w, h, hirescheck, true, alphatrans); + if (tex->bWarped && gl.legacyMode && w*h <= 256*256) // do not software-warp larger textures, especially on the old systems that still need this fallback. + { + // need to do software warping + FWarpTexture *wt = static_cast(tex); + unsigned char *warpbuffer = new unsigned char[w*h*4]; + WarpBuffer((DWORD*)warpbuffer, (const DWORD*)buffer, w, h, wt->WidthOffsetMultiplier, wt->HeightOffsetMultiplier, r_FrameTime, wt->Speed, tex->bWarped); + delete[] buffer; + buffer = warpbuffer; + wt->GenTime = r_FrameTime; + } + tex->ProcessData(buffer, w, h, false); + } + if (!hwtex->CreateTexture(buffer, w, h, texunit, needmipmap, translation, "FGLTexture.Bind")) + { + // could not create texture + delete[] buffer; + return NULL; + } + delete[] buffer; + } + if (tex->bHasCanvas) static_cast(tex)->NeedUpdate(); + if (translation != lastTranslation) lastSampler = 254; + if (lastSampler != clampmode) + lastSampler = GLRenderer->mSamplerManager->Bind(texunit, clampmode, lastSampler); + lastTranslation = translation; + return hwtex; + } + return NULL; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +float FTexCoordInfo::RowOffset(float rowoffset) const +{ + if (mTempScale.Y == 1.f) + { + if (mScale.Y == 1.f || mWorldPanning) return rowoffset; + else return rowoffset / mScale.Y; + } + else + { + if (mWorldPanning) return rowoffset / mTempScale.Y; + else return rowoffset / mScale.Y; + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +float FTexCoordInfo::TextureOffset(float textureoffset) const +{ + if (mTempScale.X == 1.f) + { + if (mScale.X == 1.f || mWorldPanning) return textureoffset; + else return textureoffset / mScale.X; + } + else + { + if (mWorldPanning) return textureoffset / mTempScale.X; + else return textureoffset / mScale.X; + } +} + +//=========================================================================== +// +// Returns the size for which texture offset coordinates are used. +// +//=========================================================================== + +float FTexCoordInfo::TextureAdjustWidth() const +{ + if (mWorldPanning) + { + if (mTempScale.X == 1.f) return mRenderWidth; + else return mWidth / mTempScale.X; + } + else return mWidth; +} + + + +//=========================================================================== +// +// +// +//=========================================================================== +FGLTexture * FMaterial::ValidateSysTexture(FTexture * tex, bool expand) +{ + if (tex && tex->UseType!=FTexture::TEX_Null) + { + FGLTexture *gltex = tex->gl_info.SystemTexture[expand]; + if (gltex == NULL) + { + gltex = new FGLTexture(tex, expand); + } + return gltex; + } + return NULL; +} + +//=========================================================================== +// +// Constructor +// +//=========================================================================== +TArray FMaterial::mMaterials; +int FMaterial::mMaxBound; + +FMaterial::FMaterial(FTexture * tx, bool expanded) +{ + mShaderIndex = 0; + tex = tx; + + // TODO: apply custom shader object here + /* if (tx->CustomShaderDefinition) + { + } + else + */ + if (tx->bWarped) + { + mShaderIndex = tx->bWarped; + tx->gl_info.shaderspeed = static_cast(tx)->GetSpeed(); + } + else if (tx->bHasCanvas) + { + } + else + { + if (tx->gl_info.shaderindex >= FIRST_USER_SHADER) + { + mShaderIndex = tx->gl_info.shaderindex; + } + else + { + tx->CreateDefaultBrightmap(); + if (tx->gl_info.Brightmap != NULL) + { + ValidateSysTexture(tx->gl_info.Brightmap, expanded); + FTextureLayer layer = {tx->gl_info.Brightmap, false}; + mTextureLayers.Push(layer); + mShaderIndex = 3; + } + } + } + mBaseLayer = ValidateSysTexture(tx, expanded); + + + mWidth = tx->GetWidth(); + mHeight = tx->GetHeight(); + mLeftOffset = tx->LeftOffset; + mTopOffset = tx->TopOffset; + mRenderWidth = tx->GetScaledWidth(); + mRenderHeight = tx->GetScaledHeight(); + mSpriteU[0] = mSpriteV[0] = 0.f; + mSpriteU[1] = mSpriteV[1] = 1.f; + + FTexture *basetex = (tx->bWarped && gl.legacyMode)? tx : tx->GetRedirect(false); + // allow the redirect only if the textute is not expanded or the scale matches. + if (!expanded || (tx->Scale.X == basetex->Scale.X && tx->Scale.Y == basetex->Scale.Y)) + { + mBaseLayer = ValidateSysTexture(basetex, expanded); + } + + float fxScale = tx->Scale.X; + float fyScale = tx->Scale.Y; + + // mSpriteRect is for positioning the sprite in the scene. + mSpriteRect.left = -mLeftOffset / fxScale; + mSpriteRect.top = -mTopOffset / fyScale; + mSpriteRect.width = mWidth / fxScale; + mSpriteRect.height = mHeight / fyScale; + + if (expanded) + { + // a little adjustment to make sprites look better with texture filtering: + // create a 1 pixel wide empty frame around them. + int trim[4]; + bool trimmed = TrimBorders(trim); // get the trim size before adding the empty frame + + int oldwidth = mWidth; + int oldheight = mHeight; + + mWidth+=2; + mHeight+=2; + mLeftOffset+=1; + mTopOffset+=1; + mRenderWidth = mRenderWidth * mWidth / oldwidth; + mRenderHeight = mRenderHeight * mHeight / oldheight; + + // Reposition the sprite with the frame considered + mSpriteRect.left = -mLeftOffset / fxScale; + mSpriteRect.top = -mTopOffset / fyScale; + mSpriteRect.width = mWidth / fxScale; + mSpriteRect.height = mHeight / fyScale; + + if (trimmed) + { + mSpriteRect.left += trim[0] / fxScale; + mSpriteRect.top += trim[1] / fyScale; + + mSpriteRect.width -= (oldwidth - trim[2]) / fxScale; + mSpriteRect.height -= (oldheight - trim[3]) / fyScale; + + mSpriteU[0] = trim[0] / (float)mWidth; + mSpriteV[0] = trim[1] / (float)mHeight; + mSpriteU[1] -= (oldwidth - trim[0] - trim[2]) / (float)mWidth; + mSpriteV[1] -= (oldheight - trim[1] - trim[3]) / (float)mHeight; + } + } + + mTextureLayers.ShrinkToFit(); + mMaxBound = -1; + mMaterials.Push(this); + tx->gl_info.Material[expanded] = this; + if (tx->bHasCanvas) tx->gl_info.mIsTransparent = 0; + mExpanded = expanded; +} + +//=========================================================================== +// +// Destructor +// +//=========================================================================== + +FMaterial::~FMaterial() +{ + for(unsigned i=0;i= size) + { + // completely empty + rect[0] = 0; + rect[1] = 0; + rect[2] = 1; + rect[3] = 1; + delete [] buffer; + return true; + } + + for(last = size-1; last >= first; last--) + { + if (buffer[last*4+3] != 0) break; + } + + rect[1] = first / w; + rect[3] = 1 + last/w - rect[1]; + + rect[0] = 0; + rect[2] = w; + + unsigned char *bufferoff = buffer + (rect[1] * w * 4); + h = rect[3]; + + for(int x = 0; x < w; x++) + { + for(int y = 0; y < h; y++) + { + if (bufferoff[(x+y*w)*4+3] != 0) goto outl; + } + rect[0]++; + } +outl: + rect[2] -= rect[0]; + + for(int x = w-1; rect[2] > 1; x--) + { + for(int y = 0; y < h; y++) + { + if (bufferoff[(x+y*w)*4+3] != 0) + { + delete [] buffer; + return true; + } + } + rect[2]--; + } + delete [] buffer; + return true; +} + + +//=========================================================================== +// +// Binds a texture to the renderer +// +//=========================================================================== + +static FMaterial *last; +static int lastclamp; +static int lasttrans; + +void FMaterial::InitGlobalState() +{ + last = nullptr; + lastclamp = 0; + lasttrans = 0; +} + +void FMaterial::Bind(int clampmode, int translation) +{ + // avoid rebinding the same texture multiple times. + if (this == last && lastclamp == clampmode && translation == lasttrans) return; + last = this; + lastclamp = clampmode; + lasttrans = translation; + + int usebright = false; + int maxbound = 0; + bool allowhires = tex->Scale.X == 1 && tex->Scale.Y == 1 && clampmode <= CLAMP_XY && !mExpanded; + + if (tex->bHasCanvas) clampmode = CLAMP_CAMTEX; + else if (tex->bWarped && clampmode <= CLAMP_XY) clampmode = CLAMP_NONE; + + const FHardwareTexture *gltexture = mBaseLayer->Bind(0, clampmode, translation, allowhires? tex:NULL); + if (gltexture != NULL) + { + for(unsigned i=0;iid; + layer = TexMan(id); + ValidateSysTexture(layer, mExpanded); + } + else + { + layer = mTextureLayers[i].texture; + } + layer->gl_info.SystemTexture[mExpanded]->Bind(i+1, clampmode, 0, NULL); + maxbound = i+1; + } + } + // unbind everything from the last texture that's still active + for(int i=maxbound+1; i<=mMaxBound;i++) + { + FHardwareTexture::Unbind(i); + mMaxBound = maxbound; + } +} + + +//=========================================================================== +// +// +// +//=========================================================================== +void FMaterial::Precache() +{ + Bind(0, 0); +} + +//=========================================================================== +// +// +// +//=========================================================================== +void FMaterial::PrecacheList(SpriteHits &translations) +{ + if (mBaseLayer != nullptr) mBaseLayer->CleanUnused(translations); + SpriteHits::Iterator it(translations); + SpriteHits::Pair *pair; + while(it.NextPair(pair)) Bind(0, pair->Key); +} + +//=========================================================================== +// +// Retrieve texture coordinate info for per-wall scaling +// +//=========================================================================== + +void FMaterial::GetTexCoordInfo(FTexCoordInfo *tci, float x, float y) const +{ + if (x == 1.f) + { + tci->mRenderWidth = mRenderWidth; + tci->mScale.X = tex->Scale.X; + tci->mTempScale.X = 1.f; + } + else + { + float scale_x = x * tex->Scale.X; + tci->mRenderWidth = xs_CeilToInt(mWidth / scale_x); + tci->mScale.X = scale_x; + tci->mTempScale.X = x; + } + + if (y == 1.f) + { + tci->mRenderHeight = mRenderHeight; + tci->mScale.Y = tex->Scale.Y; + tci->mTempScale.Y = 1.f; + } + else + { + float scale_y = y * tex->Scale.Y; + tci->mRenderHeight = xs_CeilToInt(mHeight / scale_y); + tci->mScale.Y = scale_y; + tci->mTempScale.Y = y; + } + if (tex->bHasCanvas) + { + tci->mScale.Y = -tci->mScale.Y; + tci->mRenderHeight = -tci->mRenderHeight; + } + tci->mWorldPanning = tex->bWorldPanning; + tci->mWidth = mWidth; +} + +//=========================================================================== +// +// +// +//=========================================================================== + +int FMaterial::GetAreas(FloatRect **pAreas) const +{ + if (mShaderIndex == 0) // texture splitting can only be done if there's no attached effects + { + FTexture *tex = mBaseLayer->tex; + *pAreas = tex->gl_info.areas; + return tex->gl_info.areacount; + } + else + { + return 0; + } +} + +//=========================================================================== +// +// +// +//=========================================================================== + +void FMaterial::BindToFrameBuffer() +{ + if (mBaseLayer->mHwTexture == NULL) + { + // must create the hardware texture first + mBaseLayer->Bind(0, 0, 0, NULL); + FHardwareTexture::Unbind(0); + ClearLastTexture(); + } + mBaseLayer->mHwTexture->BindToFrameBuffer(); +} + +//========================================================================== +// +// Gets a texture from the texture manager and checks its validity for +// GL rendering. +// +//========================================================================== + +FMaterial * FMaterial::ValidateTexture(FTexture * tex, bool expand) +{ +again: + if (tex && tex->UseType!=FTexture::TEX_Null) + { + if (tex->gl_info.bNoExpand) expand = false; + + FMaterial *gltex = tex->gl_info.Material[expand]; + if (gltex == NULL) + { + if (expand) + { + if (tex->bWarped || tex->bHasCanvas || tex->gl_info.shaderindex >= FIRST_USER_SHADER) + { + tex->gl_info.bNoExpand = true; + goto again; + } + if (tex->gl_info.Brightmap != NULL && + (tex->GetWidth() != tex->gl_info.Brightmap->GetWidth() || + tex->GetHeight() != tex->gl_info.Brightmap->GetHeight()) + ) + { + // do not expand if the brightmap's size differs. + tex->gl_info.bNoExpand = true; + goto again; + } + } + gltex = new FMaterial(tex, expand); + } + return gltex; + } + return NULL; +} + +FMaterial * FMaterial::ValidateTexture(FTextureID no, bool expand, bool translate) +{ + return ValidateTexture(translate? TexMan(no) : TexMan[no], expand); +} + + +//========================================================================== +// +// Flushes all hardware dependent data +// +//========================================================================== + +void FMaterial::FlushAll() +{ + for(int i=mMaterials.Size()-1;i>=0;i--) + { + mMaterials[i]->Clean(true); + } + // This is for shader layers. All shader layers must be managed by the texture manager + // so this will catch everything. + for(int i=TexMan.NumTextures()-1;i>=0;i--) + { + for (int j = 0; j < 2; j++) + { + FGLTexture *gltex = TexMan.ByIndex(i)->gl_info.SystemTexture[j]; + if (gltex != NULL) gltex->Clean(true); + } + } +} + +void FMaterial::ClearLastTexture() +{ + last = NULL; +} diff --git a/src/gl/textures/gl_material.h b/src/gl/textures/gl_material.h new file mode 100644 index 000000000..671d8c694 --- /dev/null +++ b/src/gl/textures/gl_material.h @@ -0,0 +1,271 @@ + +#ifndef __GL_MATERIAL_H +#define __GL_MATERIAL_H + +#include "m_fixed.h" +#include "textures/textures.h" +#include "gl/textures/gl_hwtexture.h" +#include "gl/renderer/gl_colormap.h" +#include "i_system.h" +#include "r_defs.h" + +EXTERN_CVAR(Bool, gl_precache) + +struct FRemapTable; +class FTextureShader; + +enum +{ + CLAMP_NONE = 0, + CLAMP_X = 1, + CLAMP_Y = 2, + CLAMP_XY = 3, + CLAMP_XY_NOMIP = 4, + CLAMP_NOFILTER = 5, + CLAMP_CAMTEX = 6, +}; + + + +struct FTexCoordInfo +{ + int mRenderWidth; + int mRenderHeight; + int mWidth; + FVector2 mScale; + FVector2 mTempScale; + bool mWorldPanning; + + float FloatToTexU(float v) const { return v / mRenderWidth; } + float FloatToTexV(float v) const { return v / mRenderHeight; } + float RowOffset(float ofs) const; + float TextureOffset(float ofs) const; + float TextureAdjustWidth() const; +}; + +//=========================================================================== +// +// this is the texture maintenance class for OpenGL. +// +//=========================================================================== +class FMaterial; + + +class FGLTexture +{ + friend class FMaterial; +public: + FTexture * tex; + FTexture * hirestexture; + char bIsTransparent; + int HiresLump; + +private: + FHardwareTexture *mHwTexture; + + bool bHasColorkey; // only for hires + bool bExpandFlag; + BYTE lastSampler; + int lastTranslation; + + unsigned char * LoadHiresTexture(FTexture *hirescheck, int *width, int *height); + + FHardwareTexture *CreateHwTexture(); + + const FHardwareTexture *Bind(int texunit, int clamp, int translation, FTexture *hirescheck); + +public: + FGLTexture(FTexture * tx, bool expandpatches); + ~FGLTexture(); + + unsigned char * CreateTexBuffer(int translation, int & w, int & h, FTexture *hirescheck, bool createexpanded = true, bool alphatrans = false); + + void Clean(bool all); + void CleanUnused(SpriteHits &usedtranslations); + int Dump(int i); + +}; + +//=========================================================================== +// +// this is the material class for OpenGL. +// +//=========================================================================== + +class FMaterial +{ + friend class FRenderState; + + struct FTextureLayer + { + FTexture *texture; + bool animated; + }; + + static TArray mMaterials; + static int mMaxBound; + + FGLTexture *mBaseLayer; + TArray mTextureLayers; + int mShaderIndex; + + short mLeftOffset; + short mTopOffset; + short mWidth; + short mHeight; + short mRenderWidth; + short mRenderHeight; + bool mExpanded; + + float mSpriteU[2], mSpriteV[2]; + FloatRect mSpriteRect; + + FGLTexture * ValidateSysTexture(FTexture * tex, bool expand); + bool TrimBorders(int *rect); + +public: + FTexture *tex; + + FMaterial(FTexture *tex, bool forceexpand); + ~FMaterial(); + void Precache(); + void PrecacheList(SpriteHits &translations); + bool isMasked() const + { + return !!mBaseLayer->tex->bMasked; + } + + int GetLayers() const + { + return mTextureLayers.Size() + 1; + } + + void Bind(int clamp, int translation); + + unsigned char * CreateTexBuffer(int translation, int & w, int & h, bool allowhires=true, bool createexpanded = true) const + { + return mBaseLayer->CreateTexBuffer(translation, w, h, allowhires? tex : NULL, createexpanded); + } + + void Clean(bool f) + { + mBaseLayer->Clean(f); + } + + void BindToFrameBuffer(); + // Patch drawing utilities + + void GetSpriteRect(FloatRect * r) const + { + *r = mSpriteRect; + } + + void GetTexCoordInfo(FTexCoordInfo *tci, float x, float y) const; + + void GetTexCoordInfo(FTexCoordInfo *tci, side_t *side, int texpos) const + { + GetTexCoordInfo(tci, (float)side->GetTextureXScale(texpos), (float)side->GetTextureYScale(texpos)); + } + + // This is scaled size in integer units as needed by walls and flats + int TextureHeight() const { return mRenderHeight; } + int TextureWidth() const { return mRenderWidth; } + + int GetAreas(FloatRect **pAreas) const; + + int GetWidth() const + { + return mWidth; + } + + int GetHeight() const + { + return mHeight; + } + + int GetLeftOffset() const + { + return mLeftOffset; + } + + int GetTopOffset() const + { + return mTopOffset; + } + + int GetScaledLeftOffset() const + { + return int(mLeftOffset / tex->Scale.X); + } + + int GetScaledTopOffset() const + { + return int(mTopOffset / tex->Scale.Y); + } + + float GetScaledLeftOffsetFloat() const + { + return float(mLeftOffset / tex->Scale.X); + } + + float GetScaledTopOffsetFloat() const + { + return float(mTopOffset/ tex->Scale.Y); + } + + // This is scaled size in floating point as needed by sprites + float GetScaledWidthFloat() const + { + return float(mWidth / tex->Scale.X); + } + + float GetScaledHeightFloat() const + { + return float(mHeight / tex->Scale.Y); + } + + // Get right/bottom UV coordinates for patch drawing + float GetUL() const { return 0; } + float GetVT() const { return 0; } + float GetUR() const { return 1; } + float GetVB() const { return 1; } + float GetU(float upix) const { return upix/(float)mWidth; } + float GetV(float vpix) const { return vpix/(float)mHeight; } + + float GetSpriteUL() const { return mSpriteU[0]; } + float GetSpriteVT() const { return mSpriteV[0]; } + float GetSpriteUR() const { return mSpriteU[1]; } + float GetSpriteVB() const { return mSpriteV[1]; } + + + + bool GetTransparent() const + { + if (mBaseLayer->bIsTransparent == -1) + { + if (!mBaseLayer->tex->bHasCanvas) + { + int w, h; + unsigned char *buffer = CreateTexBuffer(0, w, h); + delete [] buffer; + } + else + { + mBaseLayer->bIsTransparent = 0; + } + } + return !!mBaseLayer->bIsTransparent; + } + + static void DeleteAll(); + static void FlushAll(); + static FMaterial *ValidateTexture(FTexture * tex, bool expand); + static FMaterial *ValidateTexture(FTextureID no, bool expand, bool trans); + static void ClearLastTexture(); + + static void InitGlobalState(); +}; + +#endif + + diff --git a/src/gl/textures/gl_samplers.cpp b/src/gl/textures/gl_samplers.cpp new file mode 100644 index 000000000..d9d2d0700 --- /dev/null +++ b/src/gl/textures/gl_samplers.cpp @@ -0,0 +1,197 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2014-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "gl/system/gl_system.h" +#include "templates.h" +#include "c_cvars.h" +#include "c_dispatch.h" + +#include "gl/system/gl_interface.h" +#include "gl/system/gl_cvars.h" +#include "gl/system/gl_debug.h" +#include "gl/renderer/gl_renderer.h" +#include "gl_samplers.h" +#include "gl_material.h" + +extern TexFilter_s TexFilter[]; + + +FSamplerManager::FSamplerManager() +{ + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + glGenSamplers(7, mSamplers); + SetTextureFilterMode(); + glSamplerParameteri(mSamplers[5], GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glSamplerParameteri(mSamplers[5], GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glSamplerParameterf(mSamplers[5], GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.f); + glSamplerParameterf(mSamplers[4], GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.f); + glSamplerParameterf(mSamplers[6], GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.f); + + glSamplerParameteri(mSamplers[1], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glSamplerParameteri(mSamplers[2], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glSamplerParameteri(mSamplers[3], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glSamplerParameteri(mSamplers[3], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glSamplerParameteri(mSamplers[4], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glSamplerParameteri(mSamplers[4], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + for (int i = 0; i < 7; i++) + { + FString name; + name.Format("mSamplers[%d]", i); + FGLDebug::LabelObject(GL_SAMPLER, mSamplers[i], name); + } + } + +} + +FSamplerManager::~FSamplerManager() +{ + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + UnbindAll(); + glDeleteSamplers(7, mSamplers); + } +} + +void FSamplerManager::UnbindAll() +{ + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + for (int i = 0; i < FHardwareTexture::MAX_TEXTURES; i++) + { + glBindSampler(i, 0); + } + } +} + +BYTE FSamplerManager::Bind(int texunit, int num, int lastval) +{ + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + unsigned int samp = mSamplers[num]; + glBindSampler(texunit, samp); + return 255; + } + else + { + glActiveTexture(GL_TEXTURE0 + texunit); + switch (num) + { + case CLAMP_NONE: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + if (lastval >= CLAMP_XY_NOMIP) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].minfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_filter_anisotropic); + } + break; + + case CLAMP_X: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + if (lastval >= CLAMP_XY_NOMIP) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].minfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_filter_anisotropic); + } + break; + + case CLAMP_Y: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (lastval >= CLAMP_XY_NOMIP) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].minfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_filter_anisotropic); + } + break; + + case CLAMP_XY: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (lastval >= CLAMP_XY_NOMIP) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].minfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_filter_anisotropic); + } + break; + + case CLAMP_XY_NOMIP: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); + break; + + case CLAMP_NOFILTER: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); + break; + + case CLAMP_CAMTEX: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); + break; + } + glActiveTexture(GL_TEXTURE0); + return num; + } +} + + +void FSamplerManager::SetTextureFilterMode() +{ + if (gl.flags & RFL_SAMPLER_OBJECTS) + { + UnbindAll(); + + for (int i = 0; i < 4; i++) + { + glSamplerParameteri(mSamplers[i], GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].minfilter); + glSamplerParameteri(mSamplers[i], GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glSamplerParameterf(mSamplers[i], GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_filter_anisotropic); + } + glSamplerParameteri(mSamplers[4], GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].magfilter); + glSamplerParameteri(mSamplers[4], GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + glSamplerParameteri(mSamplers[6], GL_TEXTURE_MIN_FILTER, TexFilter[gl_texture_filter].magfilter); + glSamplerParameteri(mSamplers[6], GL_TEXTURE_MAG_FILTER, TexFilter[gl_texture_filter].magfilter); + } + else + { + GLRenderer->FlushTextures(); + } +} + + diff --git a/src/gl/textures/gl_samplers.h b/src/gl/textures/gl_samplers.h new file mode 100644 index 000000000..b74d49a33 --- /dev/null +++ b/src/gl/textures/gl_samplers.h @@ -0,0 +1,27 @@ +#ifndef __GL_SAMPLERS_H +#define __GL_SAMPLERS_H + +#include "gl_hwtexture.h" + +class FSamplerManager +{ + // We need 6 different samplers: 4 for the different clamping modes, + // one for 2D-textures and one for voxel textures + unsigned int mSamplers[7]; + + void UnbindAll(); + +public: + + FSamplerManager(); + ~FSamplerManager(); + + BYTE Bind(int texunit, int num, int lastval); + void SetTextureFilterMode(); + + +}; + + +#endif + diff --git a/src/gl/textures/gl_skyboxtexture.cpp b/src/gl/textures/gl_skyboxtexture.cpp new file mode 100644 index 000000000..2f7328e28 --- /dev/null +++ b/src/gl/textures/gl_skyboxtexture.cpp @@ -0,0 +1,201 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// + +#include "doomtype.h" +#include "sc_man.h" +#include "w_wad.h" +#include "textures/textures.h" +#include "gl/textures/gl_skyboxtexture.h" + + + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +FSkyBox::FSkyBox() +{ + faces[0]=faces[1]=faces[2]=faces[3]=faces[4]=faces[5]=NULL; + UseType=TEX_Override; + gl_info.bSkybox = true; + fliptop = false; +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +FSkyBox::~FSkyBox() +{ + // The faces are only referenced but not owned so don't delete them. +} + +//----------------------------------------------------------------------------- +// +// If something attempts to use this as a texture just pass the information of the first face. +// +//----------------------------------------------------------------------------- + +const BYTE *FSkyBox::GetColumn (unsigned int column, const Span **spans_out) +{ + if (faces[0]) return faces[0]->GetColumn(column, spans_out); + return NULL; +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +const BYTE *FSkyBox::GetPixels () +{ + if (faces[0]) return faces[0]->GetPixels(); + return NULL; +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +int FSkyBox::CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf) +{ + if (faces[0]) return faces[0]->CopyTrueColorPixels(bmp, x, y, rotate, inf); + return 0; +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +bool FSkyBox::UseBasePalette() +{ + return false; // not really but here it's not important. +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void FSkyBox::Unload () +{ + //for(int i=0;i<6;i++) if (faces[i]) faces[i]->Unload(); +} + +//----------------------------------------------------------------------------- +// +// +// +//----------------------------------------------------------------------------- + +void gl_ParseSkybox(FScanner &sc) +{ + int facecount=0; + + sc.MustGetString(); + + FSkyBox * sb = new FSkyBox; + sb->Name = sc.String; + sb->Name.ToUpper(); + if (sc.CheckString("fliptop")) + { + sb->fliptop = true; + } + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + sc.MustGetString(); + if (facecount<6) + { + sb->faces[facecount] = TexMan[TexMan.GetTexture(sc.String, FTexture::TEX_Wall, FTextureManager::TEXMAN_TryAny|FTextureManager::TEXMAN_Overridable)]; + } + facecount++; + } + if (facecount != 3 && facecount != 6) + { + sc.ScriptError("%s: Skybox definition requires either 3 or 6 faces", sb->Name.GetChars()); + } + sb->SetSize(); + TexMan.AddTexture(sb); +} + +//----------------------------------------------------------------------------- +// +// gl_ParseVavoomSkybox +// +//----------------------------------------------------------------------------- + +void gl_ParseVavoomSkybox() +{ + int lump = Wads.CheckNumForName("SKYBOXES"); + + if (lump < 0) return; + + FScanner sc(lump); + while (sc.GetString()) + { + int facecount=0; + int maplump = -1; + FSkyBox * sb = new FSkyBox; + sb->Name = sc.String; + sb->Name.ToUpper(); + sb->fliptop = true; + sc.MustGetStringName("{"); + while (!sc.CheckString("}")) + { + if (facecount<6) + { + sc.MustGetStringName("{"); + sc.MustGetStringName("map"); + sc.MustGetString(); + + maplump = Wads.CheckNumForFullName(sc.String, true); + + FTexture *tex = TexMan.FindTexture(sc.String, FTexture::TEX_Wall, FTextureManager::TEXMAN_TryAny); + if (tex == NULL) + { + Printf("Texture '%s' not found in Vavoom skybox '%s'\n", sc.String, sb->Name.GetChars()); + } + sb->faces[facecount] = tex; + sc.MustGetStringName("}"); + } + facecount++; + } + if (facecount != 6) + { + sc.ScriptError("%s: Skybox definition requires 6 faces", sb->Name.GetChars()); + } + sb->SetSize(); + TexMan.AddTexture(sb); + } +} + diff --git a/src/gl/textures/gl_skyboxtexture.h b/src/gl/textures/gl_skyboxtexture.h new file mode 100644 index 000000000..28a052be9 --- /dev/null +++ b/src/gl/textures/gl_skyboxtexture.h @@ -0,0 +1,44 @@ + + +//----------------------------------------------------------------------------- +// +// This is not a real texture but will be added to the texture manager +// so that it can be handled like any other sky. +// +//----------------------------------------------------------------------------- + +class FSkyBox : public FTexture +{ +public: + + FTexture * faces[6]; + bool fliptop; + + FSkyBox(); + ~FSkyBox(); + const BYTE *GetColumn (unsigned int column, const Span **spans_out); + const BYTE *GetPixels (); + int CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf); + bool UseBasePalette(); + void Unload (); + + void SetSize() + { + if (faces[0]) + { + Width=faces[0]->GetWidth(); + Height=faces[0]->GetHeight(); + CalcBitSize(); + } + } + + bool Is3Face() const + { + return faces[5]==NULL; + } + + bool IsFlipped() const + { + return fliptop; + } +}; diff --git a/src/gl/textures/gl_texture.cpp b/src/gl/textures/gl_texture.cpp new file mode 100644 index 000000000..8aaa98ae6 --- /dev/null +++ b/src/gl/textures/gl_texture.cpp @@ -0,0 +1,762 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2004-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** Global texture data +** +*/ + +#include "gl/system/gl_system.h" +#include "c_cvars.h" +#include "w_wad.h" +#include "templates.h" +#include "colormatcher.h" +#include "r_data/r_translate.h" +#include "c_dispatch.h" +#ifdef _WIN32 +#include "win32gliface.h" +#endif +#include "v_palette.h" +#include "sc_man.h" + +#include "gl/system/gl_interface.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/textures/gl_texture.h" +#include "gl/textures/gl_material.h" +#include "gl/textures/gl_samplers.h" + +//========================================================================== +// +// Texture CVARs +// +//========================================================================== +CUSTOM_CVAR(Float,gl_texture_filter_anisotropic,8.0f,CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +{ + if (GLRenderer != NULL && GLRenderer->mSamplerManager != NULL) GLRenderer->mSamplerManager->SetTextureFilterMode(); +} + +CCMD(gl_flush) +{ + if (GLRenderer != NULL) GLRenderer->FlushTextures(); +} + +CUSTOM_CVAR(Int, gl_texture_filter, 4, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +{ + if (self < 0 || self > 6) self=4; + if (GLRenderer != NULL && GLRenderer->mSamplerManager != NULL) GLRenderer->mSamplerManager->SetTextureFilterMode(); +} + +CUSTOM_CVAR(Int, gl_texture_format, 0, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +{ + // [BB] The number of available texture modes depends on the GPU capabilities. + // RFL_TEXTURE_COMPRESSION gives us one additional mode and RFL_TEXTURE_COMPRESSION_S3TC + // another three. + int numOfAvailableTextureFormat = 4; + if ( gl.flags & RFL_TEXTURE_COMPRESSION && gl.flags & RFL_TEXTURE_COMPRESSION_S3TC ) + numOfAvailableTextureFormat = 8; + else if ( gl.flags & RFL_TEXTURE_COMPRESSION ) + numOfAvailableTextureFormat = 5; + if (self < 0 || self > numOfAvailableTextureFormat-1) self=0; + GLRenderer->FlushTextures(); +} + +CUSTOM_CVAR(Bool, gl_texture_usehires, true, CVAR_ARCHIVE|CVAR_NOINITCALL) +{ + if (GLRenderer != NULL) GLRenderer->FlushTextures(); +} + +CVAR(Bool, gl_precache, false, CVAR_ARCHIVE) + +CVAR(Bool, gl_trimsprites, true, CVAR_ARCHIVE); + +TexFilter_s TexFilter[]={ + {GL_NEAREST, GL_NEAREST, false}, + {GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST, true}, + {GL_LINEAR, GL_LINEAR, false}, + {GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR, true}, + {GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, true}, + {GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST, true}, + {GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST, true}, +}; + +int TexFormat[]={ + GL_RGBA8, + GL_RGB5_A1, + GL_RGBA4, + GL_RGBA2, + // [BB] Added compressed texture formats. + GL_COMPRESSED_RGBA_ARB, + GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, + GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, + GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, +}; + + + +bool HasGlobalBrightmap; +FRemapTable GlobalBrightmap; + +//=========================================================================== +// +// Examines the colormap to see if some of the colors have to be +// considered fullbright all the time. +// +//=========================================================================== + +void gl_GenerateGlobalBrightmapFromColormap() +{ + HasGlobalBrightmap = false; + int lump = Wads.CheckNumForName("COLORMAP"); + if (lump == -1) lump = Wads.CheckNumForName("COLORMAP", ns_colormaps); + if (lump == -1) return; + FMemLump cmap = Wads.ReadLump(lump); + FMemLump palette = Wads.ReadLump("PLAYPAL"); + const unsigned char *cmapdata = (const unsigned char *)cmap.GetMem(); + const unsigned char *paldata = (const unsigned char *)palette.GetMem(); + + const int black = 0; + const int white = ColorMatcher.Pick(255,255,255); + + + GlobalBrightmap.MakeIdentity(); + memset(GlobalBrightmap.Remap, white, 256); + for(int i=0;i<256;i++) GlobalBrightmap.Palette[i]=PalEntry(255,255,255,255); + for(int j=0;j<32;j++) + { + for(int i=0;i<256;i++) + { + // the palette comparison should be for ==0 but that gives false positives with Heretic + // and Hexen. + if (cmapdata[i+j*256]!=i || (paldata[3*i]<10 && paldata[3*i+1]<10 && paldata[3*i+2]<10)) + { + GlobalBrightmap.Remap[i]=black; + GlobalBrightmap.Palette[i] = PalEntry(255, 0, 0, 0); + } + } + } + for(int i=0;i<256;i++) + { + HasGlobalBrightmap |= GlobalBrightmap.Remap[i] == white; + if (GlobalBrightmap.Remap[i] == white) DPrintf(DMSG_NOTIFY, "Marked color %d as fullbright\n",i); + } +} + +//=========================================================================== +// +// averageColor +// input is RGBA8 pixel format. +// The resulting RGB color can be scaled uniformly so that the highest +// component becomes one. +// +//=========================================================================== +static PalEntry averageColor(const DWORD *data, int size, int maxout) +{ + int i; + unsigned int r, g, b; + + + + // First clear them. + r = g = b = 0; + if (size==0) + { + return PalEntry(255,255,255); + } + for(i = 0; i < size; i++) + { + r += BPART(data[i]); + g += GPART(data[i]); + b += RPART(data[i]); + } + + r = r/size; + g = g/size; + b = b/size; + + int maxv=MAX(MAX(r,g),b); + + if(maxv && maxout) + { + r = Scale(r, maxout, maxv); + g = Scale(g, maxout, maxv); + b = Scale(b, maxout, maxv); + } + return PalEntry(255,r,g,b); +} + + + +//========================================================================== +// +// GL status data for a texture +// +//========================================================================== + +FTexture::MiscGLInfo::MiscGLInfo() throw() +{ + bGlowing = false; + GlowColor = 0; + GlowHeight = 128; + bSkybox = false; + bFullbright = false; + bBrightmapChecked = false; + bDisableFullbright = false; + bNoFilter = false; + bNoCompress = false; + bNoExpand = false; + areas = NULL; + areacount = 0; + mIsTransparent = -1; + shaderspeed = 1.f; + shaderindex = 0; + + Material[1] = Material[0] = NULL; + SystemTexture[1] = SystemTexture[0] = NULL; + Brightmap = NULL; +} + +FTexture::MiscGLInfo::~MiscGLInfo() +{ + for (int i = 0; i < 2; i++) + { + if (Material[i] != NULL) delete Material[i]; + Material[i] = NULL; + + if (SystemTexture[i] != NULL) delete SystemTexture[i]; + SystemTexture[i] = NULL; + } + + // this is just a reference to another texture in the texture manager. + Brightmap = NULL; + + if (areas != NULL) delete [] areas; + areas = NULL; +} + +//=========================================================================== +// +// Checks if the texture has a default brightmap and creates it if so +// +//=========================================================================== +void FTexture::CreateDefaultBrightmap() +{ + if (!gl_info.bBrightmapChecked) + { + // Check for brightmaps + if (UseBasePalette() && HasGlobalBrightmap && + UseType != TEX_Decal && UseType != TEX_MiscPatch && UseType != TEX_FontChar && + gl_info.Brightmap == NULL && bWarped == 0 + ) + { + // May have one - let's check when we use this texture + const BYTE *texbuf = GetPixels(); + const int white = ColorMatcher.Pick(255,255,255); + + int size = GetWidth() * GetHeight(); + for(int i=0;iGetTextureBuffer(this, w, h); + + if (buffer) + { + gl_info.GlowColor = averageColor((DWORD *) buffer, w*h, 153); + delete[] buffer; + } + + // Black glow equals nothing so switch glowing off + if (gl_info.GlowColor == 0) gl_info.bGlowing = false; + } + data[0]=gl_info.GlowColor.r/255.0f; + data[1]=gl_info.GlowColor.g/255.0f; + data[2]=gl_info.GlowColor.b/255.0f; +} + +//=========================================================================== +// +// Finds gaps in the texture which can be skipped by the renderer +// This was mainly added to speed up one area in E4M6 of 007LTSD +// +//=========================================================================== + +bool FTexture::FindHoles(const unsigned char * buffer, int w, int h) +{ + const unsigned char * li; + int y,x; + int startdraw,lendraw; + int gaps[5][2]; + int gapc=0; + + + // already done! + if (gl_info.areacount) return false; + if (UseType == TEX_Flat) return false; // flats don't have transparent parts + gl_info.areacount=-1; //whatever happens next, it shouldn't be done twice! + + // large textures are excluded for performance reasons + if (h>512) return false; + + startdraw=-1; + lendraw=0; + for(y=0;y>24; + + if (alpha != 0xff && alpha != 0) + { + gl_info.mIsTransparent = 1; + return; + } + } + gl_info.mIsTransparent = 0; + } + } +} + + +//=========================================================================== +// +// smooth the edges of transparent fields in the texture +// +//=========================================================================== + +#ifdef WORDS_BIGENDIAN +#define MSB 0 +#define SOME_MASK 0xffffff00 +#else +#define MSB 3 +#define SOME_MASK 0x00ffffff +#endif + +#define CHKPIX(ofs) (l1[(ofs)*4+MSB]==255 ? (( ((DWORD*)l1)[0] = ((DWORD*)l1)[ofs]&SOME_MASK), trans=true ) : false) + +bool FTexture::SmoothEdges(unsigned char * buffer,int w, int h) +{ + int x,y; + bool trans=buffer[MSB]==0; // If I set this to false here the code won't detect textures + // that only contain transparent pixels. + bool semitrans = false; + unsigned char * l1; + + if (h<=1 || w<=1) return false; // makes (a) no sense and (b) doesn't work with this code! + + l1=buffer; + + + if (l1[MSB]==0 && !CHKPIX(1)) CHKPIX(w); + else if (l1[MSB]<255) semitrans=true; + l1+=4; + for(x=1;xbNoDecals; + Rotations = source->Rotations; + UseType = source->UseType; + bMasked = false; + id.SetInvalid(); + SourceLump = -1; +} + +FBrightmapTexture::~FBrightmapTexture () +{ +} + +const BYTE *FBrightmapTexture::GetColumn (unsigned int column, const Span **spans_out) +{ + // not needed + return NULL; +} + +const BYTE *FBrightmapTexture::GetPixels () +{ + // not needed + return NULL; +} + +void FBrightmapTexture::Unload () +{ +} + +int FBrightmapTexture::CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf) +{ + SourcePic->CopyTrueColorTranslated(bmp, x, y, rotate, &GlobalBrightmap); + return 0; +} + + +//========================================================================== +// +// Parses a brightmap definition +// +//========================================================================== + +void gl_ParseBrightmap(FScanner &sc, int deflump) +{ + int type = FTexture::TEX_Any; + bool disable_fullbright=false; + bool thiswad = false; + bool iwad = false; + FTexture *bmtex = NULL; + + sc.MustGetString(); + if (sc.Compare("texture")) type = FTexture::TEX_Wall; + else if (sc.Compare("flat")) type = FTexture::TEX_Flat; + else if (sc.Compare("sprite")) type = FTexture::TEX_Sprite; + else sc.UnGet(); + + sc.MustGetString(); + FTextureID no = TexMan.CheckForTexture(sc.String, type); + FTexture *tex = TexMan[no]; + + sc.MustGetToken('{'); + while (!sc.CheckToken('}')) + { + sc.MustGetString(); + if (sc.Compare("disablefullbright")) + { + // This can also be used without a brightness map to disable + // fullbright in rotations that only use brightness maps on + // other angles. + disable_fullbright = true; + } + else if (sc.Compare("thiswad")) + { + // only affects textures defined in the WAD containing the definition file. + thiswad = true; + } + else if (sc.Compare ("iwad")) + { + // only affects textures defined in the IWAD. + iwad = true; + } + else if (sc.Compare ("map")) + { + sc.MustGetString(); + + if (bmtex != NULL) + { + Printf("Multiple brightmap definitions in texture %s\n", tex? tex->Name.GetChars() : "(null)"); + } + + bmtex = TexMan.FindTexture(sc.String, FTexture::TEX_Any, FTextureManager::TEXMAN_TryAny); + + if (bmtex == NULL) + Printf("Brightmap '%s' not found in texture '%s'\n", sc.String, tex? tex->Name.GetChars() : "(null)"); + } + } + if (!tex) + { + return; + } + if (thiswad || iwad) + { + bool useme = false; + int lumpnum = tex->GetSourceLump(); + + if (lumpnum != -1) + { + if (iwad && Wads.GetLumpFile(lumpnum) <= FWadCollection::IWAD_FILENUM) useme = true; + if (thiswad && Wads.GetLumpFile(lumpnum) == deflump) useme = true; + } + if (!useme) return; + } + + if (bmtex != NULL) + { + if (tex->bWarped != 0) + { + Printf("Cannot combine warping with brightmap on texture '%s'\n", tex->Name.GetChars()); + return; + } + + bmtex->bMasked = false; + tex->gl_info.Brightmap = bmtex; + } + tex->gl_info.bDisableFullbright = disable_fullbright; +} + +//========================================================================== +// +// Parses a GLBoom+ detail texture definition +// +// Syntax is this: +// detail +// { +// (walls | flats) [default_detail_name [width [height [offset_x [offset_y]]]]] +// { +// texture_name [detail_name [width [height [offset_x [offset_y]]]]] +// } +// } +// This merely parses the block and returns no error if valid. The feature +// is not actually implemented, so nothing else happens. +//========================================================================== + +void gl_ParseDetailTexture(FScanner &sc) +{ + while (!sc.CheckToken('}')) + { + sc.MustGetString(); + if (sc.Compare("walls") || sc.Compare("flats")) + { + if (!sc.CheckToken('{')) + { + sc.MustGetString(); // Default detail texture + if (sc.CheckFloat()) // Width + if (sc.CheckFloat()) // Height + if (sc.CheckFloat()) // OffsX + if (sc.CheckFloat()) // OffsY + { + // Nothing + } + } + else sc.UnGet(); + sc.MustGetToken('{'); + while (!sc.CheckToken('}')) + { + sc.MustGetString(); // Texture + if (sc.GetString()) // Detail texture + { + if (sc.CheckFloat()) // Width + if (sc.CheckFloat()) // Height + if (sc.CheckFloat()) // OffsX + if (sc.CheckFloat()) // OffsY + { + // Nothing + } + } + else sc.UnGet(); + } + } + } +} + + +//========================================================================== +// +// Prints some texture info +// +//========================================================================== + +CCMD(textureinfo) +{ + int cntt = 0; + for (int i = 0; i < TexMan.NumTextures(); i++) + { + FTexture *tex = TexMan.ByIndex(i); + if (tex->gl_info.SystemTexture[0] || tex->gl_info.SystemTexture[1] || tex->gl_info.Material[0] || tex->gl_info.Material[1]) + { + int lump = tex->GetSourceLump(); + Printf(PRINT_LOG, "Texture '%s' (Index %d, Lump %d, Name '%s'):\n", tex->Name.GetChars(), i, lump, Wads.GetLumpFullName(lump)); + if (tex->gl_info.Material[0]) + { + Printf(PRINT_LOG, "in use (normal)\n"); + } + else if (tex->gl_info.SystemTexture[0]) + { + Printf(PRINT_LOG, "referenced (normal)\n"); + } + if (tex->gl_info.Material[1]) + { + Printf(PRINT_LOG, "in use (expanded)\n"); + } + else if (tex->gl_info.SystemTexture[1]) + { + Printf(PRINT_LOG, "referenced (normal)\n"); + } + cntt++; + } + } + Printf(PRINT_LOG, "%d system textures\n", cntt); +} + diff --git a/src/gl/textures/gl_texture.h b/src/gl/textures/gl_texture.h new file mode 100644 index 000000000..455678f85 --- /dev/null +++ b/src/gl/textures/gl_texture.h @@ -0,0 +1,35 @@ +#ifndef __GL_TEXTURE_H__ +#define __GL_TEXTURE_H__ + +#include "r_defs.h" + +class FBrightmapTexture : public FTexture +{ +public: + FBrightmapTexture (FTexture *source); + ~FBrightmapTexture (); + + const BYTE *GetColumn (unsigned int column, const Span **spans_out); + const BYTE *GetPixels (); + void Unload (); + + int CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf); + bool UseBasePalette() { return false; } + +protected: + FTexture *SourcePic; + //BYTE *Pixels; + //Span **Spans; +}; + + +void gl_GenerateGlobalBrightmapFromColormap(); + + + +unsigned char *gl_CreateUpsampledTextureBuffer ( const FTexture *inputTexture, unsigned char *inputBuffer, const int inWidth, const int inHeight, int &outWidth, int &outHeight, bool hasAlpha ); +int CheckDDPK3(FTexture *tex); +int CheckExternalFile(FTexture *tex, bool & hascolorkey); + +#endif // __GL_HQRESIZE_H__ + diff --git a/src/gl/textures/gl_translate.cpp b/src/gl/textures/gl_translate.cpp new file mode 100644 index 000000000..5a6ecbea2 --- /dev/null +++ b/src/gl/textures/gl_translate.cpp @@ -0,0 +1,75 @@ +// +//--------------------------------------------------------------------------- +// +// Copyright(C) 2007-2016 Christoph Oelckers +// All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see http://www.gnu.org/licenses/ +// +//-------------------------------------------------------------------------- +// +/* +** gl_translate.cpp +** GL-related translation stuff +** +*/ + +#include "doomtype.h" +#include "r_data/r_translate.h" +#include "gl/textures/gl_translate.h" +#include "m_crc32.h" + +TArray GLTranslationPalette::AllPalettes; + + +GLTranslationPalette *GLTranslationPalette::CreatePalette(FRemapTable *remap) +{ + GLTranslationPalette *p = new GLTranslationPalette(remap); + p->Update(); + return p; +} + +bool GLTranslationPalette::Update() +{ + PalData pd; + + memset(pd.pe, 0, sizeof(pd.pe)); + memcpy(pd.pe, remap->Palette, remap->NumEntries * sizeof(*remap->Palette)); + pd.crc32 = CalcCRC32((BYTE*)pd.pe, sizeof(pd.pe)); + for(unsigned int i=0;i< AllPalettes.Size(); i++) + { + if (pd.crc32 == AllPalettes[i].crc32) + { + if (!memcmp(pd.pe, AllPalettes[i].pe, sizeof(pd.pe))) + { + Index = 1+i; + return true; + } + } + } + Index = 1+AllPalettes.Push(pd); + return true; +} + +int GLTranslationPalette::GetInternalTranslation(int trans) +{ + if (trans <= 0) return 0; + + FRemapTable *remap = TranslationToTable(trans); + if (remap == NULL || remap->Inactive) return 0; + + GLTranslationPalette *tpal = static_cast(remap->GetNative()); + if (tpal == NULL) return 0; + return tpal->GetIndex(); +} diff --git a/src/gl/textures/gl_translate.h b/src/gl/textures/gl_translate.h new file mode 100644 index 000000000..07ede1a22 --- /dev/null +++ b/src/gl/textures/gl_translate.h @@ -0,0 +1,42 @@ +#ifndef __GL_TRANSLATE__ +#define __GL_TRANSLATE__ + +#include "doomtype.h" +#include "v_video.h" + +enum +{ + TRANSLATION_ICE = -1, + TRANSLATION_INTENSITY = -2, + TRANSLATION_SHADE = -3, +}; + + +class GLTranslationPalette : public FNativePalette +{ + struct PalData + { + int crc32; + PalEntry pe[256]; + }; + static TArray AllPalettes; + + int Index; + FRemapTable *remap; + + GLTranslationPalette(FRemapTable *r) { remap=r; Index=-1; } + +public: + + static GLTranslationPalette *CreatePalette(FRemapTable *remap); + static int GetInternalTranslation(int trans); + static PalEntry *GetPalette(unsigned int index) + { + return index > 0 && index <= AllPalettes.Size()? AllPalettes[index-1].pe : NULL; + } + bool Update(); + int GetIndex() const { return Index; } +}; + + +#endif diff --git a/src/gl/unused/gl_builddraw.cpp b/src/gl/unused/gl_builddraw.cpp new file mode 100644 index 000000000..82b93b4f3 --- /dev/null +++ b/src/gl/unused/gl_builddraw.cpp @@ -0,0 +1,598 @@ +/* +** gl_builddraw.cpp +** a build-like rendering algorithm +** Uses the sections created in gl_sections.cpp +** +** NOTE: Although this code generally works, it clearly shows the limitations +** of Build's algorithm. This requires constant sorting of the collected geometry +** and that causes extreme slowdowns on larger maps. +** +**--------------------------------------------------------------------------- +** Copyright 2008 Christoph Oelckers +** 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 author may not be used to endorse or promote products +** derived from this software without specific prior written permission. +** 4. When not used as part of GZDoom or a GZDoom derivative, this code will be +** covered by the terms of the GNU Lesser General Public License as published +** by the Free Software Foundation; either version 2.1 of the License, or (at +** your option) any later version. +** 5. Full disclosure of the entire project's source code, except for third +** party libraries is mandatory. (NOTE: This clause is non-negotiable!) +** +** 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "i_system.h" +#include "p_local.h" +#include "c_dispatch.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/scene/gl_clipper.h" +#include "gl/utility/gl_clock.h" +#include "gl/data/gl_sections.h" +#include "gl/scene/gl_wall.h" + +#ifdef BUILD_TEST +#define D(x) x +#else +#define D(x) do{}while(0) +#endif + +EXTERN_CVAR (Bool, dumpsections) + +struct FBunch +{ + int startline; + int endline; + angle_t startangle; + angle_t endangle; + fixed_t minviewdist; + fixed_t maxviewdist; +}; + +void DoSubsector(subsector_t * sub, bool handlelines); + +EXTERN_CVAR(Bool, gl_render_walls) + +//========================================================================== +// +// From Build but changed to use doubles to prevent overflows +// +//========================================================================== + +static int WallInFront(FGLSectionLine *wal1, FGLSectionLine *wal2) +{ + double x11, y11, x21, y21, x12, y12, x22, y22, dx, dy, t1, t2; + + x11 = wal1->start->x; + y11 = wal1->start->y; + x21 = wal1->end->x; + y21 = wal1->end->y; + x12 = wal2->start->x; + y12 = wal2->start->y; + x22 = wal2->end->x; + y22 = wal2->end->y; + + dx = x21-x11; dy = y21-y11; + + t1 = (x12-x11)*dy - (y12-y11)*dx; + t2 = (x22-x11)*dy - (y22-y11)*dx; + if (t1 == 0) + { + t1 = t2; + if (t1 == 0) return(-1); + } + if (t2 == 0) t2 = t1; + + if ((t1*t2) >= 0) + { + t2 = (double(viewx)-x11) * dy - (double(viewy)-y11)*dx; + return((t2*t1) < 0); + } + + dx = x22-x12; dy = y22-y12; + t1 = (x11-x12)*dy - (y11-y12)*dx; + t2 = (x21-x12)*dy - (y21-y12)*dx; + if (t1 == 0) + { + t1 = t2; + if (t1 == 0) return(-1); + } + if (t2 == 0) t2 = t1; + if ((t1*t2) >= 0) + { + t2 = (double(viewx)-x12) * dy - (double(viewy)-y12)*dx; + return((t2*t1) >= 0); + } + return(-2); +} + +//========================================================================== +// +// This is a bit more complicated than it looks because angles can wrap +// around so we can only compare angle differences. +// +// Rules: +// 1. Any bunch can span at most 180°. +// 2. 2 bunches can never overlap at both ends +// 3. if there is an overlap one of the 2 starting points must be in the +// overlapping area. +// +//========================================================================== + +static int BunchInFront(FBunch *b1, FBunch *b2) +{ + angle_t anglecheck, endang; + + if (b2->startangle - b1->startangle < b1->endangle - b1->startangle) + { + // we have an overlap at b2->startangle + anglecheck = b2->startangle - b1->startangle; + + // Find the wall in b1 that overlaps b2->startangle + for(int i = b1->startline; i <= b1->endline; i++) + { + #ifdef _DEBUG + angle_t startang = SectionLines[i].start->GetClipAngleInverse() - b1->startangle; + #endif + endang = SectionLines[i].end->GetClipAngleInverse() - b1->startangle; + if (endang > anglecheck) + { + assert (startang <= anglecheck); + + // found a line + int ret = WallInFront(&SectionLines[b2->startline], &SectionLines[i]); + + D(Printf (PRINT_LOG, "Line %d <-> line %d: Result = %d.\n", + SectionLines[b2->startline].linedef-lines, + SectionLines[i].linedef-lines, ret)); + + return ret; + } + } + } + else if (b1->startangle - b2->startangle < b2->endangle - b2->startangle) + { + // we have an overlap at b1->startangle + anglecheck = b1->startangle - b2->startangle; + + // Find the wall in b2 that overlaps b1->startangle + for(int i = b2->startline; i <= b2->endline; i++) + { + #ifdef _DEBUG + angle_t startang = SectionLines[i].start->GetClipAngleInverse() - b2->startangle; + #endif + endang = SectionLines[i].end->GetClipAngleInverse() - b2->startangle; + if (endang > anglecheck) + { + assert (startang <= anglecheck); + + // found a line + int ret = WallInFront(&SectionLines[i], &SectionLines[b1->startline]); + + D(Printf (PRINT_LOG, "Line %d <-> line %d: Result = %d,\n", + SectionLines[i].linedef-lines, + SectionLines[b1->endline].linedef-lines, ret)); + + return ret; + } + } + } + // we have no overlap + return -1; +} + + +// ---------------------------------------------------------------------------- +// +// Bunches are groups of continuous lines +// This array stores the amount of points per bunch, +// the view angles for each point and the line index for the starting line +// +// ---------------------------------------------------------------------------- + +class BunchDrawer +{ + int LastBunch; + int StartTime; + TArray Bunches; + TArray CompareData; + sector_t fakebacksec; + + //========================================================================== + // + // + // + //========================================================================== +public: + BunchDrawer() + { + StartScene(); + } + + //========================================================================== + // + // + // + //========================================================================== +private: + void StartScene() + { + LastBunch = 0; + StartTime = I_MSTime(); + Bunches.Clear(); + } + + //========================================================================== + // + // + // + //========================================================================== + + void StartBunch(int linenum, angle_t startan, angle_t endan, vertex_t *startpt, vertex_t *endpt) + { + FBunch *bunch = &Bunches[LastBunch = Bunches.Reserve(1)]; + + bunch->startline = bunch->endline = linenum; + bunch->startangle = startan; + bunch->endangle = endan; + } + + //========================================================================== + // + // + // + //========================================================================== + + void AddLineToBunch(int newan) + { + Bunches[LastBunch].endline++; + Bunches[LastBunch].endangle = newan; + } + + //========================================================================== + // + // + // + //========================================================================== + + void DeleteBunch(int index) + { + Bunches.Delete(index); + } + + //========================================================================== + // + // ClipLine + // Clips the given segment + // + //========================================================================== + + enum + { + CL_Skip = 0, + CL_Draw = 1, + CL_Pass = 2, + }; + + + int ClipLine (FGLSectionLine *line, sector_t * sector, sector_t **pbacksector) + { + angle_t startAngle, endAngle; + sector_t * backsector = NULL; + bool blocking; + + startAngle = line->end->GetClipAngle(); + endAngle = line->start->GetClipAngle(); + *pbacksector = NULL; + + // Back side, i.e. backface culling - read: endAngle >= startAngle! + if (startAngle-endAngleotherside == -1) + { + // one-sided + clipper.SafeAddClipRange(startAngle, endAngle); + return CL_Draw; + } + else if (line->polysub == NULL) + { + // two sided and not a polyobject + if (line->linedef == NULL) + { + // Miniseg + return CL_Pass; + } + if (sector->sectornum == line->refseg->backsector->sectornum) + { + FTexture *tex = TexMan(line->sidedef->GetTexture(side_t::mid)); + if (!tex || tex->UseType==FTexture::TEX_Null) + { + // no mid texture: nothing to do here + return CL_Pass; + } + *pbacksector = sector; + return CL_Draw|CL_Pass; + } + else + { + // clipping checks are only needed when the backsector is not the same as the front sector + gl_CheckViewArea(line->start, line->end, line->refseg->frontsector, line->refseg->backsector); + + *pbacksector = backsector = gl_FakeFlat(line->refseg->backsector, &fakebacksec, true); + + blocking = gl_CheckClip(line->sidedef, sector, backsector); + if (blocking) + { + clipper.SafeAddClipRange(startAngle, endAngle); + return CL_Draw; + } + return CL_Draw|CL_Pass; + } + } + else + { + *pbacksector = sector; + return CL_Draw; + } + } + + //========================================================================== + // + // + // + //========================================================================== + + void ProcessBunch(int bnch) + { + FBunch *bunch = &Bunches[bnch]; + + sector_t fake; + sector_t *sec; + sector_t *backsector; + + D(Printf(PRINT_LOG, "------------------------------\nProcessing bunch %d (Startline %d)\n",bnch,SectionLines[bunch->startline].linedef-lines)); + ClipWall.Clock(); + for(int i=bunch->startline; i <= bunch->endline; i++) + { + FGLSectionLine *ln = &SectionLines[i]; + + + // Draw this line. todo: optimize + sec = gl_FakeFlat(ln->refseg->frontsector, &fake, false); + + int clipped = ClipLine(ln, sec, &backsector); + + D(Printf(PRINT_LOG, "line %d clip result is %d\n", ln->linedef - lines, clipped)); + + if (clipped & CL_Draw) + { + ln->linedef->flags |= ML_MAPPED; + + if (ln->linedef->validcount!=validcount) + { + ln->linedef->validcount=validcount; + + #ifndef BUILD_TEST + if (gl_render_walls) + { + SetupWall.Clock(); + + GLWall wall; + wall.Process(ln->refseg, sec, backsector, ln->polysub); + rendered_lines++; + + SetupWall.Unclock(); + } + #endif + } + } + + if (clipped & CL_Pass) + { + ClipWall.Unclock(); + ProcessSection(ln->otherside); + ClipWall.Clock(); + } + } + D(Printf(PRINT_LOG, "Bunch %d done\n------------------------------\n",bnch)); + ClipWall.Unclock(); + } + + //========================================================================== + // + // + // + //========================================================================== + + int FindClosestBunch() + { + int closest = 0; //Almost works, but not quite :( + + CompareData.Clear(); + for(unsigned i = 1; i < Bunches.Size(); i++) + { + switch (BunchInFront(&Bunches[i], &Bunches[closest])) + { + case 0: // i is in front + closest = i; + continue; + + case 1: // i is behind + continue; + + default: // can't determine + CompareData.Push(i); // mark for later comparison + continue; + } + } + + // we need to do a second pass to see how the marked bunches relate to the currently closest one. + for(unsigned i = 0; i < CompareData.Size(); i++) + { + switch (BunchInFront(&Bunches[CompareData[i]], &Bunches[closest])) + { + case 0: // is in front + closest = i; + CompareData.Delete(i); + i = 0; // we need to recheck everything that's still marked. + continue; + + case 1: // is behind + CompareData.Delete(i); + i--; + continue; + + default: + continue; + + } + } + return closest; + } + + //========================================================================== + // + // + // + //========================================================================== + + void ProcessSection(int sectnum) + { + FGLSection *sect = &Sections[sectnum]; + bool inbunch; + angle_t startangle; + + if (sect->validcount == StartTime) return; + sect->validcount = StartTime; + D(Printf(PRINT_LOG, "------------------------------\nProcessing section %d (sector %d)\n",sectnum, sect->sector->sectornum)); + + #ifndef BUILD_TEST + for(unsigned i = 0; i < sect->subsectors.Size(); i++) + { + DoSubsector(sect->subsectors[i], false); + if (sect->subsectors[i]->poly != NULL) + { + // ProcessPolyobject() + } + } + #endif + + //Todo: process subsectors + for(int i=0; inumloops; i++) + { + FGLSectionLoop *loop = sect->GetLoop(i); + inbunch = false; + + for(int j=0; jnumlines; j++) + { + FGLSectionLine *ln = loop->GetLine(j); + + angle_t ang1 = ln->start->GetClipAngle(); + angle_t ang2 = ln->end->GetClipAngle(); + + if (ang2 - ang1 < ANGLE_180) + { + // Backside + D(Printf(PRINT_LOG, "line %d facing backwards\n", ln->linedef - lines)); + inbunch = false; + } + else if (!clipper.SafeCheckRange(ang2, ang1)) + { + // is it visible? + D(Printf(PRINT_LOG, "line %d not in view\n", ln->linedef - lines)); + inbunch = false; + } + else if (!inbunch || startangle - ang2 >= ANGLE_180) + { + // don't let a bunch span more than 180° to avoid problems. + // This limitation ensures that the combined range of 2 + // bunches will always be less than 360° which simplifies + // the distance comparison code because it prevents a + // situation where 2 bunches may overlap at both ends. + D(Printf(PRINT_LOG, "Starting bunch %d at line %d\n",Bunches.Size(), ln->linedef - lines)); + + startangle = ang2; + // Clipping angles are backward which makes this code very hard to read so let's use the inverse + StartBunch(loop->startline + j, 0 - ang1, 0 - ang2); + inbunch = true; + } + else + { + D(Printf(PRINT_LOG, " Adding line %d\n", ln->linedef - lines)); + AddLineToBunch(0 - ang2); + } + } + } + D(Printf(PRINT_LOG, "Section %d done\n------------------------------\n",sectnum)); + } + + //========================================================================== + // + // + // + //========================================================================== + +public: + void RenderScene(int viewsection) + { + ProcessSection(viewsection); + while (Bunches.Size() > 0) + { + int closest = FindClosestBunch(); + ProcessBunch(closest); + DeleteBunch(closest); + } + } +}; + + +void gl_RenderBuild() +{ + subsector_t *sub = R_PointInSubsector(viewx, viewy); + + clipper.Clear(); + angle_t a1 = GLRenderer->FrustumAngle(); + clipper.SafeAddClipRangeRealAngles(viewangle+a1, viewangle-a1); + if (Sections.Size() == 0) gl_CreateSections(); + + int startsection = SectionForSubsector[sub-subsectors]; + + BunchDrawer bd; + bd.RenderScene(startsection); +} + +#ifdef BUILD_TEST +CCMD(testrender) +{ + gl_RenderBuild(); +} +#endif diff --git a/src/gl/unused/gl_sections.cpp b/src/gl/unused/gl_sections.cpp new file mode 100644 index 000000000..34858bd3a --- /dev/null +++ b/src/gl/unused/gl_sections.cpp @@ -0,0 +1,845 @@ +/* +** gl_sections.cpp +** Splits sectors into continuous separate parts +** +**--------------------------------------------------------------------------- +** Copyright 2008 Christoph Oelckers +** 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 author may not be used to endorse or promote products +** derived from this software without specific prior written permission. +** 4. When not used as part of GZDoom or a GZDoom derivative, this code will be +** covered by the terms of the GNU Lesser General Public License as published +** by the Free Software Foundation; either version 2.1 of the License, or (at +** your option) any later version. +** 5. Full disclosure of the entire project's source code, except for third +** party libraries is mandatory. (NOTE: This clause is non-negotiable!) +** +** 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. +**--------------------------------------------------------------------------- +** +*/ + +#include "gl/system/gl_system.h" +#include +#include "i_system.h" +#include "p_local.h" +#include "c_dispatch.h" +#include "gl/data/gl_sections.h" + +typedef void (CALLBACK *tessFunc)(); + +TArray SectionLines; +TArray SectionLoops; +TArray Sections; +TArray SectionForSubsector; + +CVAR (Bool, dumpsections, false, 0) + +#define ISDONE(no, p) (p[(no)>>3] & (1 << ((no)&7))) +#define SETDONE(no, p) p[(no)>>3] |= (1 << ((no)&7)) + +inline vertex_t *V1(side_t *s) +{ + line_t *ln = s->linedef; + return s == ln->sidedef[0]? ln->v1: ln->v2; +} + +inline vertex_t *V2(side_t *s) +{ + line_t *ln = s->linedef; + return s == ln->sidedef[0]? ln->v2: ln->v1; +} + +//========================================================================== +// +// +// +//========================================================================== + +class FSectionCreator +{ + static FSectionCreator *creator; + + BYTE *processed_segs; + BYTE *processed_subsectors; + int *section_for_segs; + + vertex_t *v1_l1, *v2_l1; + + FGLSectionLoop *loop; + FGLSection *section; // current working section + +public: + //========================================================================== + // + // + // + //========================================================================== + + FSectionCreator() + { + processed_segs = new BYTE[(numsegs+7)/8]; + processed_subsectors = new BYTE[(numsubsectors+7)/8]; + + memset(processed_segs, 0, (numsegs+7)/8); + memset(processed_subsectors, 0, (numsubsectors+7)/8); + + section_for_segs = new int[numsegs]; + memset(section_for_segs, -1, numsegs * sizeof(int)); + } + + //========================================================================== + // + // + // + //========================================================================== + + ~FSectionCreator() + { + delete [] processed_segs; + delete [] processed_subsectors; + delete [] section_for_segs; + } + + //========================================================================== + // + // + // + //========================================================================== + + void NewLoop() + { + section->numloops++; + loop = &SectionLoops[SectionLoops.Reserve(1)]; + loop->startline = SectionLines.Size(); + loop->numlines = 0 ; + } + + void NewSection(sector_t *sec) + { + section = &Sections[Sections.Reserve(1)]; + section->sector = sec; + section->subsectors.Clear(); + section->numloops = 0; + section->startloop = SectionLoops.Size(); + section->validcount = -1; + NewLoop(); + } + + void FinalizeSection() + { + } + + //========================================================================== + // + // + // + //========================================================================== + + bool AddSeg(seg_t *seg) + { + FGLSectionLine &line = SectionLines[SectionLines.Reserve(1)]; + + + bool firstline = loop->numlines == 0; + + if (ISDONE(seg-segs, processed_segs)) + { + // should never happen! + DPrintf("Tried to add seg %d to Sections twice. Cannot create Sections.\n", seg-segs); + return false; + } + + SETDONE(seg-segs, processed_segs); + section_for_segs[seg-segs] = Sections.Size()-1; + + line.start = seg->v1; + line.end = seg->v2; + line.sidedef = seg->sidedef; + line.linedef = seg->linedef; + line.refseg = seg; + line.polysub = NULL; + line.otherside = -1; + + if (loop->numlines == 0) + { + v1_l1 = seg->v1; + v2_l1 = seg->v2; + } + loop->numlines++; + return true; + } + + //========================================================================== + // + // Utility stuff + // + //========================================================================== + + sector_t *FrontRenderSector(seg_t *seg) + { + return seg->Subsector->render_sector; + } + + sector_t *BackRenderSector(seg_t *seg) + { + if (seg->PartnerSeg == NULL) return NULL; + return seg->PartnerSeg->Subsector->render_sector; + } + + bool IntraSectorSeg(seg_t *seg) + { + return FrontRenderSector(seg) == BackRenderSector(seg); + } + + + //========================================================================== + // + // returns the seg whose partner seg determines where this + // section continues + // + //========================================================================== + bool AddSubSector(subsector_t *subsec, vertex_t *startpt, seg_t **pNextSeg) + { + unsigned i = 0; + if (startpt != NULL) + { + // find the seg in this subsector that starts at the given vertex + for(i = 0; i < subsec->numlines; i++) + { + if (subsec->firstline[i].v1 == startpt) break; + } + if (i == subsec->numlines) + { + DPrintf("Vertex not found in subsector %d. Cannot create Sections.\n", subsec-subsectors); + return false; // Nodes are bad + } + } + else + { + // Find the first unprocessed non-miniseg + for(i = 0; i < subsec->numlines; i++) + { + seg_t *seg = subsec->firstline + i; + + if (seg->sidedef == NULL) continue; + if (IntraSectorSeg(seg)) continue; + if (ISDONE(seg-segs, processed_segs)) continue; + break; + } + if (i == subsec->numlines) + { + DPrintf("Unable to find a start seg. Cannot create Sections.\n"); + return false; // Nodes are bad + } + + startpt = subsec->firstline[i].v1; + } + + seg_t *thisseg = subsec->firstline + i; + if (IntraSectorSeg(thisseg)) + { + SETDONE(thisseg-segs, processed_segs); + // continue with the loop in the adjoining subsector + *pNextSeg = thisseg; + return true; + } + + while(1) + { + if (loop->numlines > 0 && thisseg->v1 == v1_l1 && thisseg->v2 == v2_l1) + { + // This loop is complete + *pNextSeg = NULL; + return true; + } + + if (!AddSeg(thisseg)) return NULL; + + i = (i+1) % subsec->numlines; + seg_t *nextseg = subsec->firstline + i; + + if (thisseg->v2 != nextseg->v1) + { + DPrintf("Segs in subsector %d are not continuous. Cannot create Sections.\n", subsec-subsectors); + return false; // Nodes are bad + } + + if (IntraSectorSeg(nextseg)) + { + SETDONE(nextseg-segs, processed_segs); + // continue with the loop in the adjoining subsector + *pNextSeg = nextseg; + return true; + } + thisseg = nextseg; + } + } + + //============================================================================= + // + // + // + //============================================================================= + + bool FindNextSeg(seg_t **pSeg) + { + // find an unprocessed non-miniseg or a miniseg with an unprocessed + // partner subsector that belongs to the same rendersector + for (unsigned i = 0; i < section->subsectors.Size(); i++) + { + for(unsigned j = 0; j < section->subsectors[i]->numlines; j++) + { + seg_t *seg = section->subsectors[i]->firstline + j; + bool intra = IntraSectorSeg(seg); + + if (!intra && !ISDONE(seg-segs, processed_segs)) + { + *pSeg = seg; + return true; + } + else if (intra && + !ISDONE(seg->PartnerSeg->Subsector-subsectors, processed_subsectors)) + { + *pSeg = seg->PartnerSeg; + return true; + } + } + } + *pSeg = NULL; + return true; + } + + //============================================================================= + // + // all segs and subsectors must be grouped into Sections + // + //============================================================================= + bool CheckSections() + { + bool res = true; + for (int i = 0; i < numsegs; i++) + { + if (segs[i].sidedef != NULL && !ISDONE(i, processed_segs) && !IntraSectorSeg(&segs[i])) + { + Printf("Seg %d (Linedef %d) not processed during section creation\n", i, segs[i].linedef-lines); + res = false; + } + } + for (int i = 0; i < numsubsectors; i++) + { + if (!ISDONE(i, processed_subsectors)) + { + Printf("Subsector %d (Sector %d) not processed during section creation\n", i, subsectors[i].sector-sectors); + res = false; + } + } + return res; + } + + //============================================================================= + // + // + // + //============================================================================= + void DeleteLine(int i) + { + SectionLines.Delete(i); + for(int i = SectionLoops.Size() - 1; i >= 0; i--) + { + FGLSectionLoop *loop = &SectionLoops[i]; + if (loop->startline > i) loop->startline--; + } + } + + //============================================================================= + // + // + // + //============================================================================= + void MergeLines(FGLSectionLoop *loop) + { + int i; + int deleted = 0; + FGLSectionLine *ln1; + FGLSectionLine *ln2; + // Merge identical lines in the list + for(i = loop->numlines - 1; i > 0; i--) + { + ln1 = loop->GetLine(i); + ln2 = loop->GetLine(i-1); + + if (ln1->sidedef == ln2->sidedef && ln1->otherside == ln2->otherside) + { + // identical references. These 2 lines can be merged. + ln2->end = ln1->end; + SectionLines.Delete(loop->startline + i); + loop->numlines--; + deleted++; + } + } + + // If we started in the middle of a sidedef the first and last lines + // may reference the same sidedef. check that, too. + + int loopstart = 0; + + ln1 = loop->GetLine(0); + for(i = loop->numlines - 1; i > 0; i--) + { + ln2 = loop->GetLine(i); + if (ln1->sidedef != ln2->sidedef || ln1->otherside != ln2->otherside) + break; + } + if (i < loop->numlines-1) + { + i++; + ln2 = loop->GetLine(i); + ln1->start = ln2->start; + SectionLines.Delete(loop->startline + i, loop->numlines - i); + deleted += loop->numlines - i; + loop->numlines = i; + } + + // Adjust all following loops + for(unsigned ii = unsigned(loop - &SectionLoops[0]) + 1; ii < SectionLoops.Size(); ii++) + { + SectionLoops[ii].startline -= deleted; + } + } + + //============================================================================= + // + // + // + //============================================================================= + void SetReferences() + { + for(unsigned i = 0; i < SectionLines.Size(); i++) + { + FGLSectionLine *ln = &SectionLines[i]; + seg_t *seg = ln->refseg; + + if (seg != NULL) + { + seg_t *partner = seg->PartnerSeg; + + if (seg->PartnerSeg == NULL) + { + ln->otherside = -1; + } + else + { + ln->otherside = section_for_segs[partner-segs]; + } + } + else + { + ln->otherside = -1; + } + } + + for(unsigned i = 0; i < SectionLoops.Size(); i++) + { + MergeLines(&SectionLoops[i]); + } + } + + //============================================================================= + // + // cbTessBegin + // + // called when the tesselation of a new loop starts + // + //============================================================================= + + static void CALLBACK cbTessBegin(GLenum type, void *section) + { + FGLSection *sect = (FGLSection*)section; + sect->primitives.Push(type); + sect->primitives.Push(sect->vertices.Size()); + } + + //============================================================================= + // + // cbTessError + // + // called when the tesselation failed + // + //============================================================================= + + static void CALLBACK cbTessError(GLenum error, void *section) + { + } + + //============================================================================= + // + // cbTessCombine + // + // called when the two or more vertexes are on the same coordinate + // + //============================================================================= + + static void CALLBACK cbTessCombine( GLdouble coords[3], void *vert[4], GLfloat w[4], void **dataOut ) + { + *dataOut = vert[0]; + } + + //============================================================================= + // + // cbTessVertex + // + // called when a vertex is found + // + //============================================================================= + + static void CALLBACK cbTessVertex( void *vert, void *section ) + { + FGLSection *sect = (FGLSection*)section; + sect->vertices.Push(int(intptr_t(vert))); + } + + //============================================================================= + // + // cbTessEnd + // + // called when the tesselation of a the current loop ends + // + //============================================================================= + + static void CALLBACK cbTessEnd(void *section) + { + } + + //============================================================================= + // + // + // + //============================================================================= + void tesselateSections() + { + // init tesselator + GLUtesselator *tess = gluNewTess(); + if (!tess) + { + return; + } + // set callbacks + gluTessCallback(tess, GLU_TESS_BEGIN_DATA, (tessFunc)cbTessBegin); + gluTessCallback(tess, GLU_TESS_VERTEX_DATA, (tessFunc)cbTessVertex); + gluTessCallback(tess, GLU_TESS_ERROR_DATA, (tessFunc)cbTessError); + gluTessCallback(tess, GLU_TESS_COMBINE, (tessFunc)cbTessCombine); + gluTessCallback(tess, GLU_TESS_END_DATA, (tessFunc)cbTessEnd); + + for(unsigned int i=0;inumloops; j++) + { + gluTessBeginContour(tess); + FGLSectionLoop *loop = sect->GetLoop(j); + for(int k=0; knumlines; k++) + { + FGLSectionLine *line = loop->GetLine(k); + vertex_t *vert = line->start; + GLdouble v[3] = { + -(double)vert->x/(double)FRACUNIT, // negate to get proper winding + 0.0, + (double)vert->y/(double)FRACUNIT + }; + gluTessVertex(tess, v, (void*)(vert - vertexes)); + } + gluTessEndContour(tess); + } + gluTessEndPolygon(tess); + sect->vertices.Push(-1337); + sect->vertices.ShrinkToFit(); + } + gluDeleteTess(tess); + } + + + //============================================================================= + // + // First mark all subsectors that have no outside boundaries as processed + // No line in such a subsector will ever be part of a section's border + // + //============================================================================= + + void MarkInternalSubsectors() + { + for(int i=0; i < numsubsectors; i++) + { + subsector_t *sub = &subsectors[i]; + int j; + + for(j=0; j < sub->numlines; j++) + { + seg_t *seg = sub->firstline + j; + if (!IntraSectorSeg(seg)) break; + } + if (j==sub->numlines) + { + // All lines are intra-sector so mark this as processed + SETDONE(i, processed_subsectors); + for(j=0; j < sub->numlines; j++) + { + seg_t *seg = sub->firstline + j; + SETDONE((sub->firstline-segs)+j, processed_segs); + if (seg->PartnerSeg != NULL) + { + SETDONE(int(seg->PartnerSeg - segs), processed_segs); + } + } + } + } + } + + //============================================================================= + // + // + // + //============================================================================= + bool CreateSections() + { + int pick = 0; + + MarkInternalSubsectors(); + while (pick < numsubsectors) + { + if (ISDONE(pick, processed_subsectors)) + { + pick++; + continue; + } + + + subsector_t *subsector = &subsectors[pick]; + + seg_t *workseg = NULL; + vertex_t *startpt = NULL; + + NewSection(subsector->render_sector); + while (1) + { + if (!ISDONE(subsector-subsectors, processed_subsectors)) + { + SETDONE(subsector-subsectors, processed_subsectors); + section->subsectors.Push(subsector); + SectionForSubsector[subsector - subsectors] = int(section - &Sections[0]); + } + + bool result = AddSubSector(subsector, startpt, &workseg); + + if (!result) + { + return false; // couldn't create Sections + } + else if (workseg != NULL) + { + // crossing into another subsector + seg_t *partner = workseg->PartnerSeg; + if (workseg->v2 != partner->v1) + { + DPrintf("Inconsistent subsector references in seg %d. Cannot create Sections.\n", workseg-segs); + return false; + } + subsector = partner->Subsector; + startpt = workseg->v1; + } + else + { + // loop complete. Check adjoining subsectors for other loops to + // be added to this section + if (!FindNextSeg(&workseg)) + { + return false; + } + else if (workseg == NULL) + { + // No more subsectors found. This section is complete! + FinalizeSection(); + break; + } + else + { + subsector = workseg->Subsector; + // If this is a regular seg, start there, otherwise start + // at the subsector's first seg + startpt = workseg->sidedef == NULL? NULL : workseg->v1; + + NewLoop(); + } + } + } + } + + if (!CheckSections()) return false; + SetReferences(); + + Sections.ShrinkToFit(); + SectionLoops.ShrinkToFit(); + SectionLines.ShrinkToFit(); + + tesselateSections(); + + return true; + } +}; + +FSectionCreator *FSectionCreator::creator; + + +//============================================================================= +// +// +// +//============================================================================= + +void DumpSection(int no, FGLSection *sect) +{ + Printf(PRINT_LOG, "Section %d, sector %d\n{\n", no, sect->sector->sectornum); + + for(int i = 0; i < sect->numloops; i++) + { + Printf(PRINT_LOG, "\tLoop %d\n\t{\n", i); + + FGLSectionLoop *loop = sect->GetLoop(i); + + for(int i = 0; i < loop->numlines; i++) + { + FGLSectionLine *ln = loop->GetLine(i); + if (ln->sidedef != NULL) + { + vertex_t *v1 = V1(ln->sidedef); + vertex_t *v2 = V2(ln->sidedef); + double dx = FIXED2DBL(v2->x-v1->x); + double dy = FIXED2DBL(v2->y-v1->y); + double dx1 = FIXED2DBL(ln->start->x-v1->x); + double dy1 = FIXED2DBL(ln->start->y-v1->y); + double dx2 = FIXED2DBL(ln->end->x-v1->x); + double dy2 = FIXED2DBL(ln->end->y-v1->y); + double d = sqrt(dx*dx+dy*dy); + double d1 = sqrt(dx1*dx1+dy1*dy1); + double d2 = sqrt(dx2*dx2+dy2*dy2); + + Printf(PRINT_LOG, "\t\tLinedef %d, %s: Start (%1.2f, %1.2f), End (%1.2f, %1.2f)", + ln->linedef - lines, ln->sidedef == ln->linedef->sidedef[0]? "front":"back", + ln->start->x/65536.f, ln->start->y/65536.f, + ln->end->x/65536.f, ln->end->y/65536.f); + + if (ln->otherside != -1) + { + Printf (PRINT_LOG, ", other side = %d", ln->otherside); + } + if (d1 > 0.005 || d2 < 0.995) + { + Printf(PRINT_LOG, ", Range = %1.3f, %1.3f", d1/d, d2/d); + } + } + else + { + Printf(PRINT_LOG, "\t\tMiniseg: Start (%1.3f, %1.3f), End (%1.3f, %1.3f)\n", + ln->start->x/65536.f, ln->start->y/65536.f, ln->end->x/65536.f, ln->end->y/65536.f); + + if (ln->otherside != -1) + { + Printf (PRINT_LOG, ", other side = %d", ln->otherside); + } + } + Printf(PRINT_LOG, "\n"); + } + Printf(PRINT_LOG, "\t}\n"); + } + int prim = 1; + for(unsigned i = 0; i < sect->vertices.Size(); i++) + { + int v = sect->vertices[i]; + if (v < 0) + { + if (i > 0) + { + Printf(PRINT_LOG, "\t}\n"); + } + switch (v) + { + case -GL_TRIANGLE_FAN: + Printf(PRINT_LOG, "\t%d: Triangle fan\n\t{\n", prim); + break; + + case -GL_TRIANGLE_STRIP: + Printf(PRINT_LOG, "\t%d: Triangle strip\n\t{\n", prim); + break; + + case -GL_TRIANGLES: + Printf(PRINT_LOG, "\t%d: Triangles\n\t{\n", prim); + break; + + default: + break; + } + prim++; + } + else + { + Printf(PRINT_LOG, "\t\tVertex %d: (%1.2f, %1.2f)\n", + v, vertexes[v].x/65536.f, vertexes[v].y/65536.f); + } + } + Printf(PRINT_LOG, "}\n\n"); +} + +//============================================================================= +// +// +// +//============================================================================= + +void DumpSections() +{ + for(unsigned i = 0; i < Sections.Size(); i++) + { + DumpSection(i, &Sections[i]); + } +} + +//============================================================================= +// +// +// +//============================================================================= + +void gl_CreateSections() +{ + SectionLines.Clear(); + SectionLoops.Clear(); + Sections.Clear(); + SectionForSubsector.Resize(numsubsectors); + memset(&SectionForSubsector[0], -1, numsubsectors * sizeof(SectionForSubsector[0])); + FSectionCreator creat; + creat.CreateSections(); + if (dumpsections) DumpSections(); +} + diff --git a/src/gl/unused/gl_sections.h b/src/gl/unused/gl_sections.h new file mode 100644 index 000000000..1974fab46 --- /dev/null +++ b/src/gl/unused/gl_sections.h @@ -0,0 +1,57 @@ + +#ifndef __GL_SECTIONS_H +#define __GL_SECTIONS_H + +#include "tarray.h" +#include "r_defs.h" + +struct FGLSectionLine +{ + vertex_t *start; + vertex_t *end; + side_t *sidedef; + line_t *linedef; + seg_t *refseg; // we need to reference at least one seg for each line. + subsector_t *polysub; // If this is part of a polyobject we need a reference to the containing subsector + int otherside; +}; + +struct FGLSectionLoop +{ + int startline; + int numlines; + + FGLSectionLine *GetLine(int no); +}; + +struct FGLSection +{ + sector_t *sector; + TArray subsectors; + TArray primitives; // each primitive has 2 entries: Primitive type and vertex count + TArray vertices; + int startloop; + int numloops; + int validcount; + + FGLSectionLoop *GetLoop(int no); +}; + +extern TArray SectionLines; +extern TArray SectionLoops; +extern TArray Sections; +extern TArray SectionForSubsector; + +inline FGLSectionLine *FGLSectionLoop::GetLine(int no) +{ + return &SectionLines[startline + no]; +} + +inline FGLSectionLoop *FGLSection::GetLoop(int no) +{ + return &SectionLoops[startloop + no]; +} + +void gl_CreateSections(); + +#endif \ No newline at end of file diff --git a/src/gl/utility/gl_clock.cpp b/src/gl/utility/gl_clock.cpp new file mode 100644 index 000000000..0dc9fd76c --- /dev/null +++ b/src/gl/utility/gl_clock.cpp @@ -0,0 +1,267 @@ +/* +** +** This is a copy of the regular cycle_t from a time when that was based +** on QueryPerformanceCounter which is too costly for real-time profiling. +** +**--------------------------------------------------------------------------- +** Copyright 1998-2016 Randy Heit +** Copyright 2007-2016 Christoph Oelckers +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include + +#define USE_WINDOWS_DWORD +#endif + +#include "i_system.h" +#include "g_level.h" +#include "c_console.h" +#include "c_dispatch.h" +#include "r_utility.h" +#include "v_video.h" +#include "gl/utility/gl_clock.h" +#include "gl/utility/gl_convert.h" + + +glcycle_t RenderWall,SetupWall,ClipWall; +glcycle_t RenderFlat,SetupFlat; +glcycle_t RenderSprite,SetupSprite; +glcycle_t All, Finish, PortalAll, Bsp; +glcycle_t ProcessAll; +glcycle_t RenderAll; +glcycle_t Dirty; +glcycle_t drawcalls; +int vertexcount, flatvertices, flatprimitives; + +int rendered_lines,rendered_flats,rendered_sprites,render_vertexsplit,render_texsplit,rendered_decals, rendered_portals; +int iter_dlightf, iter_dlight, draw_dlight, draw_dlightf; + +double gl_SecondsPerCycle = 1e-8; +double gl_MillisecPerCycle = 1e-5; // 100 MHz + +// For GL timing the performance counter is far too costly so we still need RDTSC +// even though it may not be perfect. + +void gl_CalculateCPUSpeed () +{ + #ifdef WIN32 + LARGE_INTEGER freq; + + QueryPerformanceFrequency (&freq); + + if (freq.QuadPart != 0) + { + LARGE_INTEGER count1, count2; + unsigned minDiff; + long long ClockCalibration = 0; + + // Count cycles for at least 55 milliseconds. + // The performance counter is very low resolution compared to CPU + // speeds today, so the longer we count, the more accurate our estimate. + // On the other hand, we don't want to count too long, because we don't + // want the user to notice us spend time here, since most users will + // probably never use the performance statistics. + minDiff = freq.LowPart * 11 / 200; + + // Minimize the chance of task switching during the testing by going very + // high priority. This is another reason to avoid timing for too long. + SetPriorityClass (GetCurrentProcess (), REALTIME_PRIORITY_CLASS); + SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL); + ClockCalibration = __rdtsc(); + QueryPerformanceCounter (&count1); + do + { + QueryPerformanceCounter (&count2); + } while ((DWORD)((unsigned __int64)count2.QuadPart - (unsigned __int64)count1.QuadPart) < minDiff); + ClockCalibration = __rdtsc() - ClockCalibration; + QueryPerformanceCounter (&count2); + SetPriorityClass (GetCurrentProcess (), NORMAL_PRIORITY_CLASS); + SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_NORMAL); + + double CyclesPerSecond = (double)ClockCalibration * + (double)freq.QuadPart / + (double)((__int64)count2.QuadPart - (__int64)count1.QuadPart); + gl_SecondsPerCycle = 1.0 / CyclesPerSecond; + gl_MillisecPerCycle = 1000.0 / CyclesPerSecond; + } + #endif +} + + +void ResetProfilingData() +{ + All.Reset(); + All.Clock(); + Bsp.Reset(); + PortalAll.Reset(); + RenderAll.Reset(); + ProcessAll.Reset(); + RenderWall.Reset(); + SetupWall.Reset(); + ClipWall.Reset(); + RenderFlat.Reset(); + SetupFlat.Reset(); + RenderSprite.Reset(); + SetupSprite.Reset(); + drawcalls.Reset(); + + flatvertices=flatprimitives=vertexcount=0; + render_texsplit=render_vertexsplit=rendered_lines=rendered_flats=rendered_sprites=rendered_decals=rendered_portals = 0; +} + +//----------------------------------------------------------------------------- +// +// Rendering statistics +// +//----------------------------------------------------------------------------- + +static void AppendRenderTimes(FString &str) +{ + double setupwall = SetupWall.TimeMS(); + double clipwall = ClipWall.TimeMS() - SetupWall.TimeMS(); + double bsp = Bsp.TimeMS() - ClipWall.TimeMS() - SetupFlat.TimeMS() - SetupSprite.TimeMS(); + + str.AppendFormat("W: Render=%2.3f, Setup=%2.3f, Clip=%2.3f\n" + "F: Render=%2.3f, Setup=%2.3f\n" + "S: Render=%2.3f, Setup=%2.3f\n" + "All=%2.3f, Render=%2.3f, Setup=%2.3f, BSP = %2.3f, Portal=%2.3f, Drawcalls=%2.3f, Finish=%2.3f\n", + RenderWall.TimeMS(), setupwall, clipwall, RenderFlat.TimeMS(), SetupFlat.TimeMS(), + RenderSprite.TimeMS(), SetupSprite.TimeMS(), All.TimeMS() + Finish.TimeMS(), RenderAll.TimeMS(), + ProcessAll.TimeMS(), bsp, PortalAll.TimeMS(), drawcalls.TimeMS(), Finish.TimeMS()); +} + +static void AppendRenderStats(FString &out) +{ + out.AppendFormat("Walls: %d (%d splits, %d t-splits, %d vertices)\n" + "Flats: %d (%d primitives, %d vertices)\n" + "Sprites: %d, Decals=%d, Portals: %d\n", + rendered_lines, render_vertexsplit, render_texsplit, vertexcount, rendered_flats, flatprimitives, flatvertices, rendered_sprites,rendered_decals, rendered_portals ); +} + +static void AppendLightStats(FString &out) +{ + out.AppendFormat("DLight - Walls: %d processed, %d rendered - Flats: %d processed, %d rendered\n", + iter_dlight, draw_dlight, iter_dlightf, draw_dlightf ); +} + +ADD_STAT(rendertimes) +{ + static FString buff; + static int lasttime=0; + int t=I_FPSTime(); + if (t-lasttime>1000) + { + buff.Truncate(0); + AppendRenderTimes(buff); + lasttime=t; + } + return buff; +} + +ADD_STAT(renderstats) +{ + FString out; + AppendRenderStats(out); + return out; +} + +ADD_STAT(lightstats) +{ + FString out; + AppendLightStats(out); + return out; +} + +void AppendMissingTextureStats(FString &out); + + +static int printstats; +static bool switchfps; +static unsigned int waitstart; +EXTERN_CVAR(Bool, vid_fps) + +void CheckBench() +{ + if (printstats && ConsoleState == c_up) + { + // if we started the FPS counter ourselves or ran from the console + // we need to wait for it to stabilize before using it. + if (waitstart > 0 && I_MSTime() < waitstart + 5000) return; + + FString compose; + + compose.Format("Map %s: \"%s\",\nx = %1.4f, y = %1.4f, z = %1.4f, angle = %1.4f, pitch = %1.4f\n", + level.MapName.GetChars(), level.LevelName.GetChars(), ViewPos.X, ViewPos.Y, ViewPos.Z, ViewAngle.Degrees, ViewPitch.Degrees); + + AppendRenderStats(compose); + AppendRenderTimes(compose); + AppendLightStats(compose); + AppendMissingTextureStats(compose); + compose.AppendFormat("%d fps\n\n", screen->GetLastFPS()); + + FILE *f = fopen("benchmarks.txt", "at"); + if (f != NULL) + { + fputs(compose.GetChars(), f); + fclose(f); + } + Printf("Benchmark info saved\n"); + if (switchfps) vid_fps = false; + printstats = false; + } +} + +CCMD(bench) +{ + printstats = true; + if (vid_fps == 0) + { + vid_fps = 1; + waitstart = I_MSTime(); + switchfps = true; + } + else + { + if (ConsoleState == c_up) waitstart = I_MSTime(); + switchfps = false; + } + C_HideConsole (); +} + +bool gl_benching = false; + +void checkBenchActive() +{ + FStat *stat = FStat::FindStat("rendertimes"); + gl_benching = ((stat != NULL && stat->isActive()) || printstats); +} + diff --git a/src/gl/utility/gl_clock.h b/src/gl/utility/gl_clock.h new file mode 100644 index 000000000..4d5163d86 --- /dev/null +++ b/src/gl/utility/gl_clock.h @@ -0,0 +1,125 @@ +#ifndef __GL_CLOCK_H +#define __GL_CLOCK_H + +#include "stats.h" +#include "x86.h" +#include "m_fixed.h" + +extern bool gl_benching; + +#ifdef _MSC_VER + +extern double gl_SecondsPerCycle; +extern double gl_MillisecPerCycle; + +__forceinline long long GetClockCycle () +{ +#if _M_X64 + return __rdtsc(); +#else + return CPU.bRDTSC ? __rdtsc() : 0; +#endif +} + +#elif defined(__GNUG__) && defined(__i386__) + +extern double gl_SecondsPerCycle; +extern double gl_MillisecPerCycle; + +inline long long GetClockCycle() +{ + if (CPU.bRDTSC) + { + long long res; + asm volatile ("rdtsc" : "=A" (res)); + return res; + } + else + { + return 0; + } +} + +#else + +extern double gl_SecondsPerCycle; +extern double gl_MillisecPerCycle; + +inline long long GetClockCycle () +{ + return 0; +} +#endif + +#if defined (__APPLE__) + +typedef cycle_t glcycle_t; + +#else // !__APPLE__ + +class glcycle_t +{ +public: + glcycle_t &operator= (const glcycle_t &o) + { + Counter = o.Counter; + return *this; + } + + void Reset() + { + Counter = 0; + } + + __forceinline void Clock() + { + // Not using QueryPerformanceCounter directly, so we don't need + // to pull in the Windows headers for every single file that + // wants to do some profiling. + long long time = (gl_benching? GetClockCycle() : 0); + Counter -= time; + } + + __forceinline void Unclock() + { + long long time = (gl_benching? GetClockCycle() : 0); + Counter += time; + } + + double Time() + { + return double(Counter) * gl_SecondsPerCycle; + } + + double TimeMS() + { + return double(Counter) * gl_MillisecPerCycle; + } + +private: + long long Counter; +}; + +#endif // __APPLE__ + +extern glcycle_t RenderWall,SetupWall,ClipWall; +extern glcycle_t RenderFlat,SetupFlat; +extern glcycle_t RenderSprite,SetupSprite; +extern glcycle_t All, Finish, PortalAll, Bsp; +extern glcycle_t ProcessAll; +extern glcycle_t RenderAll; +extern glcycle_t Dirty; +extern glcycle_t drawcalls; + +extern int iter_dlightf, iter_dlight, draw_dlight, draw_dlightf; +extern int rendered_lines,rendered_flats,rendered_sprites,rendered_decals,render_vertexsplit,render_texsplit; +extern int rendered_portals; + +extern int vertexcount, flatvertices, flatprimitives; + +void ResetProfilingData(); +void CheckBench(); +void checkBenchActive(); + + +#endif \ No newline at end of file diff --git a/src/gl/utility/gl_convert.h b/src/gl/utility/gl_convert.h new file mode 100644 index 000000000..61eede6b4 --- /dev/null +++ b/src/gl/utility/gl_convert.h @@ -0,0 +1,7 @@ + +#ifndef __GLC_CONVERT +#define __GLC_CONVERT + +#include "m_fixed.h" + +#endif \ No newline at end of file diff --git a/src/gl/utility/gl_cycler.cpp b/src/gl/utility/gl_cycler.cpp new file mode 100644 index 000000000..d79770bf3 --- /dev/null +++ b/src/gl/utility/gl_cycler.cpp @@ -0,0 +1,176 @@ +/* +** gl_cycler.cpp +** Implements the cycler for dynamic lights and texture shaders. +** +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** Copyright 2006 Christoph Oelckers +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#include +#include "serializer.h" +#include "gl/utility/gl_cycler.h" + +//========================================================================== +// +// This will never be called with a null-def, so don't bother with that case. +// +//========================================================================== + +FSerializer &Serialize(FSerializer &arc, const char *key, FCycler &c, FCycler *def) +{ + if (arc.BeginObject(key)) + { + arc("start", c.m_start, def->m_start) + ("end", c.m_end, def->m_end) + ("current", c.m_current, def->m_current) + ("time", c.m_time, def->m_time) + ("cycle", c.m_cycle, def->m_cycle) + ("increment", c.m_increment, def->m_increment) + ("shouldcycle", c.m_shouldCycle, def->m_shouldCycle) + .Enum("type", c.m_cycleType) + .EndObject(); + } + return arc; +} + +//========================================================================== +// +// +// +//========================================================================== + +FCycler::FCycler() +{ + m_cycle = 0.f; + m_cycleType = CYCLE_Linear; + m_shouldCycle = false; + m_start = m_current = 0.f; + m_end = 0.f; + m_increment = true; +} + + +//========================================================================== +// +// +// +//========================================================================== + +void FCycler::SetParams(float start, float end, float cycle, bool update) +{ + if (!update || cycle != m_cycle) + { + m_cycle = cycle; + m_time = 0.f; + m_increment = true; + m_current = start; + } + else + { + // When updating and keeping the same cycle, scale the current light size to the new dimensions. + float fact = (m_current - m_start) / (m_end - m_start); + m_current = start + fact *(end - start); + } + m_start = start; + m_end = end; +} + + +//========================================================================== +// +// +// +//========================================================================== + +void FCycler::Update(float diff) +{ + float mult, angle; + float step = m_end - m_start; + + if (!m_shouldCycle) + { + return; + } + + m_time += diff; + if (m_time >= m_cycle) + { + m_time = m_cycle; + } + + mult = m_time / m_cycle; + + switch (m_cycleType) + { + case CYCLE_Linear: + if (m_increment) + { + m_current = m_start + (step * mult); + } + else + { + m_current = m_end - (step * mult); + } + break; + case CYCLE_Sin: + angle = float(M_PI * 2.f * mult); + mult = sinf(angle); + mult = (mult + 1.f) / 2.f; + m_current = m_start + (step * mult); + break; + case CYCLE_Cos: + angle = float(M_PI * 2.f * mult); + mult = cosf(angle); + mult = (mult + 1.f) / 2.f; + m_current = m_start + (step * mult); + break; + case CYCLE_SawTooth: + m_current = m_start + (step * mult); + break; + case CYCLE_Square: + if (m_increment) + { + m_current = m_start; + } + else + { + m_current = m_end; + } + break; + } + + if (m_time == m_cycle) + { + m_time = 0.f; + m_increment = !m_increment; + } +} + + diff --git a/src/gl/utility/gl_cycler.h b/src/gl/utility/gl_cycler.h new file mode 100644 index 000000000..bcff7e9de --- /dev/null +++ b/src/gl/utility/gl_cycler.h @@ -0,0 +1,41 @@ +#ifndef __GL_CYCLER_H +#define __GL_CYCLER_H + +class FSerializer; + +enum CycleType +{ + CYCLE_Linear, + CYCLE_Sin, + CYCLE_Cos, + CYCLE_SawTooth, + CYCLE_Square +}; + +class FCycler; +FSerializer &Serialize(FSerializer &arc, const char *key, FCycler &c, FCycler *def); + +class FCycler +{ + friend FSerializer &Serialize(FSerializer &arc, const char *key, FCycler &c, FCycler *def); + +public: + FCycler(); + void Update(float diff); + void SetParams(float start, float end, float cycle, bool update = false); + void ShouldCycle(bool sc) { m_shouldCycle = sc; } + void SetCycleType(CycleType ct) { m_cycleType = ct; } + float GetVal() { return m_current; } + + inline operator float () const { return m_current; } + +protected: + float m_start, m_end, m_current; + float m_time, m_cycle; + bool m_increment, m_shouldCycle; + + CycleType m_cycleType; +}; + + +#endif diff --git a/src/gl/utility/gl_geometric.cpp b/src/gl/utility/gl_geometric.cpp new file mode 100644 index 000000000..6db10af74 --- /dev/null +++ b/src/gl/utility/gl_geometric.cpp @@ -0,0 +1,283 @@ +/* +** gl_geometric.cpp +** +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + + +#include +#include +#include "gl/utility/gl_geometric.h" + +static Vector axis[3] = +{ + Vector(1.0f, 0.0f, 0.0f), + Vector(0.0f, 1.0f, 0.0f), + Vector(0.0f, 0.0f, 1.0f) +}; + + + +Vector Vector::Cross(Vector &v) +{ + float x, y, z; + Vector cp; + + x = Y() * v.Z() - Z() * v.Y(); + y = Z() * v.X() - X() * v.Z(); + z = X() * v.Y() - Y() * v.X(); + + cp.Set(x, y, z); + + return cp; +} + + +Vector Vector::operator- (Vector &v) +{ + float x, y, z; + Vector vec; + + x = X() - v.X(); + y = Y() - v.Y(); + z = Z() - v.Z(); + + vec.Set(x, y, z); + + return vec; +} + + +Vector Vector::operator+ (Vector &v) +{ + float x, y, z; + Vector vec; + + x = X() + v.X(); + y = Y() + v.Y(); + z = Z() + v.Z(); + + vec.Set(x, y, z); + + return vec; +} + + +Vector Vector::operator* (float f) +{ + Vector vec(X(), Y(), Z()); + + vec.Scale(f); + + return vec; +} + + +Vector Vector::operator/ (float f) +{ + Vector vec(X(), Y(), Z()); + + vec.Scale(1.f / f); + + return vec; +} + + +bool Vector::operator== (Vector &v) +{ + return X() == v.X() && Y() == v.Y() && Z() == v.Z(); +} + + +void Vector::GetRightUp(Vector &right, Vector &up) +{ + Vector n(X(), Y(), Z()); + Vector fn(fabsf(n.X()), fabsf(n.Y()), fabsf(n.Z())); + int major = 0; + + if (fn[1] > fn[major]) major = 1; + if (fn[2] > fn[major]) major = 2; + + // build right vector by hand + if (fabsf(fn[0]-1.0f) < FLT_EPSILON || fabsf(fn[1]-1.0f) < FLT_EPSILON || fabsf(fn[2]-1.0f) < FLT_EPSILON) + { + if (major == 0 && n[0] > 0.f) + { + right.Set(0.f, 0.f, -1.f); + } + else if (major == 0) + { + right.Set(0.f, 0.f, 1.f); + } + + if (major == 1 || (major == 2 && n[2] > 0.f)) + { + right.Set(1.f, 0.f, 0.f); + } + + if (major == 2 && n[2] < 0.0f) + { + right.Set(-1.f, 0.f, 0.f); + } + } + else + { + right = axis[major].Cross(n); + } + + up = n.Cross(right); + right.Normalize(); + up.Normalize(); +} + + +void Vector::Scale(float scale) +{ + float x, y, z; + + x = X() * scale; + y = Y() * scale; + z = Z() * scale; + + Set(x, y, z); +} + + +Vector Vector::ProjectVector(Vector &a) +{ + Vector res, b; + + b.Set(X(), Y(), Z()); + res.Set(a.X(), a.Y(), a.Z()); + + res.Scale(a.Dot(b) / a.Dot(a)); + + return res; +} + + +Vector Vector::ProjectPlane(Vector &right, Vector &up) +{ + Vector src(X(), Y(), Z()); + Vector t1, t2; + + t1 = src.ProjectVector(right); + t2 = src.ProjectVector(up); + + return t1 + t2; +} + + + + + + +void Plane::Init(float *v1, float *v2, float *v3) +{ + Vector vec1, vec2, vec3; + + vec1.Set(v1); + vec2.Set(v2); + vec3.Set(v3); + +#ifdef _MSC_VER + m_normal = (vec2 - vec1).Cross(vec3 - vec1); +#else + Vector tmpVec = vec3 - vec1; + m_normal = (vec2 - vec1).Cross(tmpVec); +#endif + m_normal.Normalize(); + m_d = vec3.Dot(m_normal) * -1.f; +} + + +#define FNOTEQUAL(a, b) (fabsf(a - b) > 0.001f) +void Plane::Init(float *verts, int numVerts) +{ + float *v[3], *t; + int i, curVert; + + if (numVerts < 3) return; + + curVert = 1; + v[0] = verts + 0; + for (i = 1; i < numVerts; i++) + { + t = verts + (i * 3); + if (FNOTEQUAL(t[0], v[curVert - 1][0]) || FNOTEQUAL(t[1], v[curVert - 1][1]) || FNOTEQUAL(t[2], v[curVert - 1][2])) + { + v[curVert] = t; + curVert++; + } + if (curVert == 3) break; + } + + if (curVert != 3) + { + // degenerate triangle, no valid normal + return; + } + + Init(v[0], v[1], v[2]); +} + + +void Plane::Init(float a, float b, float c, float d) +{ + m_normal.Set(a, b, c); + m_d = d / m_normal.Length(); + m_normal.Normalize(); +} + + +void Plane::Set(secplane_t &plane) +{ + m_normal.Set((float)plane.Normal().X, (float)plane.Normal().Z, (float)plane.Normal().Y); + //m_normal.Normalize(); the vector is already normalized + m_d = (float)plane.fD(); +} + + +float Plane::DistToPoint(float x, float y, float z) +{ + Vector p; + + p.Set(x, y, z); + + return m_normal.Dot(p) + m_d; +} + + +bool Plane::PointOnSide(float x, float y, float z) +{ + return DistToPoint(x, y, z) < 0.f; +} + + diff --git a/src/gl/utility/gl_geometric.h b/src/gl/utility/gl_geometric.h new file mode 100644 index 000000000..243361d41 --- /dev/null +++ b/src/gl/utility/gl_geometric.h @@ -0,0 +1,294 @@ +/* +** gl_geometric.h +** +**--------------------------------------------------------------------------- +** Copyright 2003 Timothy Stump +** 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 author 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. +**--------------------------------------------------------------------------- +** +*/ + +#ifndef __GL_GEOM +#define __GL_GEOM + +#include "math.h" +#include "r_defs.h" + +class Vector +{ +public: + Vector() + { + SetX(0.f); + SetY(1.f); + SetZ(0.f); + m_length = 1.f; + } + + Vector(float x, float y, float z) + { + SetX(x); + SetY(y); + SetZ(z); + m_length=-1.0f; + } + + Vector(float *v) + { + SetX(v[0]); + SetY(v[1]); + SetZ(v[2]); + m_length=-1.0f; + } + + Vector(vertex_t * v) + { + SetX((float)v->fX()); + SetY((float)v->fY()); + SetZ(0); + } + + void Normalize() + { + float l = 1.f / Length(); + + SetX(X() * l); + SetY(Y() * l); + SetZ(Z() * l); + m_length=1.0f; + } + + void UpdateLength() + { + m_length = sqrtf((X() * X()) + (Y() * Y()) + (Z() * Z())); + } + + void Set(float *v) + { + SetX(v[0]); + SetY(v[1]); + SetZ(v[2]); + m_length=-1.0f; + } + + void Set(float x, float y, float z) + { + SetX(x); + SetY(y); + SetZ(z); + m_length=-1.0f; + } + + float Length() + { + if (m_length<0.0f) UpdateLength(); + return m_length; + } + + float Dist(Vector &v) + { + Vector t(X() - v.X(), Y() - v.Y(), Z() - v.Z()); + + return t.Length(); + } + + float Dot(Vector &v) + { + return (X() * v.X()) + (Y() * v.Y()) + (Z() * v.Z()); + } + + Vector Cross(Vector &v); + Vector operator- (Vector &v); + Vector operator+ (Vector &v); + Vector operator* (float f); + Vector operator/ (float f); + bool operator== (Vector &v); + bool operator!= (Vector &v) { return !((*this) == v); } + + void GetRightUp(Vector &up, Vector &right); + float operator[] (int index) const { return m_vec[index]; } + float &operator[] (int index) { return m_vec[index]; } + float X() const { return m_vec[0]; } + float Y() const { return m_vec[1]; } + float Z() const { return m_vec[2]; } + void SetX(float x) { m_vec[0] = x; } + void SetY(float y) { m_vec[1] = y; } + void SetZ(float z) { m_vec[2] = z; } + void Scale(float scale); + + Vector ProjectVector(Vector &a); + Vector ProjectPlane(Vector &right, Vector &up); +protected: + float m_vec[3]; + float m_length; +}; + + +class Plane +{ +public: + Plane() + { + m_normal.Set(0.f, 1.f, 0.f); + m_d = 0.f; + } + void Init(float *v1, float *v2, float *v3); + void Init(float a, float b, float c, float d); + void Init(float *verts, int numVerts); + void Set(secplane_t &plane); + float DistToPoint(float x, float y, float z); + bool PointOnSide(float x, float y, float z); + bool PointOnSide(Vector &v) { return PointOnSide(v.X(), v.Y(), v.Z()); } + bool ValidNormal() { return m_normal.Length() == 1.f; } + + float A() { return m_normal.X(); } + float B() { return m_normal.Y(); } + float C() { return m_normal.Z(); } + float D() { return m_d; } + + const Vector &Normal() const { return m_normal; } +protected: + Vector m_normal; + float m_d; +}; + +class Matrix3x4 // used like a 4x4 matrix with the last row always being (0,0,0,1) +{ + float m[3][4]; + +public: + + void MakeIdentity() + { + memset(m, 0, sizeof(m)); + m[0][0] = m[1][1] = m[2][2] = 1.f; + } + + void Translate(float x, float y, float z) + { + m[0][3] = m[0][0]*x + m[0][1]*y + m[0][2]*z + m[0][3]; + m[1][3] = m[1][0]*x + m[1][1]*y + m[1][2]*z + m[1][3]; + m[2][3] = m[2][0]*x + m[2][1]*y + m[2][2]*z + m[2][3]; + } + + void Scale(float x, float y, float z) + { + m[0][0] *=x; + m[1][0] *=x; + m[2][0] *=x; + + m[0][1] *=y; + m[1][1] *=y; + m[2][1] *=y; + + m[0][2] *=z; + m[1][2] *=z; + m[2][2] *=z; + } + + void Rotate(float ax, float ay, float az, float angle) + { + Matrix3x4 m1; + + Vector axis(ax, ay, az); + axis.Normalize(); + double c = cos(angle * M_PI/180.), s = sin(angle * M_PI/180.), t = 1 - c; + double sx = s*axis.X(), sy = s*axis.Y(), sz = s*axis.Z(); + double tx, ty, txx, tyy, u, v; + + tx = t*axis.X(); + m1.m[0][0] = float( (txx=tx*axis.X()) + c ); + m1.m[0][1] = float( (u=tx*axis.Y()) - sz); + m1.m[0][2] = float( (v=tx*axis.Z()) + sy); + + ty = t*axis.Y(); + m1.m[1][0] = float( u + sz); + m1.m[1][1] = float( (tyy=ty*axis.Y()) + c ); + m1.m[1][2] = float( (u=ty*axis.Z()) - sx); + + m1.m[2][0] = float( v - sy); + m1.m[2][1] = float( u + sx); + m1.m[2][2] = float( (t-txx-tyy) + c ); + + m1.m[0][3] = 0.f; + m1.m[1][3] = 0.f; + m1.m[2][3] = 0.f; + + *this = (*this) * m1; + } + + Matrix3x4 operator *(const Matrix3x4 &other) + { + Matrix3x4 result; + + result.m[0][0] = m[0][0]*other.m[0][0] + m[0][1]*other.m[1][0] + m[0][2]*other.m[2][0]; + result.m[0][1] = m[0][0]*other.m[0][1] + m[0][1]*other.m[1][1] + m[0][2]*other.m[2][1]; + result.m[0][2] = m[0][0]*other.m[0][2] + m[0][1]*other.m[1][2] + m[0][2]*other.m[2][2]; + result.m[0][3] = m[0][0]*other.m[0][3] + m[0][1]*other.m[1][3] + m[0][2]*other.m[2][3] + m[0][3]; + + result.m[1][0] = m[1][0]*other.m[0][0] + m[1][1]*other.m[1][0] + m[1][2]*other.m[2][0]; + result.m[1][1] = m[1][0]*other.m[0][1] + m[1][1]*other.m[1][1] + m[1][2]*other.m[2][1]; + result.m[1][2] = m[1][0]*other.m[0][2] + m[1][1]*other.m[1][2] + m[1][2]*other.m[2][2]; + result.m[1][3] = m[1][0]*other.m[0][3] + m[1][1]*other.m[1][3] + m[1][2]*other.m[2][3] + m[1][3]; + + result.m[2][0] = m[2][0]*other.m[0][0] + m[2][1]*other.m[1][0] + m[2][2]*other.m[2][0]; + result.m[2][1] = m[2][0]*other.m[0][1] + m[2][1]*other.m[1][1] + m[2][2]*other.m[2][1]; + result.m[2][2] = m[2][0]*other.m[0][2] + m[2][1]*other.m[1][2] + m[2][2]*other.m[2][2]; + result.m[2][3] = m[2][0]*other.m[0][3] + m[2][1]*other.m[1][3] + m[2][2]*other.m[2][3] + m[2][3]; + + return result; + } + + Vector operator *(const Vector &vec) + { + Vector result; + + result.SetX(vec.X()*m[0][0] + vec.Y()*m[0][1] + vec.Z()*m[0][2] + m[0][3]); + result.SetY(vec.X()*m[1][0] + vec.Y()*m[1][1] + vec.Z()*m[1][2] + m[1][3]); + result.SetZ(vec.X()*m[2][0] + vec.Y()*m[2][1] + vec.Z()*m[2][2] + m[2][3]); + return result; + } + + FVector3 operator *(const FVector3 &vec) + { + FVector3 result; + + result.X = vec.X*m[0][0] + vec.Y*m[0][1] + vec.Z*m[0][2] + m[0][3]; + result.Y = vec.X*m[1][0] + vec.Y*m[1][1] + vec.Z*m[1][2] + m[1][3]; + result.Z = vec.X*m[2][0] + vec.Y*m[2][1] + vec.Z*m[2][2] + m[2][3]; + return result; + } + + void MultiplyVector(float *f3 , float *f3o) + { + float x = f3[0] * m[0][0] + f3[1] * m[0][1] + f3[2] * m[0][2] + m[0][3]; + float y = f3[0] * m[1][0] + f3[1] * m[1][1] + f3[2] * m[1][2] + m[1][3]; + float z = f3[0] * m[2][0] + f3[1] * m[2][1] + f3[2] * m[2][2] + m[2][3]; + f3o[2] = z; f3o[1] = y; f3o[0] = x; + } +}; + +#endif diff --git a/src/gl/utility/gl_templates.h b/src/gl/utility/gl_templates.h new file mode 100644 index 000000000..1ebef1f48 --- /dev/null +++ b/src/gl/utility/gl_templates.h @@ -0,0 +1,82 @@ +#ifndef __GL_BASIC +#define __GL_BASIC + +#include +#include "stats.h" + + +// Disabled because it doesn't work and only accumulates large portions of blocked heap +// without providing any relevant performance boost. +template struct FreeList +{ + //T * freelist; + + T * GetNew() + { + /* + if (freelist) + { + T * n=freelist; + freelist=*((T**)n); + return new ((void*)n) T; + } + */ + return new T; + } + + void Release(T * node) + { + /* + node->~T(); + *((T**)node) = freelist; + freelist=node; + */ + delete node; + } + + ~FreeList() + { + /* + while (freelist!=NULL) + { + T * n = freelist; + freelist=*((T**)n); + delete n; + } + */ + } +}; + +template class UniqueList +{ + TArray Array; + FreeList TheFreeList; + +public: + + T * Get(T * t) + { + for(unsigned i=0;i +#include +#include +#include + +#if __cplusplus <= 199711 +#define static_assert(VAL, MSG) static_assertion(); +template struct static_assertion; +template<> struct static_assertion {}; +#endif // __cplusplus <= 199711 + +namespace +{ +template inline +unsigned char getByte(uint32_t val) { return static_cast((val >> (8 * N)) & 0xff); } + +inline unsigned char getAlpha(uint32_t pix) { return getByte<3>(pix); } +inline unsigned char getRed (uint32_t pix) { return getByte<2>(pix); } +inline unsigned char getGreen(uint32_t pix) { return getByte<1>(pix); } +inline unsigned char getBlue (uint32_t pix) { return getByte<0>(pix); } + +inline uint32_t makePixel( unsigned char r, unsigned char g, unsigned char b) { return (r << 16) | (g << 8) | b; } +inline uint32_t makePixel(unsigned char a, unsigned char r, unsigned char g, unsigned char b) { return (a << 24) | (r << 16) | (g << 8) | b; } + + +template inline +uint32_t gradientRGB(uint32_t pixFront, uint32_t pixBack) //blend front color with opacity M / N over opaque background: http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending +{ + static_assert(0 < M && M < N && N <= 1000, ""); + +#define calcColor(colFront, colBack) \ + (((colFront) * M + (colBack) * (N - M)) / N) + + return makePixel(calcColor(getRed (pixFront), getRed (pixBack)), + calcColor(getGreen(pixFront), getGreen(pixBack)), + calcColor(getBlue (pixFront), getBlue (pixBack))); + +#undef calcColor +} + + +template inline +uint32_t gradientARGB(uint32_t pixFront, uint32_t pixBack) //find intermediate color between two colors with alpha channels (=> NO alpha blending!!!) +{ + static_assert(0 < M && M < N && N <= 1000, ""); + + const unsigned int weightFront = getAlpha(pixFront) * M; + const unsigned int weightBack = getAlpha(pixBack) * (N - M); + const unsigned int weightSum = weightFront + weightBack; + if (weightSum == 0) + return 0; + +#define calcColor(colFront, colBack) \ + static_cast(((colFront) * weightFront + (colBack) * weightBack) / weightSum) + + return makePixel(static_cast(weightSum / N), + calcColor(getRed (pixFront), getRed (pixBack)), + calcColor(getGreen(pixFront), getGreen(pixBack)), + calcColor(getBlue (pixFront), getBlue (pixBack))); + +#undef calcColor +} + + +//inline +//double fastSqrt(double n) +//{ +// __asm //speeds up xBRZ by about 9% compared to std::sqrt which internally uses the same assembler instructions but adds some "fluff" +// { +// fld n +// fsqrt +// } +//} +// + + +uint32_t* byteAdvance( uint32_t* ptr, int bytes) { return reinterpret_cast< uint32_t*>(reinterpret_cast< char*>(ptr) + bytes); } +const uint32_t* byteAdvance(const uint32_t* ptr, int bytes) { return reinterpret_cast(reinterpret_cast(ptr) + bytes); } + + +//fill block with the given color +inline +void fillBlock(uint32_t* trg, int pitch, uint32_t col, int blockWidth, int blockHeight) +{ + //for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + // std::fill(trg, trg + blockWidth, col); + + for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + for (int x = 0; x < blockWidth; ++x) + trg[x] = col; +} + +inline +void fillBlock(uint32_t* trg, int pitch, uint32_t col, int n) { fillBlock(trg, pitch, col, n, n); } + + +#ifdef _MSC_VER + #define FORCE_INLINE __forceinline +#elif defined __GNUC__ + #define FORCE_INLINE __attribute__((always_inline)) inline +#else + #define FORCE_INLINE inline +#endif + + +enum RotationDegree //clock-wise +{ + ROT_0, + ROT_90, + ROT_180, + ROT_270 +}; + +//calculate input matrix coordinates after rotation at compile time +template +struct MatrixRotation; + +template +struct MatrixRotation +{ + static const size_t I_old = I; + static const size_t J_old = J; +}; + +template //(i, j) = (row, col) indices, N = size of (square) matrix +struct MatrixRotation +{ + static const size_t I_old = N - 1 - MatrixRotation(rotDeg - 1), I, J, N>::J_old; //old coordinates before rotation! + static const size_t J_old = MatrixRotation(rotDeg - 1), I, J, N>::I_old; // +}; + + +template +class OutputMatrix +{ +public: + OutputMatrix(uint32_t* out, int outWidth) : //access matrix area, top-left at position "out" for image with given width + out_(out), + outWidth_(outWidth) {} + + template + uint32_t& ref() const + { + static const size_t I_old = MatrixRotation::I_old; + static const size_t J_old = MatrixRotation::J_old; + return *(out_ + J_old + I_old * outWidth_); + } + +private: + uint32_t* out_; + const int outWidth_; +}; + + +template inline +T square(T value) { return value * value; } + + + +inline +double distRGB(uint32_t pix1, uint32_t pix2) +{ + const double r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const double g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const double b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + //euklidean RGB distance + return std::sqrt(square(r_diff) + square(g_diff) + square(b_diff)); +} + + +inline +double distYCbCr(uint32_t pix1, uint32_t pix2, double lumaWeight) +{ + //http://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion + //YCbCr conversion is a matrix multiplication => take advantage of linearity by subtracting first! + const int r_diff = static_cast(getRed (pix1)) - getRed (pix2); //we may delay division by 255 to after matrix multiplication + const int g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); // + const int b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); //substraction for int is noticeable faster than for double! + + //const double k_b = 0.0722; //ITU-R BT.709 conversion + //const double k_r = 0.2126; // + const double k_b = 0.0593; //ITU-R BT.2020 conversion + const double k_r = 0.2627; // + const double k_g = 1 - k_b - k_r; + + const double scale_b = 0.5 / (1 - k_b); + const double scale_r = 0.5 / (1 - k_r); + + const double y = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr! + const double c_b = scale_b * (b_diff - y); + const double c_r = scale_r * (r_diff - y); + + //we skip division by 255 to have similar range like other distance functions + return std::sqrt(square(lumaWeight * y) + square(c_b) + square(c_r)); +} + + +struct DistYCbCrBuffer //30% perf boost compared to distYCbCr()! +{ +public: + static double dist(uint32_t pix1, uint32_t pix2) + { +#if defined _MSC_VER && _MSC_VER < 1900 +#error function scope static initialization is not yet thread-safe! +#endif + static const DistYCbCrBuffer inst; + return inst.distImpl(pix1, pix2); + } + +private: + DistYCbCrBuffer() : buffer(256 * 256 * 256) + { + for (uint32_t i = 0; i < 256 * 256 * 256; ++i) //startup time: 114 ms on Intel Core i5 (four cores) + { + const int r_diff = getByte<2>(i) * 2 - 255; + const int g_diff = getByte<1>(i) * 2 - 255; + const int b_diff = getByte<0>(i) * 2 - 255; + + const double k_b = 0.0593; //ITU-R BT.2020 conversion + const double k_r = 0.2627; // + const double k_g = 1 - k_b - k_r; + + const double scale_b = 0.5 / (1 - k_b); + const double scale_r = 0.5 / (1 - k_r); + + const double y = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr! + const double c_b = scale_b * (b_diff - y); + const double c_r = scale_r * (r_diff - y); + + buffer[i] = static_cast(std::sqrt(square(y) + square(c_b) + square(c_r))); + } + } + + double distImpl(uint32_t pix1, uint32_t pix2) const + { + //if (pix1 == pix2) -> 8% perf degradation! + // return 0; + //if (pix1 > pix2) + // std::swap(pix1, pix2); -> 30% perf degradation!!! + + const int r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const int g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const int b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + return buffer[(((r_diff + 255) / 2) << 16) | //slightly reduce precision (division by 2) to squeeze value into single byte + (((g_diff + 255) / 2) << 8) | + (( b_diff + 255) / 2)]; + } + + std::vector buffer; //consumes 64 MB memory; using double is only 2% faster, but takes 128 MB +}; + + +enum BlendType +{ + BLEND_NONE = 0, + BLEND_NORMAL, //a normal indication to blend + BLEND_DOMINANT, //a strong indication to blend + //attention: BlendType must fit into the value range of 2 bit!!! +}; + +struct BlendResult +{ + BlendType + /**/blend_f, blend_g, + /**/blend_j, blend_k; +}; + + +struct Kernel_4x4 //kernel for preprocessing step +{ + uint32_t + /**/a, b, c, d, + /**/e, f, g, h, + /**/i, j, k, l, + /**/m, n, o, p; +}; + +/* +input kernel area naming convention: +----------------- +| A | B | C | D | +----|---|---|---| +| E | F | G | H | //evaluate the four corners between F, G, J, K +----|---|---|---| //input pixel is at position F +| I | J | K | L | +----|---|---|---| +| M | N | O | P | +----------------- +*/ +template +FORCE_INLINE //detect blend direction +BlendResult preProcessCorners(const Kernel_4x4& ker, const xbrz::ScalerCfg& cfg) //result: F, G, J, K corners of "GradientType" +{ + BlendResult result = {}; + + if ((ker.f == ker.g && + ker.j == ker.k) || + (ker.f == ker.j && + ker.g == ker.k)) + return result; + +#define dist(pix1, pix2) \ + ColorDistance::dist((pix1), (pix2), cfg.luminanceWeight) + + const int weight = 4; + double jg = dist(ker.i, ker.f) + dist(ker.f, ker.c) + dist(ker.n, ker.k) + dist(ker.k, ker.h) + weight * dist(ker.j, ker.g); + double fk = dist(ker.e, ker.j) + dist(ker.j, ker.o) + dist(ker.b, ker.g) + dist(ker.g, ker.l) + weight * dist(ker.f, ker.k); + +#undef dist + + if (jg < fk) //test sample: 70% of values max(jg, fk) / min(jg, fk) are between 1.1 and 3.7 with median being 1.8 + { + const bool dominantGradient = cfg.dominantDirectionThreshold * jg < fk; + if (ker.f != ker.g && ker.f != ker.j) + result.blend_f = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.k != ker.j && ker.k != ker.g) + result.blend_k = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + else if (fk < jg) + { + const bool dominantGradient = cfg.dominantDirectionThreshold * fk < jg; + if (ker.j != ker.f && ker.j != ker.k) + result.blend_j = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.g != ker.f && ker.g != ker.k) + result.blend_g = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + return result; +} + +struct Kernel_3x3 +{ + uint32_t + /**/a, b, c, + /**/d, e, f, + /**/g, h, i; +}; + +#define DEF_GETTER(x) template uint32_t inline get_##x(const Kernel_3x3& ker) { return ker.x; } +//we cannot and NEED NOT write "ker.##x" since ## concatenates preprocessor tokens but "." is not a token +DEF_GETTER(a) DEF_GETTER(b) DEF_GETTER(c) +DEF_GETTER(d) DEF_GETTER(e) DEF_GETTER(f) +DEF_GETTER(g) DEF_GETTER(h) DEF_GETTER(i) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, g) DEF_GETTER(b, d) DEF_GETTER(c, a) +DEF_GETTER(d, h) DEF_GETTER(e, e) DEF_GETTER(f, b) +DEF_GETTER(g, i) DEF_GETTER(h, f) DEF_GETTER(i, c) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, i) DEF_GETTER(b, h) DEF_GETTER(c, g) +DEF_GETTER(d, f) DEF_GETTER(e, e) DEF_GETTER(f, d) +DEF_GETTER(g, c) DEF_GETTER(h, b) DEF_GETTER(i, a) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, c) DEF_GETTER(b, f) DEF_GETTER(c, i) +DEF_GETTER(d, b) DEF_GETTER(e, e) DEF_GETTER(f, h) +DEF_GETTER(g, a) DEF_GETTER(h, d) DEF_GETTER(i, g) +#undef DEF_GETTER + + +//compress four blend types into a single byte +inline BlendType getTopL (unsigned char b) { return static_cast(0x3 & b); } +inline BlendType getTopR (unsigned char b) { return static_cast(0x3 & (b >> 2)); } +inline BlendType getBottomR(unsigned char b) { return static_cast(0x3 & (b >> 4)); } +inline BlendType getBottomL(unsigned char b) { return static_cast(0x3 & (b >> 6)); } + +inline void setTopL (unsigned char& b, BlendType bt) { b |= bt; } //buffer is assumed to be initialized before preprocessing! +inline void setTopR (unsigned char& b, BlendType bt) { b |= (bt << 2); } +inline void setBottomR(unsigned char& b, BlendType bt) { b |= (bt << 4); } +inline void setBottomL(unsigned char& b, BlendType bt) { b |= (bt << 6); } + +inline bool blendingNeeded(unsigned char b) { return b != 0; } + +template inline +unsigned char rotateBlendInfo(unsigned char b) { return b; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 2) | (b >> 6)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 4) | (b >> 4)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 6) | (b >> 2)) & 0xff; } + + +/* +input kernel area naming convention: +------------- +| A | B | C | +----|---|---| +| D | E | F | //input pixel is at position E +----|---|---| +| G | H | I | +------------- +*/ +template +FORCE_INLINE //perf: quite worth it! +void blendPixel(const Kernel_3x3& ker, + uint32_t* target, int trgWidth, + unsigned char blendInfo, //result of preprocessing all four corners of pixel "e" + const xbrz::ScalerCfg& cfg) +{ +#define a get_a(ker) +#define b get_b(ker) +#define c get_c(ker) +#define d get_d(ker) +#define e get_e(ker) +#define f get_f(ker) +#define g get_g(ker) +#define h get_h(ker) +#define i get_i(ker) + + const unsigned char blend = rotateBlendInfo(blendInfo); + + if (getBottomR(blend) >= BLEND_NORMAL) + { + struct LineBlend + { + static bool Eval(const Kernel_3x3& ker, const xbrz::ScalerCfg& cfg, const unsigned char blend) + { + if (getBottomR(blend) >= BLEND_DOMINANT) + return true; + +#define eq(pix1, pix2) \ + (ColorDistance::dist((pix1), (pix2), cfg.luminanceWeight) < cfg.equalColorTolerance) + + //make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes + if (getTopR(blend) != BLEND_NONE && !eq(e, g)) //but support double-blending for 90 degree corners + return false; + if (getBottomL(blend) != BLEND_NONE && !eq(e, c)) + return false; + + //no full blending for L-shapes; blend corner only (handles "mario mushroom eyes") + if (!eq(e, i) && eq(g, h) && eq(h , i) && eq(i, f) && eq(f, c)) + return false; + +#undef eq + + return true; + } + }; + + const bool doLineBlend = LineBlend::Eval(ker, cfg, blend); + +#define dist(pix1, pix2) \ + ColorDistance::dist((pix1), (pix2), cfg.luminanceWeight) + + const uint32_t px = dist(e, f) <= dist(e, h) ? f : h; //choose most similar color + + OutputMatrix out(target, trgWidth); + + if (doLineBlend) + { + const double fg = dist(f, g); //test sample: 70% of values max(fg, hc) / min(fg, hc) are between 1.1 and 3.7 with median being 1.9 + const double hc = dist(h, c); // + + const bool haveShallowLine = cfg.steepDirectionThreshold * fg <= hc && e != g && d != g; + const bool haveSteepLine = cfg.steepDirectionThreshold * hc <= fg && e != c && b != c; + + if (haveShallowLine) + { + if (haveSteepLine) + Scaler::blendLineSteepAndShallow(px, out); + else + Scaler::blendLineShallow(px, out); + } + else + { + if (haveSteepLine) + Scaler::blendLineSteep(px, out); + else + Scaler::blendLineDiagonal(px,out); + } + } + else + Scaler::blendCorner(px, out); + } + +#undef dist + +#undef a +#undef b +#undef c +#undef d +#undef e +#undef f +#undef g +#undef h +#undef i +} + + +template //scaler policy: see "Scaler2x" reference implementation +void scaleImage(const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, const xbrz::ScalerCfg& cfg, int yFirst, int yLast) +{ + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || srcWidth <= 0) + return; + + const int trgWidth = srcWidth * Scaler::scale; + + //"use" space at the end of the image as temporary buffer for "on the fly preprocessing": we even could use larger area of + //"sizeof(uint32_t) * srcWidth * (yLast - yFirst)" bytes without risk of accidental overwriting before accessing + const int bufferSize = srcWidth; + unsigned char* preProcBuffer = reinterpret_cast(trg + yLast * Scaler::scale * trgWidth) - bufferSize; + std::fill(preProcBuffer, preProcBuffer + bufferSize, 0); + static_assert(BLEND_NONE == 0, ""); + + //initialize preprocessing buffer for first row of current stripe: detect upper left and right corner blending + //this cannot be optimized for adjacent processing stripes; we must not allow for a memory race condition! + if (yFirst > 0) + { + const int y = yFirst - 1; + + const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0); + const uint32_t* s_0 = src + srcWidth * y; //center line + const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1); + const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1); + + for (int x = 0; x < srcWidth; ++x) + { + const int x_m1 = std::max(x - 1, 0); + const int x_p1 = std::min(x + 1, srcWidth - 1); + const int x_p2 = std::min(x + 2, srcWidth - 1); + + Kernel_4x4 ker = {}; //perf: initialization is negligible + ker.a = s_m1[x_m1]; //read sequentially from memory as far as possible + ker.b = s_m1[x]; + ker.c = s_m1[x_p1]; + ker.d = s_m1[x_p2]; + + ker.e = s_0[x_m1]; + ker.f = s_0[x]; + ker.g = s_0[x_p1]; + ker.h = s_0[x_p2]; + + ker.i = s_p1[x_m1]; + ker.j = s_p1[x]; + ker.k = s_p1[x_p1]; + ker.l = s_p1[x_p2]; + + ker.m = s_p2[x_m1]; + ker.n = s_p2[x]; + ker.o = s_p2[x_p1]; + ker.p = s_p2[x_p2]; + + const BlendResult res = preProcessCorners(ker, cfg); + /* + preprocessing blend result: + --------- + | F | G | //evalute corner between F, G, J, K + ----|---| //input pixel is at position F + | J | K | + --------- + */ + setTopR(preProcBuffer[x], res.blend_j); + + if (x + 1 < bufferSize) + setTopL(preProcBuffer[x + 1], res.blend_k); + } + } + //------------------------------------------------------------------------------------ + + for (int y = yFirst; y < yLast; ++y) + { + uint32_t* out = trg + Scaler::scale * y * trgWidth; //consider MT "striped" access + + const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0); + const uint32_t* s_0 = src + srcWidth * y; //center line + const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1); + const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1); + + unsigned char blend_xy1 = 0; //corner blending for current (x, y + 1) position + + for (int x = 0; x < srcWidth; ++x, out += Scaler::scale) + { + //all those bounds checks have only insignificant impact on performance! + const int x_m1 = std::max(x - 1, 0); //perf: prefer array indexing to additional pointers! + const int x_p1 = std::min(x + 1, srcWidth - 1); + const int x_p2 = std::min(x + 2, srcWidth - 1); + + Kernel_4x4 ker4 = {}; //perf: initialization is negligible + + ker4.a = s_m1[x_m1]; //read sequentially from memory as far as possible + ker4.b = s_m1[x]; + ker4.c = s_m1[x_p1]; + ker4.d = s_m1[x_p2]; + + ker4.e = s_0[x_m1]; + ker4.f = s_0[x]; + ker4.g = s_0[x_p1]; + ker4.h = s_0[x_p2]; + + ker4.i = s_p1[x_m1]; + ker4.j = s_p1[x]; + ker4.k = s_p1[x_p1]; + ker4.l = s_p1[x_p2]; + + ker4.m = s_p2[x_m1]; + ker4.n = s_p2[x]; + ker4.o = s_p2[x_p1]; + ker4.p = s_p2[x_p2]; + + //evaluate the four corners on bottom-right of current pixel + unsigned char blend_xy = 0; //for current (x, y) position + { + const BlendResult res = preProcessCorners(ker4, cfg); + /* + preprocessing blend result: + --------- + | F | G | //evalute corner between F, G, J, K + ----|---| //current input pixel is at position F + | J | K | + --------- + */ + blend_xy = preProcBuffer[x]; + setBottomR(blend_xy, res.blend_f); //all four corners of (x, y) have been determined at this point due to processing sequence! + + setTopR(blend_xy1, res.blend_j); //set 2nd known corner for (x, y + 1) + preProcBuffer[x] = blend_xy1; //store on current buffer position for use on next row + + blend_xy1 = 0; + setTopL(blend_xy1, res.blend_k); //set 1st known corner for (x + 1, y + 1) and buffer for use on next column + + if (x + 1 < bufferSize) //set 3rd known corner for (x + 1, y) + setBottomL(preProcBuffer[x + 1], res.blend_g); + } + + //fill block of size scale * scale with the given color + fillBlock(out, trgWidth * sizeof(uint32_t), ker4.f, Scaler::scale); //place *after* preprocessing step, to not overwrite the results while processing the the last pixel! + + //blend four corners of current pixel + if (blendingNeeded(blend_xy)) //good 5% perf-improvement + { + Kernel_3x3 ker3 = {}; //perf: initialization is negligible + + ker3.a = ker4.a; + ker3.b = ker4.b; + ker3.c = ker4.c; + + ker3.d = ker4.e; + ker3.e = ker4.f; + ker3.f = ker4.g; + + ker3.g = ker4.i; + ker3.h = ker4.j; + ker3.i = ker4.k; + + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + } + } + } +} + +//------------------------------------------------------------------------------------ + +template +struct Scaler2x : public ColorGradient +{ + static const int scale = 2; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<1, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 1>(), col); + alphaGrad<5, 6>(out.template ref<1, 1>(), col); //[!] fixes 7/8 used in xBR + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref<1, 1>(), col); + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<21, 100>(out.template ref<1, 1>(), col); //exact: 1 - pi/4 = 0.2146018366 + } +}; + + +template +struct Scaler3x : public ColorGradient +{ + static const int scale = 3; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + out.template ref<2, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<2, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 2>(), col); + alphaGrad<3, 4>(out.template ref<2, 1>(), col); + alphaGrad<3, 4>(out.template ref<1, 2>(), col); + out.template ref<2, 2>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 8>(out.template ref<1, 2>(), col); //conflict with other rotations for this odd scale + alphaGrad<1, 8>(out.template ref<2, 1>(), col); + alphaGrad<7, 8>(out.template ref<2, 2>(), col); // + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<45, 100>(out.template ref<2, 2>(), col); //exact: 0.4545939598 + //alphaGrad<7, 256>(out.template ref<2, 1>(), col); //0.02826017254 -> negligible + avoid conflicts with other rotations for this odd scale + //alphaGrad<7, 256>(out.template ref<1, 2>(), col); //0.02826017254 + } +}; + + +template +struct Scaler4x : public ColorGradient +{ + static const int scale = 4; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<3, 4>(out.template ref<3, 1>(), col); + alphaGrad<3, 4>(out.template ref<1, 3>(), col); + alphaGrad<1, 4>(out.template ref<3, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 3>(), col); + + alphaGrad<1, 3>(out.template ref<2, 2>(), col); //[!] fixes 1/4 used in xBR + + out.template ref<3, 3>() = col; + out.template ref<3, 2>() = col; + out.template ref<2, 3>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<68, 100>(out.template ref<3, 3>(), col); //exact: 0.6848532563 + alphaGrad< 9, 100>(out.template ref<3, 2>(), col); //0.08677704501 + alphaGrad< 9, 100>(out.template ref<2, 3>(), col); //0.08677704501 + } +}; + + +template +struct Scaler5x : public ColorGradient +{ + static const int scale = 5; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<4, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + alphaGrad<2, 3>(out.template ref<3, 3>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 8>(out.template ref(), col); //conflict with other rotations for this odd scale + alphaGrad<1, 8>(out.template ref(), col); + alphaGrad<1, 8>(out.template ref(), col); // + + alphaGrad<7, 8>(out.template ref<4, 3>(), col); + alphaGrad<7, 8>(out.template ref<3, 4>(), col); + + out.template ref<4, 4>() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<86, 100>(out.template ref<4, 4>(), col); //exact: 0.8631434088 + alphaGrad<23, 100>(out.template ref<4, 3>(), col); //0.2306749731 + alphaGrad<23, 100>(out.template ref<3, 4>(), col); //0.2306749731 + //alphaGrad<1, 64>(out.template ref<4, 2>(), col); //0.01676812367 -> negligible + avoid conflicts with other rotations for this odd scale + //alphaGrad<1, 64>(out.template ref<2, 4>(), col); //0.01676812367 + } +}; + + +template +struct Scaler6x : public ColorGradient +{ + static const int scale = 6; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<5, scale - 3>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<97, 100>(out.template ref<5, 5>(), col); //exact: 0.9711013910 + alphaGrad<42, 100>(out.template ref<4, 5>(), col); //0.4236372243 + alphaGrad<42, 100>(out.template ref<5, 4>(), col); //0.4236372243 + alphaGrad< 6, 100>(out.template ref<5, 3>(), col); //0.05652034508 + alphaGrad< 6, 100>(out.template ref<3, 5>(), col); //0.05652034508 + } +}; + +//------------------------------------------------------------------------------------ + +struct ColorDistanceRGB +{ + static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight) + { + return DistYCbCrBuffer::dist(pix1, pix2); + + //if (pix1 == pix2) //about 4% perf boost + // return 0; + //return distYCbCr(pix1, pix2, luminanceWeight); + } +}; + +struct ColorDistanceARGB +{ + static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight) + { + const double a1 = getAlpha(pix1) / 255.0 ; + const double a2 = getAlpha(pix2) / 255.0 ; + /* + Requirements for a color distance handling alpha channel: with a1, a2 in [0, 1] + + 1. if a1 = a2, distance should be: a1 * distYCbCr() + 2. if a1 = 0, distance should be: a2 * distYCbCr(black, white) = a2 * 255 + 3. if a1 = 1, ??? maybe: 255 * (1 - a2) + a2 * distYCbCr() + */ + + //return std::min(a1, a2) * DistYCbCrBuffer::dist(pix1, pix2) + 255 * abs(a1 - a2); + //=> following code is 15% faster: + const double d = DistYCbCrBuffer::dist(pix1, pix2); + if (a1 < a2) + return a1 * d + 255 * (a2 - a1); + else + return a2 * d + 255 * (a1 - a2); + + //alternative? return std::sqrt(a1 * a2 * square(DistYCbCrBuffer::dist(pix1, pix2)) + square(255 * (a1 - a2))); + } +}; + + +struct ColorGradientRGB +{ + template + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) + { + pixBack = gradientRGB(pixFront, pixBack); + } +}; + +struct ColorGradientARGB +{ + template + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) + { + pixBack = gradientARGB(pixFront, pixBack); + } +}; +} + + +void xbrz::scale(size_t factor, const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, ColorFormat colFmt, const xbrz::ScalerCfg& cfg, int yFirst, int yLast) +{ + switch (colFmt) + { + case ARGB: + switch (factor) + { + case 2: + return scaleImage, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + break; + + case RGB: + switch (factor) + { + case 2: + return scaleImage, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + break; + } + assert(false); +} + + +bool xbrz::equalColorTest(uint32_t col1, uint32_t col2, ColorFormat colFmt, double luminanceWeight, double equalColorTolerance) +{ + switch (colFmt) + { + case ARGB: + return ColorDistanceARGB::dist(col1, col2, luminanceWeight) < equalColorTolerance; + + case RGB: + return ColorDistanceRGB::dist(col1, col2, luminanceWeight) < equalColorTolerance; + } + assert(false); + return false; +} + + +void xbrz::nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch, + uint32_t* trg, int trgWidth, int trgHeight, int trgPitch, + SliceType st, int yFirst, int yLast) +{ + if (srcPitch < srcWidth * static_cast(sizeof(uint32_t)) || + trgPitch < trgWidth * static_cast(sizeof(uint32_t))) + { + assert(false); + return; + } + + switch (st) + { + case NN_SCALE_SLICE_SOURCE: + //nearest-neighbor (going over source image - fast for upscaling, since source is read only once + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || trgWidth <= 0 || trgHeight <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + //mathematically: ySrc = floor(srcHeight * yTrg / trgHeight) + // => search for integers in: [ySrc, ySrc + 1) * trgHeight / srcHeight + + //keep within for loop to support MT input slices! + const int yTrg_first = ( y * trgHeight + srcHeight - 1) / srcHeight; //=ceil(y * trgHeight / srcHeight) + const int yTrg_last = ((y + 1) * trgHeight + srcHeight - 1) / srcHeight; //=ceil(((y + 1) * trgHeight) / srcHeight) + const int blockHeight = yTrg_last - yTrg_first; + + if (blockHeight > 0) + { + const uint32_t* srcLine = byteAdvance(src, y * srcPitch); + uint32_t* trgLine = byteAdvance(trg, yTrg_first * trgPitch); + int xTrg_first = 0; + + for (int x = 0; x < srcWidth; ++x) + { + int xTrg_last = ((x + 1) * trgWidth + srcWidth - 1) / srcWidth; + const int blockWidth = xTrg_last - xTrg_first; + if (blockWidth > 0) + { + xTrg_first = xTrg_last; + fillBlock(trgLine, trgPitch, srcLine[x], blockWidth, blockHeight); + trgLine += blockWidth; + } + } + } + } + break; + + case NN_SCALE_SLICE_TARGET: + //nearest-neighbor (going over target image - slow for upscaling, since source is read multiple times missing out on cache! Fast for similar image sizes!) + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, trgHeight); + if (yFirst >= yLast || srcHeight <= 0 || srcWidth <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + uint32_t* trgLine = byteAdvance(trg, y * trgPitch); + const int ySrc = srcHeight * y / trgHeight; + const uint32_t* srcLine = byteAdvance(src, ySrc * srcPitch); + for (int x = 0; x < trgWidth; ++x) + { + const int xSrc = srcWidth * x / trgWidth; + trgLine[x] = srcLine[xSrc]; + } + } + break; + } +} diff --git a/src/gl/xbr/xbrz.h b/src/gl/xbr/xbrz.h new file mode 100644 index 000000000..c641429e5 --- /dev/null +++ b/src/gl/xbr/xbrz.h @@ -0,0 +1,102 @@ +// **************************************************************************** +// * This file is part of the HqMAME project. It is distributed under * +// * GNU General Public License: http://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the MAME library (or with modified * +// * versions of MAME that use the same license as MAME), and distribute * +// * linked combinations including the two. You must obey the GNU General * +// * Public License in all respects for all of the code used other than MAME. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// * * +// * An explicit permission was granted to use xBRZ in combination with ZDoom * +// * and derived projects as long as it is used for non-commercial purposes. * +// * * +// * Backported to C++98 by Alexey Lysiuk * +// **************************************************************************** + +#ifndef XBRZ_HEADER_3847894708239054 +#define XBRZ_HEADER_3847894708239054 + +#include //size_t +#include //uint32_t +#include +#include "xbrz_config.h" + +namespace xbrz +{ +/* +------------------------------------------------------------------------- +| xBRZ: "Scale by rules" - high quality image upscaling filter by Zenju | +------------------------------------------------------------------------- +using a modified approach of xBR: +http://board.byuu.org/viewtopic.php?f=10&t=2248 +- new rule set preserving small image features +- highly optimized for performance +- support alpha channel +- support multithreading +- support 64-bit architectures +- support processing image slices +- support scaling up to 6xBRZ +*/ + +enum ColorFormat //from high bits -> low bits, 8 bit per channel +{ + RGB, //8 bit for each red, green, blue, upper 8 bits unused + ARGB, //including alpha channel, BGRA byte order on little-endian machines +}; + +/* +-> map source (srcWidth * srcHeight) to target (scale * width x scale * height) image, optionally processing a half-open slice of rows [yFirst, yLast) only +-> support for source/target pitch in bytes! +-> if your emulator changes only a few image slices during each cycle (e.g. DOSBox) then there's no need to run xBRZ on the complete image: + Just make sure you enlarge the source image slice by 2 rows on top and 2 on bottom (this is the additional range the xBRZ algorithm is using during analysis) + Caveat: If there are multiple changed slices, make sure they do not overlap after adding these additional rows in order to avoid a memory race condition + in the target image data if you are using multiple threads for processing each enlarged slice! + +THREAD-SAFETY: - parts of the same image may be scaled by multiple threads as long as the [yFirst, yLast) ranges do not overlap! + - there is a minor inefficiency for the first row of a slice, so avoid processing single rows only; suggestion: process 8-16 rows at least +*/ +#ifdef max +#undef max +#endif +void scale(size_t factor, //valid range: 2 - 6 + const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, + ColorFormat colFmt, + const ScalerCfg& cfg = ScalerCfg(), + int yFirst = 0, int yLast = std::numeric_limits::max()); //slice of source image + +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + uint32_t* trg, int trgWidth, int trgHeight); + +enum SliceType +{ + NN_SCALE_SLICE_SOURCE, + NN_SCALE_SLICE_TARGET, +}; +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch, //pitch in bytes! + uint32_t* trg, int trgWidth, int trgHeight, int trgPitch, + SliceType st, int yFirst, int yLast); + +//parameter tuning +bool equalColorTest(uint32_t col1, uint32_t col2, ColorFormat colFmt, double luminanceWeight, double equalColorTolerance); + + + + + +//########################### implementation ########################### +inline +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + uint32_t* trg, int trgWidth, int trgHeight) +{ + nearestNeighborScale(src, srcWidth, srcHeight, srcWidth * sizeof(uint32_t), + trg, trgWidth, trgHeight, trgWidth * sizeof(uint32_t), + NN_SCALE_SLICE_TARGET, 0, trgHeight); +} +} + +#endif diff --git a/src/gl/xbr/xbrz_config.h b/src/gl/xbr/xbrz_config.h new file mode 100644 index 000000000..28e9e9044 --- /dev/null +++ b/src/gl/xbr/xbrz_config.h @@ -0,0 +1,45 @@ +// **************************************************************************** +// * This file is part of the HqMAME project. It is distributed under * +// * GNU General Public License: http://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the MAME library (or with modified * +// * versions of MAME that use the same license as MAME), and distribute * +// * linked combinations including the two. You must obey the GNU General * +// * Public License in all respects for all of the code used other than MAME. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// * * +// * An explicit permission was granted to use xBRZ in combination with ZDoom * +// * and derived projects as long as it is used for non-commercial purposes. * +// * * +// * Backported to C++98 by Alexey Lysiuk * +// **************************************************************************** + +#ifndef XBRZ_CONFIG_HEADER_284578425345 +#define XBRZ_CONFIG_HEADER_284578425345 + +//do NOT include any headers here! used by xBRZ_dll!!! + +namespace xbrz +{ +struct ScalerCfg +{ + ScalerCfg() : + luminanceWeight(1), + equalColorTolerance(30), + dominantDirectionThreshold(3.6), + steepDirectionThreshold(2.2), + newTestAttribute(0) {} + + double luminanceWeight; + double equalColorTolerance; + double dominantDirectionThreshold; + double steepDirectionThreshold; + double newTestAttribute; //unused; test new parameters +}; +} + +#endif \ No newline at end of file diff --git a/src/gl/xbr/xbrz_config_old.h b/src/gl/xbr/xbrz_config_old.h new file mode 100644 index 000000000..480af7976 --- /dev/null +++ b/src/gl/xbr/xbrz_config_old.h @@ -0,0 +1,45 @@ +// **************************************************************************** +// * This file is part of the HqMAME project. It is distributed under * +// * GNU General Public License: http://www.gnu.org/licenses/gpl.html * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the MAME library (or with modified * +// * versions of MAME that use the same license as MAME), and distribute * +// * linked combinations including the two. You must obey the GNU General * +// * Public License in all respects for all of the code used other than MAME. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// * * +// * An explicit permission was granted to use xBRZ in combination with ZDoom * +// * and derived projects as long as it is used for non-commercial purposes. * +// * * +// * Backported to C++98 by Alexey Lysiuk * +// **************************************************************************** + +#ifndef __XBRZ_CONFIG_OLD_HEADER_INCLUDED__ +#define __XBRZ_CONFIG_OLD_HEADER_INCLUDED__ + +//do NOT include any headers here! used by xBRZ_dll!!! + +namespace xbrz_old +{ +struct ScalerCfg +{ + ScalerCfg() : + luminanceWeight_(1), + equalColorTolerance_(30), + dominantDirectionThreshold(3.6), + steepDirectionThreshold(2.2), + newTestAttribute_(0) {} + + double luminanceWeight_; + double equalColorTolerance_; + double dominantDirectionThreshold; + double steepDirectionThreshold; + double newTestAttribute_; //unused; test new parameters +}; +} + +#endif \ No newline at end of file diff --git a/src/gl/xbr/xbrz_old.cpp b/src/gl/xbr/xbrz_old.cpp new file mode 100644 index 000000000..07527cb95 --- /dev/null +++ b/src/gl/xbr/xbrz_old.cpp @@ -0,0 +1,1365 @@ +// **************************************************************************** +// * This file is part of the HqMAME project. It is distributed under * +// * GNU General Public License: http://www.gnu.org/licenses/gpl.html * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the MAME library (or with modified * +// * versions of MAME that use the same license as MAME), and distribute * +// * linked combinations including the two. You must obey the GNU General * +// * Public License in all respects for all of the code used other than MAME. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// * * +// * An explicit permission was granted to use xBRZ in combination with ZDoom * +// * and derived projects as long as it is used for non-commercial purposes. * +// * * +// * Backported to C++98 by Alexey Lysiuk * +// **************************************************************************** + +#include "xbrz_old.h" + +#include +#include +#include + +#if __cplusplus > 199711 +#define XBRZ_CXX11 +#endif // __cplusplus > 199711 + +namespace +{ +template inline +unsigned char getByte(uint32_t val) { return static_cast((val >> (8 * N)) & 0xff); } + +inline unsigned char getRed (uint32_t val) { return getByte<2>(val); } +inline unsigned char getGreen(uint32_t val) { return getByte<1>(val); } +inline unsigned char getBlue (uint32_t val) { return getByte<0>(val); } + +template inline +T abs(T value) +{ +#ifdef XBRZ_CXX11 + static_assert(std::numeric_limits::is_signed, ""); +#endif // XBRZ_CXX11 + return value < 0 ? -value : value; +} + +const uint32_t redMask = 0xff0000; +const uint32_t greenMask = 0x00ff00; +const uint32_t blueMask = 0x0000ff; + +template inline +void alphaBlend(uint32_t& dst, uint32_t col) //blend color over destination with opacity N / M +{ +#ifdef XBRZ_CXX11 + static_assert(N < 256, "possible overflow of (col & redMask) * N"); + static_assert(M < 256, "possible overflow of (col & redMask ) * N + (dst & redMask ) * (M - N)"); + static_assert(0 < N && N < M, ""); +#endif // XBRZ_CXX11 + + static const uint32_t ALPHA_MASK = 0xFF000000; + static const uint32_t ALPHA_SHIFT = 24; + + static const uint32_t FULL_OPAQUE = 0xFF; + + const uint32_t colAlpha = col >> ALPHA_SHIFT; + const uint32_t dstAlpha = dst >> ALPHA_SHIFT; + + // Overflow is ignored intentionally! + + const uint32_t alpha = (FULL_OPAQUE == colAlpha && FULL_OPAQUE == dstAlpha) + ? ALPHA_MASK + : ALPHA_MASK & ((colAlpha * N + dstAlpha * (M - N)) / M << ALPHA_SHIFT); + + dst = (redMask & ((col & redMask ) * N + (dst & redMask ) * (M - N)) / M) | //this works because 8 upper bits are free + (greenMask & ((col & greenMask) * N + (dst & greenMask) * (M - N)) / M) | + (blueMask & ((col & blueMask ) * N + (dst & blueMask ) * (M - N)) / M) | + alpha; +} + + +//inline +//double fastSqrt(double n) +//{ +// __asm //speeds up xBRZ by about 9% compared to std::sqrt +// { +// fld n +// fsqrt +// } +//} +// + + +inline +uint32_t alphaBlend2(uint32_t pix1, uint32_t pix2, double alpha) +{ + return (redMask & static_cast((pix1 & redMask ) * alpha + (pix2 & redMask ) * (1 - alpha))) | + (greenMask & static_cast((pix1 & greenMask) * alpha + (pix2 & greenMask) * (1 - alpha))) | + (blueMask & static_cast((pix1 & blueMask ) * alpha + (pix2 & blueMask ) * (1 - alpha))); +} + + +uint32_t* byteAdvance( uint32_t* ptr, int bytes) { return reinterpret_cast< uint32_t*>(reinterpret_cast< char*>(ptr) + bytes); } +const uint32_t* byteAdvance(const uint32_t* ptr, int bytes) { return reinterpret_cast(reinterpret_cast(ptr) + bytes); } + + +//fill block with the given color +inline +void fillBlock(uint32_t* trg, int pitch, uint32_t col, int blockWidth, int blockHeight) +{ + //for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + // std::fill(trg, trg + blockWidth, col); + + for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + for (int x = 0; x < blockWidth; ++x) + trg[x] = col; +} + +inline +void fillBlock(uint32_t* trg, int pitch, uint32_t col, int n) { fillBlock(trg, pitch, col, n, n); } + + +#ifdef _MSC_VER +#define FORCE_INLINE __forceinline +#elif defined __GNUC__ +#define FORCE_INLINE __attribute__((always_inline)) inline +#else +#define FORCE_INLINE inline +#endif + + +enum RotationDegree //clock-wise +{ + ROT_0, + ROT_90, + ROT_180, + ROT_270 +}; + +//calculate input matrix coordinates after rotation at compile time +template +struct MatrixRotation; + +template +struct MatrixRotation +{ + static const size_t I_old = I; + static const size_t J_old = J; +}; + +template //(i, j) = (row, col) indices, N = size of (square) matrix +struct MatrixRotation +{ + static const size_t I_old = N - 1 - MatrixRotation(rotDeg - 1), I, J, N>::J_old; //old coordinates before rotation! + static const size_t J_old = MatrixRotation(rotDeg - 1), I, J, N>::I_old; // +}; + + +template +class OutputMatrix +{ +public: + OutputMatrix(uint32_t* out, int outWidth) : //access matrix area, top-left at position "out" for image with given width + out_(out), + outWidth_(outWidth) {} + + template + uint32_t& ref() const + { + static const size_t I_old = MatrixRotation::I_old; + static const size_t J_old = MatrixRotation::J_old; + return *(out_ + J_old + I_old * outWidth_); + } + +private: + uint32_t* out_; + const int outWidth_; +}; + + +template inline +T square(T value) { return value * value; } + + +/* +inline +void rgbtoLuv(uint32_t c, double& L, double& u, double& v) +{ + //http://www.easyrgb.com/index.php?X=MATH&H=02#text2 + double r = getRed (c) / 255.0; + double g = getGreen(c) / 255.0; + double b = getBlue (c) / 255.0; + + if ( r > 0.04045 ) + r = std::pow(( ( r + 0.055 ) / 1.055 ) , 2.4); + else + r /= 12.92; + if ( g > 0.04045 ) + g = std::pow(( ( g + 0.055 ) / 1.055 ) , 2.4); + else + g /= 12.92; + if ( b > 0.04045 ) + b = std::pow(( ( b + 0.055 ) / 1.055 ) , 2.4); + else + b /= 12.92; + + r *= 100; + g *= 100; + b *= 100; + + double x = 0.4124564 * r + 0.3575761 * g + 0.1804375 * b; + double y = 0.2126729 * r + 0.7151522 * g + 0.0721750 * b; + double z = 0.0193339 * r + 0.1191920 * g + 0.9503041 * b; + //--------------------- + double var_U = 4 * x / ( x + 15 * y + 3 * z ); + double var_V = 9 * y / ( x + 15 * y + 3 * z ); + double var_Y = y / 100; + + if ( var_Y > 0.008856 ) var_Y = std::pow(var_Y , 1.0/3 ); + else var_Y = 7.787 * var_Y + 16.0 / 116; + + const double ref_X = 95.047; //Observer= 2 degree, Illuminant= D65 + const double ref_Y = 100.000; + const double ref_Z = 108.883; + + const double ref_U = ( 4 * ref_X ) / ( ref_X + ( 15 * ref_Y ) + ( 3 * ref_Z ) ); + const double ref_V = ( 9 * ref_Y ) / ( ref_X + ( 15 * ref_Y ) + ( 3 * ref_Z ) ); + + L = ( 116 * var_Y ) - 16; + u = 13 * L * ( var_U - ref_U ); + v = 13 * L * ( var_V - ref_V ); +} +*/ + +inline +void rgbtoLab(uint32_t c, unsigned char& L, signed char& A, signed char& B) +{ + //code: http://www.easyrgb.com/index.php?X=MATH + //test: http://www.workwithcolor.com/color-converter-01.htm + //------RGB to XYZ------ + double r = getRed (c) / 255.0; + double g = getGreen(c) / 255.0; + double b = getBlue (c) / 255.0; + + r = r > 0.04045 ? std::pow(( r + 0.055 ) / 1.055, 2.4) : r / 12.92; + r = g > 0.04045 ? std::pow(( g + 0.055 ) / 1.055, 2.4) : g / 12.92; + r = b > 0.04045 ? std::pow(( b + 0.055 ) / 1.055, 2.4) : b / 12.92; + + r *= 100; + g *= 100; + b *= 100; + + double x = 0.4124564 * r + 0.3575761 * g + 0.1804375 * b; + double y = 0.2126729 * r + 0.7151522 * g + 0.0721750 * b; + double z = 0.0193339 * r + 0.1191920 * g + 0.9503041 * b; + //------XYZ to Lab------ + const double refX = 95.047; // + const double refY = 100.000; //Observer= 2 degree, Illuminant= D65 + const double refZ = 108.883; // + double var_X = x / refX; + double var_Y = y / refY; + double var_Z = z / refZ; + + var_X = var_X > 0.008856 ? std::pow(var_X, 1.0 / 3) : 7.787 * var_X + 4.0 / 29; + var_Y = var_Y > 0.008856 ? std::pow(var_Y, 1.0 / 3) : 7.787 * var_Y + 4.0 / 29; + var_Z = var_Z > 0.008856 ? std::pow(var_Z, 1.0 / 3) : 7.787 * var_Z + 4.0 / 29; + + L = static_cast(116 * var_Y - 16); + A = static_cast< signed char>(500 * (var_X - var_Y)); + B = static_cast< signed char>(200 * (var_Y - var_Z)); +}; + + +inline +double distLAB(uint32_t pix1, uint32_t pix2) +{ + unsigned char L1 = 0; //[0, 100] + signed char a1 = 0; //[-128, 127] + signed char b1 = 0; //[-128, 127] + rgbtoLab(pix1, L1, a1, b1); + + unsigned char L2 = 0; + signed char a2 = 0; + signed char b2 = 0; + rgbtoLab(pix2, L2, a2, b2); + + //----------------------------- + //http://www.easyrgb.com/index.php?X=DELT + + //Delta E/CIE76 + return std::sqrt(square(1.0 * L1 - L2) + + square(1.0 * a1 - a2) + + square(1.0 * b1 - b2)); +} + + +/* +inline +void rgbtoHsl(uint32_t c, double& h, double& s, double& l) +{ + //http://www.easyrgb.com/index.php?X=MATH&H=18#text18 + const int r = getRed (c); + const int g = getGreen(c); + const int b = getBlue (c); + + const int varMin = numeric::min(r, g, b); + const int varMax = numeric::max(r, g, b); + const int delMax = varMax - varMin; + + l = (varMax + varMin) / 2.0 / 255.0; + + if (delMax == 0) //gray, no chroma... + { + h = 0; + s = 0; + } + else + { + s = l < 0.5 ? + delMax / (1.0 * varMax + varMin) : + delMax / (2.0 * 255 - varMax - varMin); + + double delR = ((varMax - r) / 6.0 + delMax / 2.0) / delMax; + double delG = ((varMax - g) / 6.0 + delMax / 2.0) / delMax; + double delB = ((varMax - b) / 6.0 + delMax / 2.0) / delMax; + + if (r == varMax) + h = delB - delG; + else if (g == varMax) + h = 1 / 3.0 + delR - delB; + else if (b == varMax) + h = 2 / 3.0 + delG - delR; + + if (h < 0) + h += 1; + if (h > 1) + h -= 1; + } +} + +inline +double distHSL(uint32_t pix1, uint32_t pix2, double lightningWeight) +{ + double h1 = 0; + double s1 = 0; + double l1 = 0; + rgbtoHsl(pix1, h1, s1, l1); + double h2 = 0; + double s2 = 0; + double l2 = 0; + rgbtoHsl(pix2, h2, s2, l2); + + //HSL is in cylindric coordinatates where L represents height, S radius, H angle, + //however we interpret the cylinder as a bi-conic solid with top/bottom radius 0, middle radius 1 + assert(0 <= h1 && h1 <= 1); + assert(0 <= h2 && h2 <= 1); + + double r1 = l1 < 0.5 ? + l1 * 2 : + 2 - l1 * 2; + + double x1 = r1 * s1 * std::cos(h1 * 2 * numeric::pi); + double y1 = r1 * s1 * std::sin(h1 * 2 * numeric::pi); + double z1 = l1; + + double r2 = l2 < 0.5 ? + l2 * 2 : + 2 - l2 * 2; + + double x2 = r2 * s2 * std::cos(h2 * 2 * numeric::pi); + double y2 = r2 * s2 * std::sin(h2 * 2 * numeric::pi); + double z2 = l2; + + return 255 * std::sqrt(square(x1 - x2) + square(y1 - y2) + square(lightningWeight * (z1 - z2))); +} +*/ + + +inline +double distRGB(uint32_t pix1, uint32_t pix2) +{ + const double r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const double g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const double b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + //euklidean RGB distance + return std::sqrt(square(r_diff) + square(g_diff) + square(b_diff)); +} + + +inline +double distNonLinearRGB(uint32_t pix1, uint32_t pix2) +{ + //non-linear rgb: http://www.compuphase.com/cmetric.htm + const double r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const double g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const double b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + const double r_avg = (static_cast(getRed(pix1)) + getRed(pix2)) / 2; + return std::sqrt((2 + r_avg / 255) * square(r_diff) + 4 * square(g_diff) + (2 + (255 - r_avg) / 255) * square(b_diff)); +} + + +inline +double distYCbCr(uint32_t pix1, uint32_t pix2, double lumaWeight) +{ + //http://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion + //YCbCr conversion is a matrix multiplication => take advantage of linearity by subtracting first! + const int r_diff = static_cast(getRed (pix1)) - getRed (pix2); //we may delay division by 255 to after matrix multiplication + const int g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); // + const int b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); //substraction for int is noticeable faster than for double! + + const double k_b = 0.0722; //ITU-R BT.709 conversion + const double k_r = 0.2126; // + const double k_g = 1 - k_b - k_r; + + const double scale_b = 0.5 / (1 - k_b); + const double scale_r = 0.5 / (1 - k_r); + + const double y = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr! + const double c_b = scale_b * (b_diff - y); + const double c_r = scale_r * (r_diff - y); + + //we skip division by 255 to have similar range like other distance functions + return std::sqrt(square(lumaWeight * y) + square(c_b) + square(c_r)); +} + + +inline +double distYUV(uint32_t pix1, uint32_t pix2, double luminanceWeight) +{ + //perf: it's not worthwhile to buffer the YUV-conversion, the direct code is faster by ~ 6% + //since RGB -> YUV conversion is essentially a matrix multiplication, we can calculate the RGB diff before the conversion (distributive property) + const double r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const double g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const double b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + //http://en.wikipedia.org/wiki/YUV#Conversion_to.2Ffrom_RGB + const double w_b = 0.114; + const double w_r = 0.299; + const double w_g = 1 - w_r - w_b; + + const double u_max = 0.436; + const double v_max = 0.615; + + const double scale_u = u_max / (1 - w_b); + const double scale_v = v_max / (1 - w_r); + + double y = w_r * r_diff + w_g * g_diff + w_b * b_diff;//value range: 255 * [-1, 1] + double u = scale_u * (b_diff - y); //value range: 255 * 2 * u_max * [-1, 1] + double v = scale_v * (r_diff - y); //value range: 255 * 2 * v_max * [-1, 1] + +#ifndef NDEBUG + const double eps = 0.5; +#endif + assert(std::abs(y) <= 255 + eps); + assert(std::abs(u) <= 255 * 2 * u_max + eps); + assert(std::abs(v) <= 255 * 2 * v_max + eps); + + return std::sqrt(square(luminanceWeight * y) + square(u) + square(v)); +} + + +inline +double colorDist(uint32_t pix1, uint32_t pix2, double luminanceWeight) +{ + if (pix1 == pix2) //about 8% perf boost + return 0; + + //return distHSL(pix1, pix2, luminanceWeight); + //return distRGB(pix1, pix2); + //return distLAB(pix1, pix2); + //return distNonLinearRGB(pix1, pix2); + //return distYUV(pix1, pix2, luminanceWeight); + + return distYCbCr(pix1, pix2, luminanceWeight); +} + + +enum BlendType +{ + BLEND_NONE = 0, + BLEND_NORMAL, //a normal indication to blend + BLEND_DOMINANT, //a strong indication to blend + //attention: BlendType must fit into the value range of 2 bit!!! +}; + +struct BlendResult +{ + BlendType + /**/blend_f, blend_g, + /**/blend_j, blend_k; +}; + + +struct Kernel_4x4 //kernel for preprocessing step +{ + uint32_t + /**/a, b, c, d, + /**/e, f, g, h, + /**/i, j, k, l, + /**/m, n, o, p; +}; + +/* +input kernel area naming convention: +----------------- +| A | B | C | D | +----|---|---|---| +| E | F | G | H | //evalute the four corners between F, G, J, K +----|---|---|---| //input pixel is at position F +| I | J | K | L | +----|---|---|---| +| M | N | O | P | +----------------- +*/ +FORCE_INLINE //detect blend direction +BlendResult preProcessCorners(const Kernel_4x4& ker, const xbrz_old::ScalerCfg& cfg) //result: F, G, J, K corners of "GradientType" +{ + BlendResult result = {}; + + if ((ker.f == ker.g && + ker.j == ker.k) || + (ker.f == ker.j && + ker.g == ker.k)) + return result; + +#ifdef XBRZ_CXX11 + auto dist = [&](uint32_t col1, uint32_t col2) { return colorDist(col1, col2, cfg.luminanceWeight_); }; +#else // !XBRZ_CXX11 +#define dist(C1, C2) colorDist((C1), (C2), cfg.luminanceWeight_) +#endif // XBRZ_CXX11 + + const int weight = 4; + double jg = dist(ker.i, ker.f) + dist(ker.f, ker.c) + dist(ker.n, ker.k) + dist(ker.k, ker.h) + weight * dist(ker.j, ker.g); + double fk = dist(ker.e, ker.j) + dist(ker.j, ker.o) + dist(ker.b, ker.g) + dist(ker.g, ker.l) + weight * dist(ker.f, ker.k); + +#ifndef XBRZ_CXX11 +#undef dist +#endif // !XBRZ_CXX11 + + if (jg < fk) //test sample: 70% of values max(jg, fk) / min(jg, fk) are between 1.1 and 3.7 with median being 1.8 + { + const bool dominantGradient = cfg.dominantDirectionThreshold * jg < fk; + if (ker.f != ker.g && ker.f != ker.j) + result.blend_f = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.k != ker.j && ker.k != ker.g) + result.blend_k = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + else if (fk < jg) + { + const bool dominantGradient = cfg.dominantDirectionThreshold * fk < jg; + if (ker.j != ker.f && ker.j != ker.k) + result.blend_j = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.g != ker.f && ker.g != ker.k) + result.blend_g = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + return result; +} + +struct Kernel_3x3 +{ + uint32_t + /**/a, b, c, + /**/d, e, f, + /**/g, h, i; +}; + +#define DEF_GETTER(x) template uint32_t inline get_##x(const Kernel_3x3& ker) { return ker.x; } +//we cannot and NEED NOT write "ker.##x" since ## concatenates preprocessor tokens but "." is not a token +DEF_GETTER(a) DEF_GETTER(b) DEF_GETTER(c) +DEF_GETTER(d) DEF_GETTER(e) DEF_GETTER(f) +DEF_GETTER(g) DEF_GETTER(h) DEF_GETTER(i) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, g) DEF_GETTER(b, d) DEF_GETTER(c, a) +DEF_GETTER(d, h) DEF_GETTER(e, e) DEF_GETTER(f, b) +DEF_GETTER(g, i) DEF_GETTER(h, f) DEF_GETTER(i, c) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, i) DEF_GETTER(b, h) DEF_GETTER(c, g) +DEF_GETTER(d, f) DEF_GETTER(e, e) DEF_GETTER(f, d) +DEF_GETTER(g, c) DEF_GETTER(h, b) DEF_GETTER(i, a) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, c) DEF_GETTER(b, f) DEF_GETTER(c, i) +DEF_GETTER(d, b) DEF_GETTER(e, e) DEF_GETTER(f, h) +DEF_GETTER(g, a) DEF_GETTER(h, d) DEF_GETTER(i, g) +#undef DEF_GETTER + + +//compress four blend types into a single byte +inline BlendType getTopL (unsigned char b) { return static_cast(0x3 & b); } +inline BlendType getTopR (unsigned char b) { return static_cast(0x3 & (b >> 2)); } +inline BlendType getBottomR(unsigned char b) { return static_cast(0x3 & (b >> 4)); } +inline BlendType getBottomL(unsigned char b) { return static_cast(0x3 & (b >> 6)); } + +inline void setTopL (unsigned char& b, BlendType bt) { b |= bt; } //buffer is assumed to be initialized before preprocessing! +inline void setTopR (unsigned char& b, BlendType bt) { b |= (bt << 2); } +inline void setBottomR(unsigned char& b, BlendType bt) { b |= (bt << 4); } +inline void setBottomL(unsigned char& b, BlendType bt) { b |= (bt << 6); } + +inline bool blendingNeeded(unsigned char b) { return b != 0; } + +template inline +unsigned char rotateBlendInfo(unsigned char b) { return b; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 2) | (b >> 6)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 4) | (b >> 4)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 6) | (b >> 2)) & 0xff; } + + +#ifndef NDEBUG +int debugPixelX = -1; +int debugPixelY = 84; +bool breakIntoDebugger = false; +#endif + +#define a get_a(ker) +#define b get_b(ker) +#define c get_c(ker) +#define d get_d(ker) +#define e get_e(ker) +#define f get_f(ker) +#define g get_g(ker) +#define h get_h(ker) +#define i get_i(ker) + +#ifndef XBRZ_CXX11 + +template +bool doLineBlend(const Kernel_3x3& ker, const xbrz_old::ScalerCfg& cfg, const unsigned char blend) +{ + if (getBottomR(blend) >= BLEND_DOMINANT) + return true; + +#define eq(C1, C2) (colorDist((C1), (C2), cfg.luminanceWeight_) < cfg.equalColorTolerance_) + + //make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes + if (getTopR(blend) != BLEND_NONE && !eq(e, g)) //but support double-blending for 90 degree corners + return false; + if (getBottomL(blend) != BLEND_NONE && !eq(e, c)) + return false; + + //no full blending for L-shapes; blend corner only (handles "mario mushroom eyes") + if (eq(g, h) && eq(h , i) && eq(i, f) && eq(f, c) && !eq(e, i)) + return false; + +#undef eq + + return true; +}; + +#endif // !XBRZ_CXX11 + +/* +input kernel area naming convention: +------------- +| A | B | C | +----|---|---| +| D | E | F | //input pixel is at position E +----|---|---| +| G | H | I | +------------- +*/ +template +FORCE_INLINE //perf: quite worth it! +void scalePixel(const Kernel_3x3& ker, + uint32_t* target, int trgWidth, + unsigned char blendInfo, //result of preprocessing all four corners of pixel "e" + const xbrz_old::ScalerCfg& cfg) +{ +#ifndef NDEBUG + if (breakIntoDebugger) +#ifdef _MSC_VER + __debugbreak(); //__asm int 3; +#else // !_MSC_VER + __builtin_trap(); +#endif // _MSC_VER +#endif + + const unsigned char blend = rotateBlendInfo(blendInfo); + + if (getBottomR(blend) >= BLEND_NORMAL) + { +#ifdef XBRZ_CXX11 + auto eq = [&](uint32_t col1, uint32_t col2) { return colorDist(col1, col2, cfg.luminanceWeight_) < cfg.equalColorTolerance_; }; + auto dist = [&](uint32_t col1, uint32_t col2) { return colorDist(col1, col2, cfg.luminanceWeight_); }; + + const bool doLineBlend = [&]() -> bool + { + if (getBottomR(blend) >= BLEND_DOMINANT) + return true; + + //make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes + if (getTopR(blend) != BLEND_NONE && !eq(e, g)) //but support double-blending for 90 degree corners + return false; + if (getBottomL(blend) != BLEND_NONE && !eq(e, c)) + return false; + + //no full blending for L-shapes; blend corner only (handles "mario mushroom eyes") + if (eq(g, h) && eq(h , i) && eq(i, f) && eq(f, c) && !eq(e, i)) + return false; + + return true; + }(); +#else // !XBRZ_CXX11 +#define dist(C1, C2) colorDist((C1), (C2), cfg.luminanceWeight_) +#endif // XBRZ_CXX11 + + const uint32_t px = dist(e, f) <= dist(e, h) ? f : h; //choose most similar color + + OutputMatrix out(target, trgWidth); + +#ifdef XBRZ_CXX11 + if (doLineBlend) +#else // !XBRZ_CXX11 + if (doLineBlend(ker, cfg, blend)) +#endif // XBRZ_CXX11 + { + const double fg = dist(f, g); //test sample: 70% of values max(fg, hc) / min(fg, hc) are between 1.1 and 3.7 with median being 1.9 + const double hc = dist(h, c); // + + const bool haveShallowLine = cfg.steepDirectionThreshold * fg <= hc && e != g && d != g; + const bool haveSteepLine = cfg.steepDirectionThreshold * hc <= fg && e != c && b != c; + + if (haveShallowLine) + { + if (haveSteepLine) + Scaler::blendLineSteepAndShallow(px, out); + else + Scaler::blendLineShallow(px, out); + } + else + { + if (haveSteepLine) + Scaler::blendLineSteep(px, out); + else + Scaler::blendLineDiagonal(px,out); + } + } + else + Scaler::blendCorner(px, out); + } + +#ifndef XBRZ_CXX11 +#undef dist +#endif // XBRZ_CXX11 + +#undef a +#undef b +#undef c +#undef d +#undef e +#undef f +#undef g +#undef h +#undef i +} + + +template //scaler policy: see "Scaler2x" reference implementation +void scaleImage(const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, const xbrz_old::ScalerCfg& cfg, int yFirst, int yLast) +{ + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || srcWidth <= 0) + return; + + const int trgWidth = srcWidth * Scaler::scale; + + //"use" space at the end of the image as temporary buffer for "on the fly preprocessing": we even could use larger area of + //"sizeof(uint32_t) * srcWidth * (yLast - yFirst)" bytes without risk of accidental overwriting before accessing + const int bufferSize = srcWidth; + unsigned char* preProcBuffer = reinterpret_cast(trg + yLast * Scaler::scale * trgWidth) - bufferSize; + std::fill(preProcBuffer, preProcBuffer + bufferSize, 0); +#ifdef XBRZ_CXX11 + static_assert(BLEND_NONE == 0, ""); +#endif // XBRZ_CXX11 + + //initialize preprocessing buffer for first row: detect upper left and right corner blending + //this cannot be optimized for adjacent processing stripes; we must not allow for a memory race condition! + if (yFirst > 0) + { + const int y = yFirst - 1; + + const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0); + const uint32_t* s_0 = src + srcWidth * y; //center line + const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1); + const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1); + + for (int x = 0; x < srcWidth; ++x) + { + const int x_m1 = std::max(x - 1, 0); + const int x_p1 = std::min(x + 1, srcWidth - 1); + const int x_p2 = std::min(x + 2, srcWidth - 1); + + Kernel_4x4 ker = {}; //perf: initialization is negligable + ker.a = s_m1[x_m1]; //read sequentially from memory as far as possible + ker.b = s_m1[x]; + ker.c = s_m1[x_p1]; + ker.d = s_m1[x_p2]; + + ker.e = s_0[x_m1]; + ker.f = s_0[x]; + ker.g = s_0[x_p1]; + ker.h = s_0[x_p2]; + + ker.i = s_p1[x_m1]; + ker.j = s_p1[x]; + ker.k = s_p1[x_p1]; + ker.l = s_p1[x_p2]; + + ker.m = s_p2[x_m1]; + ker.n = s_p2[x]; + ker.o = s_p2[x_p1]; + ker.p = s_p2[x_p2]; + + const BlendResult res = preProcessCorners(ker, cfg); + /* + preprocessing blend result: + --------- + | F | G | //evalute corner between F, G, J, K + ----|---| //input pixel is at position F + | J | K | + --------- + */ + setTopR(preProcBuffer[x], res.blend_j); + + if (x + 1 < srcWidth) + setTopL(preProcBuffer[x + 1], res.blend_k); + } + } + //------------------------------------------------------------------------------------ + + for (int y = yFirst; y < yLast; ++y) + { + uint32_t* out = trg + Scaler::scale * y * trgWidth; //consider MT "striped" access + + const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0); + const uint32_t* s_0 = src + srcWidth * y; //center line + const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1); + const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1); + + unsigned char blend_xy1 = 0; //corner blending for current (x, y + 1) position + + for (int x = 0; x < srcWidth; ++x, out += Scaler::scale) + { +#ifndef NDEBUG + breakIntoDebugger = debugPixelX == x && debugPixelY == y; +#endif + //all those bounds checks have only insignificant impact on performance! + const int x_m1 = std::max(x - 1, 0); //perf: prefer array indexing to additional pointers! + const int x_p1 = std::min(x + 1, srcWidth - 1); + const int x_p2 = std::min(x + 2, srcWidth - 1); + + //evaluate the four corners on bottom-right of current pixel + unsigned char blend_xy = 0; //for current (x, y) position + { + Kernel_4x4 ker = {}; //perf: initialization is negligable + ker.a = s_m1[x_m1]; //read sequentially from memory as far as possible + ker.b = s_m1[x]; + ker.c = s_m1[x_p1]; + ker.d = s_m1[x_p2]; + + ker.e = s_0[x_m1]; + ker.f = s_0[x]; + ker.g = s_0[x_p1]; + ker.h = s_0[x_p2]; + + ker.i = s_p1[x_m1]; + ker.j = s_p1[x]; + ker.k = s_p1[x_p1]; + ker.l = s_p1[x_p2]; + + ker.m = s_p2[x_m1]; + ker.n = s_p2[x]; + ker.o = s_p2[x_p1]; + ker.p = s_p2[x_p2]; + + const BlendResult res = preProcessCorners(ker, cfg); + /* + preprocessing blend result: + --------- + | F | G | //evalute corner between F, G, J, K + ----|---| //current input pixel is at position F + | J | K | + --------- + */ + blend_xy = preProcBuffer[x]; + setBottomR(blend_xy, res.blend_f); //all four corners of (x, y) have been determined at this point due to processing sequence! + + setTopR(blend_xy1, res.blend_j); //set 2nd known corner for (x, y + 1) + preProcBuffer[x] = blend_xy1; //store on current buffer position for use on next row + + blend_xy1 = 0; + setTopL(blend_xy1, res.blend_k); //set 1st known corner for (x + 1, y + 1) and buffer for use on next column + + if (x + 1 < srcWidth) //set 3rd known corner for (x + 1, y) + setBottomL(preProcBuffer[x + 1], res.blend_g); + } + + //fill block of size scale * scale with the given color + fillBlock(out, trgWidth * sizeof(uint32_t), s_0[x], Scaler::scale); //place *after* preprocessing step, to not overwrite the results while processing the the last pixel! + + //blend four corners of current pixel + if (blendingNeeded(blend_xy)) //good 20% perf-improvement + { + Kernel_3x3 ker = {}; //perf: initialization is negligable + + ker.a = s_m1[x_m1]; //read sequentially from memory as far as possible + ker.b = s_m1[x]; + ker.c = s_m1[x_p1]; + + ker.d = s_0[x_m1]; + ker.e = s_0[x]; + ker.f = s_0[x_p1]; + + ker.g = s_p1[x_m1]; + ker.h = s_p1[x]; + ker.i = s_p1[x_p1]; + + scalePixel(ker, out, trgWidth, blend_xy, cfg); + scalePixel(ker, out, trgWidth, blend_xy, cfg); + scalePixel(ker, out, trgWidth, blend_xy, cfg); + scalePixel(ker, out, trgWidth, blend_xy, cfg); + } + } + } +} + + +struct Scaler2x +{ + static const int scale = 2; + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<1, 0>(), col); + alphaBlend<1, 4>(out.template ref<0, 1>(), col); + alphaBlend<5, 6>(out.template ref<1, 1>(), col); //[!] fixes 7/8 used in xBR + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 2>(out.template ref<1, 1>(), col); + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaBlend<21, 100>(out.template ref<1, 1>(), col); //exact: 1 - pi/4 = 0.2146018366 + } +}; + + +struct Scaler3x +{ + static const int scale = 3; + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + + alphaBlend<3, 4>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + out.template ref<2, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<2, 0>(), col); + alphaBlend<1, 4>(out.template ref<0, 2>(), col); + alphaBlend<3, 4>(out.template ref<2, 1>(), col); + alphaBlend<3, 4>(out.template ref<1, 2>(), col); + out.template ref<2, 2>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 8>(out.template ref<1, 2>(), col); + alphaBlend<1, 8>(out.template ref<2, 1>(), col); + alphaBlend<7, 8>(out.template ref<2, 2>(), col); + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaBlend<45, 100>(out.template ref<2, 2>(), col); //exact: 0.4545939598 + //alphaBlend<14, 1000>(out.template ref<2, 1>(), col); //0.01413008627 -> negligable + //alphaBlend<14, 1000>(out.template ref<1, 2>(), col); //0.01413008627 + } +}; + + +struct Scaler4x +{ + static const int scale = 4; + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + + alphaBlend<3, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + alphaBlend<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<3, 4>(out.template ref<3, 1>(), col); + alphaBlend<3, 4>(out.template ref<1, 3>(), col); + alphaBlend<1, 4>(out.template ref<3, 0>(), col); + alphaBlend<1, 4>(out.template ref<0, 3>(), col); + alphaBlend<1, 3>(out.template ref<2, 2>(), col); //[!] fixes 1/4 used in xBR + out.template ref<3, 3>() = out.template ref<3, 2>() = out.template ref<2, 3>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 2>(out.template ref(), col); + alphaBlend<1, 2>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaBlend<68, 100>(out.template ref<3, 3>(), col); //exact: 0.6848532563 + alphaBlend< 9, 100>(out.template ref<3, 2>(), col); //0.08677704501 + alphaBlend< 9, 100>(out.template ref<2, 3>(), col); //0.08677704501 + } +}; + + +struct Scaler5x +{ + static const int scale = 5; + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + + alphaBlend<3, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + alphaBlend<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + alphaBlend<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<4, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + + out.template ref() = col; + out.template ref() = col; + + out.template ref<4, scale - 1>() = col; + + alphaBlend<2, 3>(out.template ref<3, 3>(), col); + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 8>(out.template ref(), col); + alphaBlend<1, 8>(out.template ref(), col); + alphaBlend<1, 8>(out.template ref(), col); + + alphaBlend<7, 8>(out.template ref<4, 3>(), col); + alphaBlend<7, 8>(out.template ref<3, 4>(), col); + + out.template ref<4, 4>() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaBlend<86, 100>(out.template ref<4, 4>(), col); //exact: 0.8631434088 + alphaBlend<23, 100>(out.template ref<4, 3>(), col); //0.2306749731 + alphaBlend<23, 100>(out.template ref<3, 4>(), col); //0.2306749731 + //alphaBlend<8, 1000>(out.template ref<4, 2>(), col); //0.008384061834 -> negligable + //alphaBlend<8, 1000>(out.template ref<2, 4>(), col); //0.008384061834 + } +}; +} + + +struct Scaler6x +{ + static const int scale = 6; + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + + alphaBlend<3, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + alphaBlend<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + alphaBlend<3, 4>(out.template ref<3, scale - 2>(), col); + alphaBlend<3, 4>(out.template ref<5, scale - 3>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 4>(out.template ref<0, scale - 1>(), col); + alphaBlend<1, 4>(out.template ref<2, scale - 2>(), col); + alphaBlend<3, 4>(out.template ref<1, scale - 1>(), col); + alphaBlend<3, 4>(out.template ref<3, scale - 2>(), col); + + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<1, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + alphaBlend<3, 4>(out.template ref(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaBlend<1, 2>(out.template ref(), col); + alphaBlend<1, 2>(out.template ref(), col); + alphaBlend<1, 2>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaBlend<97, 100>(out.template ref<5, 5>(), col); //exact: 0.9711013910 + alphaBlend<42, 100>(out.template ref<4, 5>(), col); //0.4236372243 + alphaBlend<42, 100>(out.template ref<5, 4>(), col); //0.4236372243 + alphaBlend< 6, 100>(out.template ref<5, 3>(), col); //0.05652034508 + alphaBlend< 6, 100>(out.template ref<3, 5>(), col); //0.05652034508 + } +}; + + +void xbrz_old::scale(size_t factor, const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, const xbrz_old::ScalerCfg& cfg, int yFirst, int yLast) +{ + switch (factor) + { + case 2: + return scaleImage(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + assert(false); +} + + +bool xbrz_old::equalColor(uint32_t col1, uint32_t col2, double luminanceWeight, double equalColorTolerance) +{ + return colorDist(col1, col2, luminanceWeight) < equalColorTolerance; +} + + +void xbrz_old::nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch, + uint32_t* trg, int trgWidth, int trgHeight, int trgPitch, + SliceType st, int yFirst, int yLast) +{ + if (srcPitch < srcWidth * static_cast(sizeof(uint32_t)) || + trgPitch < trgWidth * static_cast(sizeof(uint32_t))) + { + assert(false); + return; + } + + switch (st) + { + case NN_SCALE_SLICE_SOURCE: + //nearest-neighbor (going over source image - fast for upscaling, since source is read only once + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || trgWidth <= 0 || trgHeight <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + //mathematically: ySrc = floor(srcHeight * yTrg / trgHeight) + // => search for integers in: [ySrc, ySrc + 1) * trgHeight / srcHeight + + //keep within for loop to support MT input slices! + const int yTrg_first = ( y * trgHeight + srcHeight - 1) / srcHeight; //=ceil(y * trgHeight / srcHeight) + const int yTrg_last = ((y + 1) * trgHeight + srcHeight - 1) / srcHeight; //=ceil(((y + 1) * trgHeight) / srcHeight) + const int blockHeight = yTrg_last - yTrg_first; + + if (blockHeight > 0) + { + const uint32_t* srcLine = byteAdvance(src, y * srcPitch); + uint32_t* trgLine = byteAdvance(trg, yTrg_first * trgPitch); + int xTrg_first = 0; + + for (int x = 0; x < srcWidth; ++x) + { + int xTrg_last = ((x + 1) * trgWidth + srcWidth - 1) / srcWidth; + const int blockWidth = xTrg_last - xTrg_first; + if (blockWidth > 0) + { + xTrg_first = xTrg_last; + fillBlock(trgLine, trgPitch, srcLine[x], blockWidth, blockHeight); + trgLine += blockWidth; + } + } + } + } + break; + + case NN_SCALE_SLICE_TARGET: + //nearest-neighbor (going over target image - slow for upscaling, since source is read multiple times missing out on cache! Fast for similar image sizes!) + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, trgHeight); + if (yFirst >= yLast || srcHeight <= 0 || srcWidth <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + uint32_t* trgLine = byteAdvance(trg, y * trgPitch); + const int ySrc = srcHeight * y / trgHeight; + const uint32_t* srcLine = byteAdvance(src, ySrc * srcPitch); + for (int x = 0; x < trgWidth; ++x) + { + const int xSrc = srcWidth * x / trgWidth; + trgLine[x] = srcLine[xSrc]; + } + } + break; + } +} diff --git a/src/gl/xbr/xbrz_old.h b/src/gl/xbr/xbrz_old.h new file mode 100644 index 000000000..c93a1480a --- /dev/null +++ b/src/gl/xbr/xbrz_old.h @@ -0,0 +1,92 @@ +// **************************************************************************** +// * This file is part of the HqMAME project. It is distributed under * +// * GNU General Public License: http://www.gnu.org/licenses/gpl.html * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the MAME library (or with modified * +// * versions of MAME that use the same license as MAME), and distribute * +// * linked combinations including the two. You must obey the GNU General * +// * Public License in all respects for all of the code used other than MAME. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// * * +// * An explicit permission was granted to use xBRZ in combination with ZDoom * +// * and derived projects as long as it is used for non-commercial purposes. * +// * * +// * Backported to C++98 by Alexey Lysiuk * +// **************************************************************************** + +#ifndef __XBRZ_OLD_HEADER_INCLUDED__ +#define __XBRZ_OLD_HEADER_INCLUDED__ + +#include //size_t +#include //uint32_t +#include +#include "xbrz_config_old.h" + +namespace xbrz_old +{ +/* +------------------------------------------------------------------------- +| xBRZ: "Scale by rules" - high quality image upscaling filter by Zenju | +------------------------------------------------------------------------- +using a modified approach of xBR: +http://board.byuu.org/viewtopic.php?f=10&t=2248 +- new rule set preserving small image features +- support multithreading +- support 64 bit architectures +- support processing image slices +*/ + +/* +-> map source (srcWidth * srcHeight) to target (scale * width x scale * height) image, optionally processing a half-open slice of rows [yFirst, yLast) only +-> color format: ARGB (BGRA byte order), alpha channel unused +-> support for source/target pitch in bytes! +-> if your emulator changes only a few image slices during each cycle (e.g. Dosbox) then there's no need to run xBRZ on the complete image: + Just make sure you enlarge the source image slice by 2 rows on top and 2 on bottom (this is the additional range the xBRZ algorithm is using during analysis) + Caveat: If there are multiple changed slices, make sure they do not overlap after adding these additional rows in order to avoid a memory race condition + if you are using multiple threads for processing each enlarged slice! + +THREAD-SAFETY: - parts of the same image may be scaled by multiple threads as long as the [yFirst, yLast) ranges do not overlap! + - there is a minor inefficiency for the first row of a slice, so avoid processing single rows only + + +*/ +void scale(size_t factor, //valid range: 2 - 5 + const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, + const ScalerCfg& cfg = ScalerCfg(), + int yFirst = 0, int yLast = std::numeric_limits::max()); //slice of source image + +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + uint32_t* trg, int trgWidth, int trgHeight); + +enum SliceType +{ + NN_SCALE_SLICE_SOURCE, + NN_SCALE_SLICE_TARGET, +}; +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch, //pitch in bytes! + uint32_t* trg, int trgWidth, int trgHeight, int trgPitch, + SliceType st, int yFirst, int yLast); + +//parameter tuning +bool equalColor(uint32_t col1, uint32_t col2, double luminanceWeight, double equalColorTolerance); + + + + + +//########################### implementation ########################### +inline +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + uint32_t* trg, int trgWidth, int trgHeight) +{ + nearestNeighborScale(src, srcWidth, srcHeight, srcWidth * sizeof(uint32_t), + trg, trgWidth, trgHeight, trgWidth * sizeof(uint32_t), + NN_SCALE_SLICE_TARGET, 0, trgHeight); +} +} + +#endif diff --git a/src/menu/playerdisplay.cpp b/src/menu/playerdisplay.cpp index c3d11a43a..16671975a 100644 --- a/src/menu/playerdisplay.cpp +++ b/src/menu/playerdisplay.cpp @@ -78,7 +78,6 @@ public: const BYTE *GetColumn(unsigned int column, const Span **spans_out); const BYTE *GetPixels(); - void Unload(); bool CheckModified(); protected: @@ -212,10 +211,6 @@ bool FBackdropTexture::CheckModified() return LastRenderTic != gametic; } -void FBackdropTexture::Unload() -{ -} - //============================================================================= // // diff --git a/src/p_3dfloors.cpp b/src/p_3dfloors.cpp index d27ebe4d1..c2d011be9 100644 --- a/src/p_3dfloors.cpp +++ b/src/p_3dfloors.cpp @@ -202,7 +202,7 @@ static void P_Add3DFloor(sector_t* sec, sector_t* sec2, line_t* master, int flag // kg3D - software renderer only hack // this is really required because of ceilingclip and floorclip - if(flags & FF_BOTHPLANES) + if((vid_renderer == 0) && (flags & FF_BOTHPLANES)) { P_Add3DFloor(sec, sec2, master, FF_EXISTS | FF_THISINSIDE | FF_RENDERPLANES | FF_NOSHADE | FF_SEETHROUGH | FF_SHOOTTHROUGH | (flags & (FF_INVERTSECTOR | FF_TRANSLUCENT | FF_ADDITIVETRANS)), alpha); diff --git a/src/p_actionfunctions.cpp b/src/p_actionfunctions.cpp index 4136ec331..5bf5bf450 100644 --- a/src/p_actionfunctions.cpp +++ b/src/p_actionfunctions.cpp @@ -1286,9 +1286,9 @@ DEFINE_ACTION_FUNCTION(AActor, A_Explode) { ang = i*360./nails; // Comparing the results of a test wad with Eternity, it seems A_NailBomb does not aim - P_LineAttack (self, ang, MISSILERANGE, 0., + P_LineAttack(self, ang, MISSILERANGE, 0., //P_AimLineAttack (self, ang, MISSILERANGE), - naildamage, NAME_Hitscan, pufftype); + naildamage, NAME_Hitscan, pufftype, (self->flags & MF_MISSILE) ? LAF_TARGETISSOURCE : 0); } } diff --git a/src/p_effect.h b/src/p_effect.h index 614702a49..eb417d63c 100644 --- a/src/p_effect.h +++ b/src/p_effect.h @@ -31,6 +31,8 @@ ** */ +#pragma once + #include "vectors.h" #define FX_ROCKET 0x00000001 diff --git a/src/p_lnspec.cpp b/src/p_lnspec.cpp index 179e057b3..d368739e1 100644 --- a/src/p_lnspec.cpp +++ b/src/p_lnspec.cpp @@ -74,6 +74,9 @@ */ static const BYTE ChangeMap[8] = { 0, 1, 5, 3, 7, 2, 6, 0 }; +int LS_Sector_SetPlaneReflection(line_t *ln, AActor *it, bool backSide, int arg0, int arg1, int arg2, int arg3, int arg4); +int LS_SetGlobalFogParameter(line_t *ln, AActor *it, bool backSide, int arg0, int arg1, int arg2, int arg3, int arg4); + #define FUNC(a) static int a (line_t *ln, AActor *it, bool backSide, \ int arg0, int arg1, int arg2, int arg3, int arg4) @@ -3462,9 +3465,9 @@ static lnSpecFunc LineSpecials[] = /* 154 */ LS_Teleport_NoStop, /* 155 */ LS_NOP, /* 156 */ LS_NOP, - /* 157 */ LS_NOP, // SetGlobalFogParameter + /* 157 */ LS_SetGlobalFogParameter, /* 158 */ LS_FS_Execute, - /* 159 */ LS_NOP, // Sector_SetPlaneReflection + /* 159 */ LS_Sector_SetPlaneReflection, /* 160 */ LS_NOP, // Sector_Set3DFloor /* 161 */ LS_NOP, // Sector_SetContents /* 162 */ LS_NOP, // Reserved Doom64 branch diff --git a/src/p_local.h b/src/p_local.h index 93bbbbf11..41f980d44 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -323,6 +323,7 @@ enum // P_LineAttack flags LAF_NORANDOMPUFFZ = 2, LAF_NOIMPACTDECAL = 4, LAF_NOINTERACT = 8, + LAF_TARGETISSOURCE = 16, }; AActor *P_LineAttack(AActor *t1, DAngle angle, double distance, DAngle pitch, int damage, FName damageType, PClassActor *pufftype, int flags = 0, FTranslatedLineTarget *victim = NULL, int *actualdamage = NULL); diff --git a/src/p_map.cpp b/src/p_map.cpp index 85c3e3da8..913840e59 100644 --- a/src/p_map.cpp +++ b/src/p_map.cpp @@ -82,6 +82,56 @@ static FRandom pr_crunch("DoCrunch"); TArray spechit; TArray portalhit; + +//========================================================================== +// +// CanCollideWith +// +// Checks if an actor can collide with another one, calling virtual script functions to check. +// +//========================================================================== + +DEFINE_ACTION_FUNCTION(AActor, CanCollideWith) +{ + // No need to check the parameters, as they are not even used. + ACTION_RETURN_BOOL(true); +} + +bool P_CanCollideWith(AActor *tmthing, AActor *thing) +{ + static unsigned VIndex = ~0u; + if (VIndex == ~0u) + { + VIndex = GetVirtualIndex(RUNTIME_CLASS(AActor), "CanCollideWith"); + assert(VIndex != ~0u); + } + + VMValue params[3] = { tmthing, thing, false }; + VMReturn ret; + int retval; + ret.IntAt(&retval); + + auto clss = tmthing->GetClass(); + VMFunction *func = clss->Virtuals.Size() > VIndex ? clss->Virtuals[VIndex] : nullptr; + if (func != nullptr) + { + GlobalVMStack.Call(func, params, 3, &ret, 1, nullptr); + if (!retval) return false; + } + std::swap(params[0].a, params[1].a); + params[2].i = true; + + // re-get for the other actor. + clss = thing->GetClass(); + func = clss->Virtuals.Size() > VIndex ? clss->Virtuals[VIndex] : nullptr; + if (func != nullptr) + { + GlobalVMStack.Call(func, params, 3, &ret, 1, nullptr); + if (!retval) return false; + } + return true; +} + //========================================================================== // // FindRefPoint @@ -402,6 +452,9 @@ bool P_TeleportMove(AActor* thing, const DVector3 &pos, bool telefrag, bool modi } } + if (!P_CanCollideWith(tmf.thing, th)) + continue; + // monsters don't stomp things except on boss level // [RH] Some Heretic/Hexen monsters can telestomp // ... and some items can never be telefragged while others will be telefragged by everything that teleports upon them. @@ -1147,12 +1200,6 @@ static bool CanAttackHurt(AActor *victim, AActor *shooter) // //========================================================================== -DEFINE_ACTION_FUNCTION(AActor, CanCollideWith) -{ - // No need to check the parameters, as they are not even used. - ACTION_RETURN_BOOL(true); -} - bool PIT_CheckThing(FMultiBlockThingsIterator &it, FMultiBlockThingsIterator::CheckResult &cres, const FBoundingBox &box, FCheckPosition &tm) { AActor *thing = cres.thing; @@ -1257,36 +1304,7 @@ bool PIT_CheckThing(FMultiBlockThingsIterator &it, FMultiBlockThingsIterator::Ch if (((thing->flags & MF_SOLID) || (thing->flags6 & (MF6_TOUCHY | MF6_BUMPSPECIAL))) && ((tm.thing->flags & (MF_SOLID|MF_MISSILE)) || (tm.thing->flags2 & MF2_BLASTED) || (tm.thing->flags6 & MF6_BLOCKEDBYSOLIDACTORS) || (tm.thing->BounceFlags & BOUNCE_MBF))) { - static unsigned VIndex = ~0u; - if (VIndex == ~0u) - { - VIndex = GetVirtualIndex(RUNTIME_CLASS(AActor), "CanCollideWith"); - assert(VIndex != ~0u); - } - - VMValue params[3] = { tm.thing, thing, false }; - VMReturn ret; - int retval; - ret.IntAt(&retval); - - auto clss = tm.thing->GetClass(); - VMFunction *func = clss->Virtuals.Size() > VIndex ? clss->Virtuals[VIndex] : nullptr; - if (func != nullptr) - { - GlobalVMStack.Call(func, params, 3, &ret, 1, nullptr); - if (!retval) return true; - } - std::swap(params[0].a, params[1].a); - params[2].i = true; - - // re-get for the other actor. - clss = thing->GetClass(); - func = clss->Virtuals.Size() > VIndex ? clss->Virtuals[VIndex] : nullptr; - if (func != nullptr) - { - GlobalVMStack.Call(func, params, 3, &ret, 1, nullptr); - if (!retval) return true; - } + if (!P_CanCollideWith(tm.thing, thing)) return true; } @@ -1959,6 +1977,12 @@ bool P_TestMobjZ(AActor *actor, bool quick, AActor **pOnmobj) { // something higher is in the way continue; } + else if (!P_CanCollideWith(actor, thing)) + { // If they cannot collide, they cannot block each other. + continue; + } + + onmobj = thing; if (quick) break; } @@ -4476,7 +4500,9 @@ AActor *P_LineAttack(AActor *t1, DAngle angle, double distance, puff = P_SpawnPuff(t1, pufftype, bleedpos, 0., 0., 2, puffFlags | PF_HITTHING | PF_TEMPORARY); killPuff = true; } - newdam = P_DamageMobj(trace.Actor, puff ? puff : t1, t1, damage, damageType, dmgflags|DMG_USEANGLE, trace.SrcAngleFromTarget); + auto src = t1; + if ((flags & LAF_TARGETISSOURCE) && t1 && t1->target) src = t1->target; + newdam = P_DamageMobj(trace.Actor, puff ? puff : t1, src, damage, damageType, dmgflags|DMG_USEANGLE, trace.SrcAngleFromTarget); if (actualdamage != NULL) { *actualdamage = newdam; @@ -5943,6 +5969,9 @@ int P_PushUp(AActor *thing, FChangePosition *cpos) continue; if ((thing->flags & MF_MISSILE) && (intersect->flags2 & MF2_REFLECTIVE) && (intersect->flags7 & MF7_THRUREFLECT)) continue; + if (!P_CanCollideWith(thing, intersect)) + continue; + if (!(intersect->flags2 & MF2_PASSMOBJ) || (!(intersect->flags3 & MF3_ISMONSTER) && intersect->Mass > mymass) || (intersect->flags4 & MF4_ACTLIKEBRIDGE) @@ -5989,6 +6018,18 @@ int P_PushDown(AActor *thing, FChangePosition *cpos) for (; firstintersect < lastintersect; firstintersect++) { AActor *intersect = intersectors[firstintersect]; + + // [GZ] Skip this iteration for THRUSPECIES things + // Should there be MF2_THRUGHOST / MF3_GHOST checks there too for consistency? + // Or would that risk breaking established behavior? THRUGHOST, like MTHRUSPECIES, + // is normally for projectiles which would have exploded by now anyway... + if (thing->flags6 & MF6_THRUSPECIES && thing->GetSpecies() == intersect->GetSpecies()) + continue; + if ((thing->flags & MF_MISSILE) && (intersect->flags2 & MF2_REFLECTIVE) && (intersect->flags7 & MF7_THRUREFLECT)) + continue; + if (!P_CanCollideWith(thing, intersect)) + continue; + if (!(intersect->flags2 & MF2_PASSMOBJ) || (!(intersect->flags3 & MF3_ISMONSTER) && intersect->Mass > mymass) || (intersect->flags4 & MF4_ACTLIKEBRIDGE) diff --git a/src/p_portals.cpp b/src/p_portals.cpp new file mode 100644 index 000000000..92ecfd075 --- /dev/null +++ b/src/p_portals.cpp @@ -0,0 +1,35 @@ +/* +** p_portals.cpp +** +** portal stuff +** +**--------------------------------------------------------------------------- +** Copyright 2015 Christoph Oelckers +** 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 author 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/src/p_pspr.h b/src/p_pspr.h index 48c67be95..2b84f7949 100644 --- a/src/p_pspr.h +++ b/src/p_pspr.h @@ -73,6 +73,7 @@ public: int GetID() const { return ID; } int GetSprite() const { return Sprite; } int GetFrame() const { return Frame; } + int GetTics() const { return Tics; } FState* GetState() const { return State; } DPSprite* GetNext() { return Next; } AActor* GetCaller() { return Caller; } diff --git a/src/p_saveg.cpp b/src/p_saveg.cpp index c2f79a5c6..59e83d9e7 100644 --- a/src/p_saveg.cpp +++ b/src/p_saveg.cpp @@ -271,6 +271,8 @@ FSerializer &Serialize(FSerializer &arc, const char *key, sector_t &p, sector_t .Terrain("floorterrain", p.terrainnum[0], &def->terrainnum[0]) .Terrain("ceilingterrain", p.terrainnum[1], &def->terrainnum[1]) ("scrolls", scroll, nul) + // GZDoom exclusive: + .Array("reflect", p.reflect, def->reflect, 2) .EndObject(); if (arc.isReading() && !scroll.isZero()) diff --git a/src/p_spec.cpp b/src/p_spec.cpp index e4aea5595..ccfafedac 100644 --- a/src/p_spec.cpp +++ b/src/p_spec.cpp @@ -982,6 +982,23 @@ static void CopyPortal(int sectortag, int plane, unsigned pnum, double alpha, bo } } } + if (tolines && lines[j].special == Sector_SetPortal && + lines[j].args[1] == 5 && + lines[j].args[3] == sectortag) + { + if (lines[j].args[0] == 0) + { + lines[j].portaltransferred = pnum; + } + else + { + FLineIdIterator itr(lines[j].args[0]); + while ((s = itr.Next()) >= 0) + { + lines[s].portaltransferred = pnum; + } + } + } } } @@ -1232,6 +1249,7 @@ void P_SpawnSpecials (void) // Init special SECTORs. sector = sectors; + for (i = 0; i < numsectors; i++, sector++) { if (sector->special == 0) diff --git a/src/p_user.cpp b/src/p_user.cpp index 6db4a57f5..c8f30e0d7 100644 --- a/src/p_user.cpp +++ b/src/p_user.cpp @@ -1897,11 +1897,12 @@ void P_CalcHeight (player_t *player) return; } + //[SP] Added (x*player->mo->ViewBob) to allow DECORATE changes to view bobbing speed. if (still) { if (player->health > 0) { - angle = level.time / (120 * TICRATE / 35.) * 360.; + angle = level.time / (120 * TICRATE / 35.) * 360. * player->mo->ViewBob; bob = player->userinfo.GetStillBob() * angle.Sin(); } else @@ -1911,7 +1912,7 @@ void P_CalcHeight (player_t *player) } else { - angle = level.time / (20 * TICRATE / 35.) * 360.; + angle = level.time / (20 * TICRATE / 35.) * 360. * player->mo->ViewBob; bob = player->bob * angle.Sin() * (player->mo->waterlevel > 1 ? 0.25f : 0.5f); } diff --git a/src/portal.cpp b/src/portal.cpp index 4b8a81dc1..121b05e19 100644 --- a/src/portal.cpp +++ b/src/portal.cpp @@ -1232,8 +1232,8 @@ bool P_CollectConnectedGroups(int startgroup, const DVector3 &position, double u { int othergroup = wsec->GetOppositePortalGroup(sector_t::floor); DVector2 pos = Displacements.getOffset(startgroup, othergroup) + position; - processMask.setBit(othergroup | FPortalGroupArray::LOWER); - out.Add(othergroup); + processMask.setBit(othergroup); + out.Add(othergroup | FPortalGroupArray::LOWER); wsec = P_PointInSector(pos); // get lower sector at the exact spot we want to check and repeat retval = true; } diff --git a/src/posix/cocoa/i_common.h b/src/posix/cocoa/i_common.h index 4a558cf24..9cedb0262 100644 --- a/src/posix/cocoa/i_common.h +++ b/src/posix/cocoa/i_common.h @@ -190,6 +190,9 @@ typedef NSInteger NSApplicationActivationPolicy; static const NSWindowCollectionBehavior NSWindowCollectionBehaviorFullScreenAuxiliary = NSWindowCollectionBehavior(1 << 8); +static const NSOpenGLPixelFormatAttribute NSOpenGLPFAOpenGLProfile(96); +static const NSOpenGLPixelFormatAttribute NSOpenGLProfileVersion3_2Core(0x3200); + #endif // prior to 10.7 #endif // COCOA_I_COMMON_INCLUDED diff --git a/src/posix/cocoa/i_video.mm b/src/posix/cocoa/i_video.mm index 5e073daf3..5875e87b8 100644 --- a/src/posix/cocoa/i_video.mm +++ b/src/posix/cocoa/i_video.mm @@ -31,10 +31,11 @@ ** */ +#include "gl/system/gl_load.h" + #include "i_common.h" #import -#import // Avoid collision between DObject class and Objective-C #define Class ObjectClass @@ -45,6 +46,7 @@ #include "hardware.h" #include "i_system.h" #include "m_argv.h" +#include "m_png.h" #include "r_renderer.h" #include "r_swrenderer.h" #include "st_console.h" @@ -56,6 +58,14 @@ #include "v_video.h" #include "version.h" +#include "gl/system/gl_system.h" +#include "gl/data/gl_vertexbuffer.h" +#include "gl/renderer/gl_renderer.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_interface.h" +#include "gl/textures/gl_samplers.h" +#include "gl/utility/gl_clock.h" + #undef Class @@ -91,11 +101,23 @@ @end +DFrameBuffer *CreateGLSWFrameBuffer(int width, int height, bool bgra, bool fullscreen); EXTERN_CVAR(Bool, ticker ) EXTERN_CVAR(Bool, vid_vsync) EXTERN_CVAR(Bool, vid_hidpi) +CUSTOM_CVAR(Bool, swtruecolor, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + // Strictly speaking this doesn't require a mode switch, but it is the easiest + // way to force a CreateFramebuffer call without a lot of refactoring. + extern int NewWidth, NewHeight, NewBits, DisplayBits; + NewWidth = screen->GetWidth(); + NewHeight = screen->GetHeight(); + NewBits = DisplayBits; + setmodeneeded = true; +} + CUSTOM_CVAR(Bool, fullscreen, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) { extern int NewWidth, NewHeight, NewBits, DisplayBits; @@ -111,6 +133,36 @@ CUSTOM_CVAR(Bool, vid_autoswitch, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_ Printf("You must restart " GAMENAME " to apply graphics switching mode\n"); } +static int s_currentRenderer; + +CUSTOM_CVAR(Int, vid_renderer, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + // 0: Software renderer + // 1: OpenGL renderer + + if (self != s_currentRenderer) + { + switch (self) + { + case 0: + Printf("Switching to software renderer...\n"); + break; + case 1: + Printf("Switching to OpenGL renderer...\n"); + break; + default: + Printf("Unknown renderer (%d). Falling back to software renderer...\n", + static_cast(vid_renderer)); + self = 0; + break; + } + + Printf("You must restart " GAMENAME " to switch the renderer\n"); + } +} + +EXTERN_CVAR(Bool, gl_smooth_rendered) + RenderBufferOptions rbOpts; @@ -124,7 +176,7 @@ namespace const NSInteger LEVEL_WINDOWED = NSNormalWindowLevel; const NSUInteger STYLE_MASK_FULLSCREEN = NSBorderlessWindowMask; - const NSUInteger STYLE_MASK_WINDOWED = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask; + const NSUInteger STYLE_MASK_WINDOWED = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask; } @@ -187,19 +239,18 @@ namespace @end - // --------------------------------------------------------------------------- class CocoaVideo : public IVideo { public: - explicit CocoaVideo(int multisample); + CocoaVideo(); virtual EDisplayType GetDisplayType() { return DISPLAY_Both; } virtual void SetWindowedScale(float scale); - virtual DFrameBuffer* CreateFrameBuffer(int width, int height, bool fs, DFrameBuffer* old); + virtual DFrameBuffer* CreateFrameBuffer(int width, int height, bool bgra, bool fs, DFrameBuffer* old); virtual void StartModeIterator(int bits, bool fullscreen); virtual bool NextMode(int* width, int* height, bool* letterbox); @@ -235,10 +286,13 @@ private: }; +// --------------------------------------------------------------------------- + + class CocoaFrameBuffer : public DFrameBuffer { public: - CocoaFrameBuffer(int width, int height, bool fullscreen); + CocoaFrameBuffer(int width, int height, bool bgra, bool fullscreen); ~CocoaFrameBuffer(); virtual bool Lock(bool buffer); @@ -417,23 +471,14 @@ CocoaWindow* CreateCocoaWindow(const NSUInteger styleMask) return window; } -} // unnamed namespace - - -// --------------------------------------------------------------------------- - - -CocoaVideo::CocoaVideo(const int multisample) -: m_window(CreateCocoaWindow(STYLE_MASK_WINDOWED)) -, m_width(-1) -, m_height(-1) -, m_fullscreen(false) -, m_hiDPI(false) +enum OpenGLProfile { - memset(&m_modeIterator, 0, sizeof m_modeIterator); - - // Set attributes for OpenGL context + Core, + Legacy +}; +NSOpenGLPixelFormat* CreatePixelFormat(const OpenGLProfile profile) +{ NSOpenGLPixelFormatAttribute attributes[16]; size_t i = 0; @@ -450,20 +495,59 @@ CocoaVideo::CocoaVideo(const int multisample) attributes[i++] = NSOpenGLPFAAllowOfflineRenderers; } - if (multisample) + if (NSAppKitVersionNumber >= AppKit10_7 && OpenGLProfile::Core == profile) { - attributes[i++] = NSOpenGLPFAMultisample; - attributes[i++] = NSOpenGLPFASampleBuffers; - attributes[i++] = NSOpenGLPixelFormatAttribute(1); - attributes[i++] = NSOpenGLPFASamples; - attributes[i++] = NSOpenGLPixelFormatAttribute(multisample); + NSOpenGLPixelFormatAttribute profile = NSOpenGLProfileVersion3_2Core; + const char* const glversion = Args->CheckValue("-glversion"); + + if (nullptr != glversion) + { + const double version = strtod(glversion, nullptr) + 0.01; + if (version < 3.2) + { + profile = NSOpenGLProfileVersionLegacy; + } + } + + attributes[i++] = NSOpenGLPFAOpenGLProfile; + attributes[i++] = profile; } attributes[i] = NSOpenGLPixelFormatAttribute(0); - // Create OpenGL context and view + return [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes]; +} - NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes]; +} // unnamed namespace + + +// --------------------------------------------------------------------------- + + +CocoaVideo::CocoaVideo() +: m_window(CreateCocoaWindow(STYLE_MASK_WINDOWED)) +, m_width(-1) +, m_height(-1) +, m_fullscreen(false) +, m_hiDPI(false) +{ + memset(&m_modeIterator, 0, sizeof m_modeIterator); + + // Create OpenGL pixel format + + NSOpenGLPixelFormat* pixelFormat = CreatePixelFormat(OpenGLProfile::Core); + + if (nil == pixelFormat) + { + pixelFormat = CreatePixelFormat(OpenGLProfile::Legacy); + + if (nil == pixelFormat) + { + I_FatalError("Cannot OpenGL create pixel format, graphics hardware is not supported"); + } + } + + // Create OpenGL context and view const NSRect contentRect = [m_window contentRectForFrameRect:[m_window frame]]; NSOpenGLView* glView = [[CocoaView alloc] initWithFrame:contentRect @@ -518,14 +602,14 @@ bool CocoaVideo::NextMode(int* const width, int* const height, bool* const lette return false; } -DFrameBuffer* CocoaVideo::CreateFrameBuffer(const int width, const int height, const bool fullscreen, DFrameBuffer* const old) +DFrameBuffer* CocoaVideo::CreateFrameBuffer(const int width, const int height, const bool bgra, const bool fullscreen, DFrameBuffer* const old) { PalEntry flashColor = 0; int flashAmount = 0; if (NULL != old) { - if (width == m_width && height == m_height) + if (width == m_width && height == m_height && bgra == old->IsBgra()) { SetMode(width, height, fullscreen, vid_hidpi); return old; @@ -542,7 +626,18 @@ DFrameBuffer* CocoaVideo::CreateFrameBuffer(const int width, const int height, c delete old; } - CocoaFrameBuffer* fb = new CocoaFrameBuffer(width, height, fullscreen); + DFrameBuffer* fb = NULL; + + if (1 == s_currentRenderer) + { + fb = new OpenGLFrameBuffer(NULL, width, height, 32, 60, fullscreen); + } + else + { + //fb = new CocoaFrameBuffer(width, height, bgra, fullscreen); + fb = CreateGLSWFrameBuffer(width, height, bgra, fullscreen); + } + fb->SetFlash(flashColor, flashAmount); SetMode(width, height, fullscreen, vid_hidpi); @@ -761,8 +856,11 @@ CocoaVideo* CocoaVideo::GetInstance() } -CocoaFrameBuffer::CocoaFrameBuffer(int width, int height, bool fullscreen) -: DFrameBuffer(width, height) +// --------------------------------------------------------------------------- + + +CocoaFrameBuffer::CocoaFrameBuffer(int width, int height, bool bgra, bool fullscreen) +: DFrameBuffer(width, height, bgra) , m_needPaletteUpdate(false) , m_gamma(0.0f) , m_needGammaUpdate(false) @@ -771,6 +869,14 @@ CocoaFrameBuffer::CocoaFrameBuffer(int width, int height, bool fullscreen) , m_pixelBuffer(new uint8_t[width * height * BYTES_PER_PIXEL]) , m_texture(0) { + static bool isOpenGLInitialized; + + if (!isOpenGLInitialized) + { + ogl_LoadFunctions(); + isOpenGLInitialized = true; + } + glEnable(GL_TEXTURE_RECTANGLE_ARB); glGenTextures(1, &m_texture); @@ -856,8 +962,15 @@ void CocoaFrameBuffer::Update() FlipCycles.Reset(); BlitCycles.Clock(); - GPfx.Convert(MemBuffer, Pitch, m_pixelBuffer, Width * BYTES_PER_PIXEL, - Width, Height, FRACUNIT, FRACUNIT, 0, 0); + if (IsBgra()) + { + CopyWithGammaBgra(m_pixelBuffer, Width * BYTES_PER_PIXEL, m_gammaTable[0], m_gammaTable[1], m_gammaTable[2], m_flashColor, m_flashAmount); + } + else + { + GPfx.Convert(MemBuffer, Pitch, m_pixelBuffer, Width * BYTES_PER_PIXEL, + Width, Height, FRACUNIT, FRACUNIT, 0, 0); + } FlipCycles.Clock(); Flip(); @@ -989,8 +1102,10 @@ void CocoaFrameBuffer::Flip() static const GLenum format = GL_ABGR_EXT; #endif // __LITTLE_ENDIAN__ - glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, - Width, Height, 0, format, GL_UNSIGNED_BYTE, m_pixelBuffer); + if (IsBgra()) + glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, Width, Height, 0, GL_BGRA, GL_UNSIGNED_BYTE, m_pixelBuffer); + else + glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, Width, Height, 0, format, GL_UNSIGNED_BYTE, m_pixelBuffer); glBegin(GL_QUADS); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); @@ -1010,6 +1125,153 @@ void CocoaFrameBuffer::Flip() } +// --------------------------------------------------------------------------- + + +SDLGLFB::SDLGLFB(void*, const int width, const int height, int, int, const bool fullscreen, bool bgra) +: DFrameBuffer(width, height, bgra) +, m_lock(-1) +, m_isUpdatePending(false) +{ + CGGammaValue gammaTable[GAMMA_TABLE_SIZE]; + uint32_t actualChannelSize; + + const CGError result = CGGetDisplayTransferByTable(kCGDirectMainDisplay, GAMMA_CHANNEL_SIZE, + gammaTable, &gammaTable[GAMMA_CHANNEL_SIZE], &gammaTable[GAMMA_CHANNEL_SIZE * 2], &actualChannelSize); + m_supportsGamma = kCGErrorSuccess == result && GAMMA_CHANNEL_SIZE == actualChannelSize; + + if (m_supportsGamma) + { + for (uint32_t i = 0; i < GAMMA_TABLE_SIZE; ++i) + { + m_originalGamma[i] = static_cast(gammaTable[i] * 65535.0f); + } + } +} + +SDLGLFB::SDLGLFB() +{ +} + +SDLGLFB::~SDLGLFB() +{ +} + + +bool SDLGLFB::Lock(bool buffered) +{ + m_lock++; + + Buffer = MemBuffer; + + return true; +} + +void SDLGLFB::Unlock() +{ + if (m_isUpdatePending && 1 == m_lock) + { + Update(); + } + else if (--m_lock <= 0) + { + m_lock = 0; + } +} + +bool SDLGLFB::IsLocked() +{ + return m_lock > 0; +} + + +bool SDLGLFB::IsFullscreen() +{ + return CocoaVideo::IsFullscreen(); +} + +void SDLGLFB::SetVSync(bool vsync) +{ +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 + const long value = vsync ? 1 : 0; +#else // 10.5 or newer + const GLint value = vsync ? 1 : 0; +#endif // prior to 10.5 + + [[NSOpenGLContext currentContext] setValues:&value + forParameter:NSOpenGLCPSwapInterval]; +} + + +void SDLGLFB::InitializeState() +{ +} + +bool SDLGLFB::CanUpdate() +{ + if (m_lock != 1) + { + if (m_lock > 0) + { + m_isUpdatePending = true; + --m_lock; + } + + return false; + } + + return true; +} + +void SDLGLFB::SwapBuffers() +{ + [[NSOpenGLContext currentContext] flushBuffer]; +} + +void SDLGLFB::SetGammaTable(WORD* table) +{ + if (m_supportsGamma) + { + CGGammaValue gammaTable[GAMMA_TABLE_SIZE]; + + for (uint32_t i = 0; i < GAMMA_TABLE_SIZE; ++i) + { + gammaTable[i] = static_cast(table[i] / 65535.0f); + } + + CGSetDisplayTransferByTable(kCGDirectMainDisplay, GAMMA_CHANNEL_SIZE, + gammaTable, &gammaTable[GAMMA_CHANNEL_SIZE], &gammaTable[GAMMA_CHANNEL_SIZE * 2]); + } +} + +void SDLGLFB::ResetGammaTable() +{ + if (m_supportsGamma) + { + SetGammaTable(m_originalGamma); + } +} + +int SDLGLFB::GetClientWidth() +{ + NSView *view = [[NSOpenGLContext currentContext] view]; + NSRect backingBounds = [view convertRectToBacking: [view bounds]]; + int clientWidth = (int)backingBounds.size.width; + return clientWidth > 0 ? clientWidth : Width; +} + +int SDLGLFB::GetClientHeight() +{ + NSView *view = [[NSOpenGLContext currentContext] view]; + NSRect backingBounds = [view convertRectToBacking: [view bounds]]; + int clientHeight = (int)backingBounds.size.height; + return clientHeight > 0 ? clientHeight : Height; +} + + +// --------------------------------------------------------------------------- + + ADD_STAT(blit) { FString result; @@ -1021,6 +1283,9 @@ ADD_STAT(blit) IVideo* Video; +// --------------------------------------------------------------------------- + + void I_ShutdownGraphics() { if (NULL != screen) @@ -1041,7 +1306,7 @@ void I_InitGraphics() val.Bool = !!Args->CheckParm("-devparm"); ticker.SetGenericRepDefault(val, CVAR_Bool); - Video = new CocoaVideo(0); + Video = new CocoaVideo; atterm(I_ShutdownGraphics); } @@ -1054,9 +1319,15 @@ static void I_DeleteRenderer() void I_CreateRenderer() { + s_currentRenderer = vid_renderer; + if (NULL == Renderer) { - Renderer = new FSoftwareRenderer; + extern FRenderer* gl_CreateInterface(); + + Renderer = 1 == s_currentRenderer + ? gl_CreateInterface() + : new FSoftwareRenderer; atterm(I_DeleteRenderer); } } @@ -1064,7 +1335,7 @@ void I_CreateRenderer() DFrameBuffer* I_SetMode(int &width, int &height, DFrameBuffer* old) { - return Video->CreateFrameBuffer(width, height, fullscreen, old); + return Video->CreateFrameBuffer(width, height, swtruecolor, fullscreen, old); } bool I_CheckResolution(const int width, const int height, const int bits) @@ -1128,6 +1399,9 @@ void I_ClosestResolution(int *width, int *height, int bits) } +// --------------------------------------------------------------------------- + + EXTERN_CVAR(Int, vid_maxfps); EXTERN_CVAR(Bool, cl_capfps); @@ -1166,6 +1440,9 @@ CUSTOM_CVAR(Bool, vid_hidpi, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) } +// --------------------------------------------------------------------------- + + CCMD(vid_listmodes) { if (Video == NULL) diff --git a/src/posix/cocoa/sdlglvideo.h b/src/posix/cocoa/sdlglvideo.h new file mode 100644 index 000000000..43f2c9c43 --- /dev/null +++ b/src/posix/cocoa/sdlglvideo.h @@ -0,0 +1,90 @@ +/* + ** sdlglvideo.h + ** + **--------------------------------------------------------------------------- + ** Copyright 2012-2014 Alexey Lysiuk + ** 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 author 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. + **--------------------------------------------------------------------------- + ** + */ + + +// IMPORTANT NOTE! +// This file was intentially named sdlglvideo.h but it has nothing with SDL +// The name was selected to avoid spreding of changes over the project +// The same applies to SDLGLFB class +// See gl/system/gl_framebuffer.h for details about its usage + + +#ifndef COCOA_SDLGLVIDEO_H_INCLUDED +#define COCOA_SDLGLVIDEO_H_INCLUDED + +#include "v_video.h" + +#include "gl/shaders/gl_shader.h" +#include "gl/textures/gl_hwtexture.h" + + +class SDLGLFB : public DFrameBuffer +{ +public: + // This must have the same parameters as the Windows version, even if they are not used! + SDLGLFB(void *hMonitor, int width, int height, int, int, bool fullscreen, bool bgra); + ~SDLGLFB(); + + virtual bool Lock(bool buffered = true); + virtual void Unlock(); + virtual bool IsLocked(); + + virtual bool IsFullscreen(); + virtual void SetVSync(bool vsync); + + int GetClientWidth(); + int GetClientHeight(); + +protected: + int m_lock; + bool m_isUpdatePending; + + static const uint32_t GAMMA_CHANNEL_SIZE = 256; + static const uint32_t GAMMA_CHANNEL_COUNT = 3; + static const uint32_t GAMMA_TABLE_SIZE = GAMMA_CHANNEL_SIZE * GAMMA_CHANNEL_COUNT; + + bool m_supportsGamma; + WORD m_originalGamma[GAMMA_TABLE_SIZE]; + + SDLGLFB(); + + void InitializeState(); + + bool CanUpdate(); + void SwapBuffers(); + + void SetGammaTable(WORD* table); + void ResetGammaTable(); +}; + +#endif // COCOA_SDLGLVIDEO_H_INCLUDED diff --git a/src/posix/hardware.h b/src/posix/hardware.h index 618941fe5..3c06cb6c6 100644 --- a/src/posix/hardware.h +++ b/src/posix/hardware.h @@ -74,7 +74,7 @@ class IVideo virtual EDisplayType GetDisplayType () = 0; virtual void SetWindowedScale (float scale) = 0; - virtual DFrameBuffer *CreateFrameBuffer (int width, int height, bool fs, DFrameBuffer *old) = 0; + virtual DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old) = 0; virtual void StartModeIterator (int bits, bool fs) = 0; virtual bool NextMode (int *width, int *height, bool *letterbox) = 0; diff --git a/src/posix/sdl/hardware.cpp b/src/posix/sdl/hardware.cpp index 8bae3f900..8fbb7c08a 100644 --- a/src/posix/sdl/hardware.cpp +++ b/src/posix/sdl/hardware.cpp @@ -36,6 +36,7 @@ #include #include +#include "version.h" #include "hardware.h" #include "i_video.h" #include "i_system.h" @@ -46,15 +47,50 @@ #include "v_text.h" #include "doomstat.h" #include "m_argv.h" +#include "sdlglvideo.h" #include "r_renderer.h" #include "r_swrenderer.h" EXTERN_CVAR (Bool, ticker) EXTERN_CVAR (Bool, fullscreen) +EXTERN_CVAR (Bool, swtruecolor) EXTERN_CVAR (Float, vid_winscale) +CVAR (Bool, vid_sdl, 0, 0); + IVideo *Video; +extern int NewWidth, NewHeight, NewBits, DisplayBits; +bool V_DoModeSetup (int width, int height, int bits); +void I_RestartRenderer(); + +int currentrenderer; + +// [ZDoomGL] +CUSTOM_CVAR (Int, vid_renderer, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + // 0: Software renderer + // 1: OpenGL renderer + + if (self != currentrenderer) + { + switch (self) + { + case 0: + Printf("Switching to software renderer...\n"); + break; + case 1: + Printf("Switching to OpenGL renderer...\n"); + break; + default: + Printf("Unknown renderer (%d). Falling back to software renderer...\n", (int) vid_renderer); + self = 0; // make sure to actually switch to the software renderer + break; + } + Printf("You must restart " GAMENAME " to switch the renderer\n"); + } +} + void I_ShutdownGraphics () { if (screen) @@ -84,8 +120,11 @@ void I_InitGraphics () val.Bool = !!Args->CheckParm ("-devparm"); ticker.SetGenericRepDefault (val, CVAR_Bool); - - Video = new SDLVideo (0); + + //currentrenderer = vid_renderer; + if (currentrenderer==1 || vid_sdl==0) Video = new SDLGLVideo(0); + else Video = new SDLVideo (0); + if (Video == NULL) I_FatalError ("Failed to initialize display"); @@ -101,9 +140,11 @@ static void I_DeleteRenderer() void I_CreateRenderer() { + currentrenderer = vid_renderer; if (Renderer == NULL) { - Renderer = new FSoftwareRenderer; + if (currentrenderer==1) Renderer = gl_CreateInterface(); + else Renderer = new FSoftwareRenderer; atterm(I_DeleteRenderer); } } @@ -128,7 +169,7 @@ DFrameBuffer *I_SetMode (int &width, int &height, DFrameBuffer *old) fs = fullscreen; break; } - DFrameBuffer *res = Video->CreateFrameBuffer (width, height, fs, old); + DFrameBuffer *res = Video->CreateFrameBuffer (width, height, swtruecolor, fs, old); /* Right now, CreateFrameBuffer cannot return NULL if (res == NULL) @@ -282,6 +323,16 @@ CUSTOM_CVAR (Int, vid_maxfps, 200, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) extern int NewWidth, NewHeight, NewBits, DisplayBits; +CUSTOM_CVAR(Bool, swtruecolor, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +{ + // Strictly speaking this doesn't require a mode switch, but it is the easiest + // way to force a CreateFramebuffer call without a lot of refactoring. + NewWidth = screen->GetWidth(); + NewHeight = screen->GetHeight(); + NewBits = DisplayBits; + setmodeneeded = true; +} + CUSTOM_CVAR (Bool, fullscreen, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) { NewWidth = screen->GetWidth(); diff --git a/src/posix/sdl/sdlglvideo.cpp b/src/posix/sdl/sdlglvideo.cpp new file mode 100644 index 000000000..7858fdad9 --- /dev/null +++ b/src/posix/sdl/sdlglvideo.cpp @@ -0,0 +1,493 @@ + +// HEADER FILES ------------------------------------------------------------ + +#include "doomtype.h" + +#include "templates.h" +#include "i_system.h" +#include "i_video.h" +#include "v_video.h" +#include "v_pfx.h" +#include "stats.h" +#include "version.h" +#include "c_console.h" + +#include "sdlglvideo.h" +#include "gl/system/gl_system.h" +#include "r_defs.h" +#include "gl/gl_functions.h" +//#include "gl/gl_intern.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/shaders/gl_shader.h" +#include "gl/utility/gl_templates.h" +#include "gl/textures/gl_material.h" +#include "gl/system/gl_cvars.h" + +// MACROS ------------------------------------------------------------------ + +// TYPES ------------------------------------------------------------------- + +IMPLEMENT_CLASS(SDLGLFB, true, false) + +struct MiniModeInfo +{ + WORD Width, Height; +}; + +// PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- + +// PRIVATE FUNCTION PROTOTYPES --------------------------------------------- + +// EXTERNAL DATA DECLARATIONS ---------------------------------------------- + +extern IVideo *Video; +// extern int vid_renderer; + +EXTERN_CVAR (Float, Gamma) +EXTERN_CVAR (Int, vid_adapter) +EXTERN_CVAR (Int, vid_displaybits) +EXTERN_CVAR (Int, vid_renderer) +EXTERN_CVAR (Int, vid_maxfps) +EXTERN_CVAR (Bool, cl_capfps) + +DFrameBuffer *CreateGLSWFrameBuffer(int width, int height, bool bgra, bool fullscreen); + +// PUBLIC DATA DEFINITIONS ------------------------------------------------- + +CUSTOM_CVAR(Bool, gl_debug, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + Printf("This won't take effect until " GAMENAME " is restarted.\n"); +} + +// PRIVATE DATA DEFINITIONS ------------------------------------------------ + +// Dummy screen sizes to pass when windowed +static MiniModeInfo WinModes[] = +{ + { 320, 200 }, + { 320, 240 }, + { 400, 225 }, // 16:9 + { 400, 300 }, + { 480, 270 }, // 16:9 + { 480, 360 }, + { 512, 288 }, // 16:9 + { 512, 384 }, + { 640, 360 }, // 16:9 + { 640, 400 }, + { 640, 480 }, + { 720, 480 }, // 16:10 + { 720, 540 }, + { 800, 450 }, // 16:9 + { 800, 480 }, + { 800, 500 }, // 16:10 + { 800, 600 }, + { 848, 480 }, // 16:9 + { 960, 600 }, // 16:10 + { 960, 720 }, + { 1024, 576 }, // 16:9 + { 1024, 600 }, // 17:10 + { 1024, 640 }, // 16:10 + { 1024, 768 }, + { 1088, 612 }, // 16:9 + { 1152, 648 }, // 16:9 + { 1152, 720 }, // 16:10 + { 1152, 864 }, + { 1280, 720 }, // 16:9 + { 1280, 854 }, + { 1280, 800 }, // 16:10 + { 1280, 960 }, + { 1280, 1024 }, // 5:4 + { 1360, 768 }, // 16:9 + { 1366, 768 }, + { 1400, 787 }, // 16:9 + { 1400, 875 }, // 16:10 + { 1400, 1050 }, + { 1440, 900 }, + { 1440, 960 }, + { 1440, 1080 }, + { 1600, 900 }, // 16:9 + { 1600, 1000 }, // 16:10 + { 1600, 1200 }, + { 1920, 1080 }, + { 1920, 1200 }, + { 2048, 1536 }, + { 2560, 1440 }, + { 2560, 1600 }, + { 2560, 2048 }, + { 2880, 1800 }, + { 3200, 1800 }, + { 3840, 2160 }, + { 3840, 2400 }, + { 4096, 2160 }, + { 5120, 2880 } +}; + +// CODE -------------------------------------------------------------------- + +SDLGLVideo::SDLGLVideo (int parm) +{ + IteratorBits = 0; + if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { + fprintf( stderr, "Video initialization failed: %s\n", + SDL_GetError( ) ); + } +#ifndef _WIN32 + // mouse cursor is visible by default on linux systems, we disable it by default + SDL_ShowCursor (0); +#endif +} + +SDLGLVideo::~SDLGLVideo () +{ + if (GLRenderer != NULL) GLRenderer->FlushTextures(); +} + +void SDLGLVideo::StartModeIterator (int bits, bool fs) +{ + IteratorMode = 0; + IteratorBits = bits; +} + +bool SDLGLVideo::NextMode (int *width, int *height, bool *letterbox) +{ + if (IteratorBits != 8) + return false; + + if ((unsigned)IteratorMode < sizeof(WinModes)/sizeof(WinModes[0])) + { + *width = WinModes[IteratorMode].Width; + *height = WinModes[IteratorMode].Height; + ++IteratorMode; + return true; + } + return false; +} + +DFrameBuffer *SDLGLVideo::CreateFrameBuffer (int width, int height, bool bgra, bool fullscreen, DFrameBuffer *old) +{ + static int retry = 0; + static int owidth, oheight; + + PalEntry flashColor; +// int flashAmount; + + if (old != NULL) + { // Reuse the old framebuffer if its attributes are the same + SDLGLFB *fb = static_cast (old); + if (fb->Width == width && + fb->Height == height) + { + bool fsnow = (SDL_GetWindowFlags (fb->Screen) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; + + if (fsnow != fullscreen) + { + SDL_SetWindowFullscreen (fb->Screen, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); + } + return old; + } +// old->GetFlash (flashColor, flashAmount); + delete old; + } + else + { + flashColor = 0; +// flashAmount = 0; + } + + SDLGLFB *fb; + if (vid_renderer == 1) + fb = new OpenGLFrameBuffer (0, width, height, 32, 60, fullscreen); + else + fb = (SDLGLFB*)CreateGLSWFrameBuffer (width, height, bgra, fullscreen); + + retry = 0; + + // If we could not create the framebuffer, try again with slightly + // different parameters in this order: + // 1. Try with the closest size + // 2. Try in the opposite screen mode with the original size + // 3. Try in the opposite screen mode with the closest size + // This is a somewhat confusing mass of recursion here. + + while (fb == NULL || !fb->IsValid ()) + { + if (fb != NULL) + { + delete fb; + } + + switch (retry) + { + case 0: + owidth = width; + oheight = height; + case 2: + // Try a different resolution. Hopefully that will work. + I_ClosestResolution (&width, &height, 8); + break; + + case 1: + // Try changing fullscreen mode. Maybe that will work. + width = owidth; + height = oheight; + fullscreen = !fullscreen; + break; + + default: + // I give up! + I_FatalError ("Could not create new screen (%d x %d)", owidth, oheight); + + fprintf( stderr, "!!! [SDLGLVideo::CreateFrameBuffer] Got beyond I_FatalError !!!" ); + return NULL; //[C] actually this shouldn't be reached; probably should be replaced with an ASSERT + } + + ++retry; + fb = static_cast(CreateFrameBuffer (width, height, false, fullscreen, NULL)); + } + +// fb->SetFlash (flashColor, flashAmount); + return fb; +} + +void SDLGLVideo::SetWindowedScale (float scale) +{ +} + +bool SDLGLVideo::SetResolution (int width, int height, int bits) +{ + // FIXME: Is it possible to do this without completely destroying the old + // interface? +#ifndef NO_GL + + if (GLRenderer != NULL) GLRenderer->FlushTextures(); + I_ShutdownGraphics(); + + Video = new SDLGLVideo(0); + if (Video == NULL) I_FatalError ("Failed to initialize display"); + +#if (defined(WINDOWS)) || defined(WIN32) + bits=32; +#else + bits=24; +#endif + + V_DoModeSetup(width, height, bits); +#endif + return true; // We must return true because the old video context no longer exists. +} + +//========================================================================== +// +// +// +//========================================================================== + +bool SDLGLVideo::SetupPixelFormat(bool allowsoftware, int multisample) +{ + SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); + SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); + SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); + SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); + SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24 ); + SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8 ); + SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); + if (multisample > 0) { + SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); + SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, multisample ); + } + if (gl_debug) + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool SDLGLVideo::InitHardware (bool allowsoftware, int multisample) +{ + if (!SetupPixelFormat(allowsoftware, multisample)) + { + Printf ("R_OPENGL: Reverting to software mode...\n"); + return false; + } + return true; +} + + +// FrameBuffer implementation ----------------------------------------------- + +SDLGLFB::SDLGLFB (void *, int width, int height, int, int, bool fullscreen, bool bgra) + : DFrameBuffer (width, height, bgra) +{ + int i; + + m_Lock=0; + + UpdatePending = false; + + if (!static_cast(Video)->InitHardware(false, 0)) + { + vid_renderer = 0; + return; + } + + FString caption; + caption.Format(GAMESIG " %s (%s)", GetVersionString(), GetGitTime()); + Screen = SDL_CreateWindow (caption, + SDL_WINDOWPOS_UNDEFINED_DISPLAY(vid_adapter), SDL_WINDOWPOS_UNDEFINED_DISPLAY(vid_adapter), + width, height, (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)|SDL_WINDOW_OPENGL); + + if (Screen == NULL) + return; + + GLContext = SDL_GL_CreateContext(Screen); + if (GLContext == NULL) + return; + + m_supportsGamma = -1 != SDL_GetWindowGammaRamp(Screen, m_origGamma[0], m_origGamma[1], m_origGamma[2]); +} + +SDLGLFB::~SDLGLFB () +{ + if (Screen) + { + ResetGammaTable(); + + if (GLContext) + { + SDL_GL_DeleteContext(GLContext); + } + + SDL_DestroyWindow(Screen); + } +} + + + + +void SDLGLFB::InitializeState() +{ +} + +bool SDLGLFB::CanUpdate () +{ + if (m_Lock != 1) + { + if (m_Lock > 0) + { + UpdatePending = true; + --m_Lock; + } + return false; + } + return true; +} + +void SDLGLFB::SetGammaTable(WORD *tbl) +{ + if (m_supportsGamma) + { + SDL_SetWindowGammaRamp(Screen, &tbl[0], &tbl[256], &tbl[512]); + } +} + +void SDLGLFB::ResetGammaTable() +{ + if (m_supportsGamma) + { + SDL_SetWindowGammaRamp(Screen, m_origGamma[0], m_origGamma[1], m_origGamma[2]); + } +} + +bool SDLGLFB::Lock(bool buffered) +{ + m_Lock++; + Buffer = MemBuffer; + return true; +} + +bool SDLGLFB::Lock () +{ + return Lock(false); +} + +void SDLGLFB::Unlock () +{ + if (UpdatePending && m_Lock == 1) + { + Update (); + } + else if (--m_Lock <= 0) + { + m_Lock = 0; + } +} + +bool SDLGLFB::IsLocked () +{ + return m_Lock>0;// true; +} + +bool SDLGLFB::IsFullscreen () +{ + return (SDL_GetWindowFlags (Screen) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; +} + + +bool SDLGLFB::IsValid () +{ + return DFrameBuffer::IsValid() && Screen != NULL; +} + +void SDLGLFB::SetVSync( bool vsync ) +{ +#if defined (__APPLE__) + const GLint value = vsync ? 1 : 0; + CGLSetParameter( CGLGetCurrentContext(), kCGLCPSwapInterval, &value ); +#else + if (vsync) + { + if (SDL_GL_SetSwapInterval(-1) == -1) + SDL_GL_SetSwapInterval(1); + } + else + { + SDL_GL_SetSwapInterval(0); + } +#endif +} + +void SDLGLFB::NewRefreshRate () +{ +} + +void SDLGLFB::SwapBuffers() +{ +#ifndef __APPLE__ + if (vid_maxfps && !cl_capfps) + { + SEMAPHORE_WAIT(FPSLimitSemaphore) + } +#endif + + SDL_GL_SwapWindow (Screen); +} + +int SDLGLFB::GetClientWidth() +{ + int width = 0; + SDL_GL_GetDrawableSize(Screen, &width, nullptr); + return width; +} + +int SDLGLFB::GetClientHeight() +{ + int height = 0; + SDL_GL_GetDrawableSize(Screen, nullptr, &height); + return height; +} diff --git a/src/posix/sdl/sdlglvideo.h b/src/posix/sdl/sdlglvideo.h new file mode 100644 index 000000000..01e70caac --- /dev/null +++ b/src/posix/sdl/sdlglvideo.h @@ -0,0 +1,84 @@ +#ifndef __SDLGLVIDEO_H__ +#define __SDLGLVIDEO_H__ + +#include "hardware.h" +#include "v_video.h" +#include +#include "gl/system/gl_system.h" + +EXTERN_CVAR (Float, dimamount) +EXTERN_CVAR (Color, dimcolor) + +struct FRenderer; +FRenderer *gl_CreateInterface(); + +class SDLGLVideo : public IVideo +{ + public: + SDLGLVideo (int parm); + ~SDLGLVideo (); + + EDisplayType GetDisplayType () { return DISPLAY_Both; } + void SetWindowedScale (float scale); + + DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old); + + void StartModeIterator (int bits, bool fs); + bool NextMode (int *width, int *height, bool *letterbox); + bool SetResolution (int width, int height, int bits); + + bool SetupPixelFormat(bool allowsoftware, int multisample); + bool InitHardware (bool allowsoftware, int multisample); + +private: + int IteratorMode; + int IteratorBits; +}; +class SDLGLFB : public DFrameBuffer +{ + DECLARE_CLASS(SDLGLFB, DFrameBuffer) +public: + // this must have the same parameters as the Windows version, even if they are not used! + SDLGLFB (void *hMonitor, int width, int height, int, int, bool fullscreen, bool bgra); + ~SDLGLFB (); + + void ForceBuffering (bool force); + bool Lock(bool buffered); + bool Lock (); + void Unlock(); + bool IsLocked (); + + bool IsValid (); + bool IsFullscreen (); + + virtual void SetVSync( bool vsync ); + void SwapBuffers(); + + void NewRefreshRate (); + + friend class SDLGLVideo; + + int GetClientWidth(); + int GetClientHeight(); + +protected: + bool CanUpdate(); + void SetGammaTable(WORD *tbl); + void ResetGammaTable(); + void InitializeState(); + + SDLGLFB () {} + BYTE GammaTable[3][256]; + bool UpdatePending; + + SDL_Window *Screen; + + SDL_GLContext GLContext; + + void UpdateColors (); + + int m_Lock; + Uint16 m_origGamma[3][256]; + bool m_supportsGamma; +}; +#endif diff --git a/src/posix/sdl/sdlvideo.cpp b/src/posix/sdl/sdlvideo.cpp index 4a6833026..e127f5685 100644 --- a/src/posix/sdl/sdlvideo.cpp +++ b/src/posix/sdl/sdlvideo.cpp @@ -28,7 +28,7 @@ class SDLFB : public DFrameBuffer { DECLARE_CLASS(SDLFB, DFrameBuffer) public: - SDLFB (int width, int height, bool fullscreen, SDL_Window *oldwin); + SDLFB (int width, int height, bool bgra, bool fullscreen, SDL_Window *oldwin); ~SDLFB (); bool Lock (bool buffer); @@ -258,7 +258,7 @@ bool SDLVideo::NextMode (int *width, int *height, bool *letterbox) return false; } -DFrameBuffer *SDLVideo::CreateFrameBuffer (int width, int height, bool fullscreen, DFrameBuffer *old) +DFrameBuffer *SDLVideo::CreateFrameBuffer (int width, int height, bool bgra, bool fullscreen, DFrameBuffer *old) { static int retry = 0; static int owidth, oheight; @@ -272,7 +272,8 @@ DFrameBuffer *SDLVideo::CreateFrameBuffer (int width, int height, bool fullscree { // Reuse the old framebuffer if its attributes are the same SDLFB *fb = static_cast (old); if (fb->Width == width && - fb->Height == height) + fb->Height == height && + fb->Bgra == bgra) { bool fsnow = (SDL_GetWindowFlags (fb->Screen) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; @@ -297,7 +298,7 @@ DFrameBuffer *SDLVideo::CreateFrameBuffer (int width, int height, bool fullscree flashAmount = 0; } - SDLFB *fb = new SDLFB (width, height, fullscreen, oldwin); + SDLFB *fb = new SDLFB (width, height, bgra, fullscreen, oldwin); // If we could not create the framebuffer, try again with slightly // different parameters in this order: @@ -336,7 +337,7 @@ DFrameBuffer *SDLVideo::CreateFrameBuffer (int width, int height, bool fullscree } ++retry; - fb = static_cast(CreateFrameBuffer (width, height, fullscreen, NULL)); + fb = static_cast(CreateFrameBuffer (width, height, bgra, fullscreen, NULL)); } retry = 0; @@ -351,8 +352,8 @@ void SDLVideo::SetWindowedScale (float scale) // FrameBuffer implementation ----------------------------------------------- -SDLFB::SDLFB (int width, int height, bool fullscreen, SDL_Window *oldwin) - : DFrameBuffer (width, height) +SDLFB::SDLFB (int width, int height, bool bgra, bool fullscreen, SDL_Window *oldwin) + : DFrameBuffer (width, height, bgra) { int i; @@ -495,7 +496,11 @@ void SDLFB::Update () pitch = Surface->pitch; } - if (NotPaletted) + if (Bgra) + { + CopyWithGammaBgra(pixels, pitch, GammaTable[0], GammaTable[1], GammaTable[2], Flash, FlashAmount); + } + else if (NotPaletted) { GPfx.Convert (MemBuffer, Pitch, pixels, pitch, Width, Height, @@ -675,13 +680,20 @@ void SDLFB::ResetSDLRenderer () SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 255); Uint32 fmt; - switch(vid_displaybits) + if (Bgra) { - default: fmt = SDL_PIXELFORMAT_ARGB8888; break; - case 30: fmt = SDL_PIXELFORMAT_ARGB2101010; break; - case 24: fmt = SDL_PIXELFORMAT_RGB888; break; - case 16: fmt = SDL_PIXELFORMAT_RGB565; break; - case 15: fmt = SDL_PIXELFORMAT_ARGB1555; break; + fmt = SDL_PIXELFORMAT_ARGB8888; + } + else + { + switch (vid_displaybits) + { + default: fmt = SDL_PIXELFORMAT_ARGB8888; break; + case 30: fmt = SDL_PIXELFORMAT_ARGB2101010; break; + case 24: fmt = SDL_PIXELFORMAT_RGB888; break; + case 16: fmt = SDL_PIXELFORMAT_RGB565; break; + case 15: fmt = SDL_PIXELFORMAT_ARGB1555; break; + } } Texture = SDL_CreateTexture (Renderer, fmt, SDL_TEXTUREACCESS_STREAMING, Width, Height); diff --git a/src/posix/sdl/sdlvideo.h b/src/posix/sdl/sdlvideo.h index 072167b5a..385733bc1 100644 --- a/src/posix/sdl/sdlvideo.h +++ b/src/posix/sdl/sdlvideo.h @@ -10,7 +10,7 @@ class SDLVideo : public IVideo EDisplayType GetDisplayType () { return DISPLAY_Both; } void SetWindowedScale (float scale); - DFrameBuffer *CreateFrameBuffer (int width, int height, bool fs, DFrameBuffer *old); + DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old); void StartModeIterator (int bits, bool fs); bool NextMode (int *width, int *height, bool *letterbox); diff --git a/src/r_bsp.cpp b/src/r_bsp.cpp index fef7271e1..d8a6c2c01 100644 --- a/src/r_bsp.cpp +++ b/src/r_bsp.cpp @@ -1129,6 +1129,9 @@ void R_Subsector (subsector_t *sub) portal ) : NULL; + if (ceilingplane) + R_AddPlaneLights(ceilingplane, frontsector->lighthead); + if (fixedlightlev < 0 && frontsector->e && frontsector->e->XFloor.lightlist.Size()) { light = P_GetPlaneLight(frontsector, &frontsector->floorplane, false); @@ -1166,6 +1169,9 @@ void R_Subsector (subsector_t *sub) portal ) : NULL; + if (floorplane) + R_AddPlaneLights(floorplane, frontsector->lighthead); + // kg3D - fake planes rendering if (r_3dfloors && frontsector->e && frontsector->e->XFloor.ffloors.Size()) { @@ -1223,6 +1229,9 @@ void R_Subsector (subsector_t *sub) frontsector->sky, NULL); + if (floorplane) + R_AddPlaneLights(floorplane, frontsector->lighthead); + R_FakeDrawLoop(sub); fake3D = 0; frontsector = sub->sector; @@ -1284,6 +1293,9 @@ void R_Subsector (subsector_t *sub) frontsector->sky, NULL); + if (ceilingplane) + R_AddPlaneLights(ceilingplane, frontsector->lighthead); + R_FakeDrawLoop(sub); fake3D = 0; frontsector = sub->sector; diff --git a/src/r_data/colormaps.cpp b/src/r_data/colormaps.cpp index 2d3c0e49d..659470a23 100644 --- a/src/r_data/colormaps.cpp +++ b/src/r_data/colormaps.cpp @@ -72,8 +72,8 @@ struct FakeCmap }; TArray fakecmaps; -BYTE *realcolormaps; -BYTE *realfbcolormaps; //[SP] For fullbright use +FSWColormap realcolormaps; +FSWColormap realfbcolormaps; //[SP] For fullbright use size_t numfakecmaps; @@ -410,7 +410,7 @@ void R_SetDefaultColormap (const char *name) foo.Color = 0xFFFFFF; foo.Fade = 0; - foo.Maps = realcolormaps; + foo.Maps = realcolormaps.Maps; foo.Desaturate = 0; foo.Next = NULL; foo.BuildLights (); @@ -432,7 +432,7 @@ void R_SetDefaultColormap (const char *name) remap[0] = 0; for (i = 0; i < NUMCOLORMAPS; ++i) { - BYTE *map2 = &realcolormaps[i*256]; + BYTE *map2 = &realcolormaps.Maps[i*256]; lumpr.Read (map, 256); for (j = 0; j < 256; ++j) { @@ -456,15 +456,11 @@ void R_DeinitColormaps () { SpecialColormaps.Clear(); fakecmaps.Clear(); - if (realcolormaps != NULL) + delete[] realcolormaps.Maps; + if (realfbcolormaps.Maps) { - delete[] realcolormaps; - realcolormaps = NULL; - } - if (realfbcolormaps != NULL) - { - delete[] realfbcolormaps; - realfbcolormaps = NULL; + delete[] realfbcolormaps.Maps; + realfbcolormaps.Maps = nullptr; } FreeSpecialLights(); } @@ -508,7 +504,7 @@ void R_InitColormaps () } } } - realcolormaps = new BYTE[256*NUMCOLORMAPS*fakecmaps.Size()]; + realcolormaps.Maps = new BYTE[256*NUMCOLORMAPS*fakecmaps.Size()]; R_SetDefaultColormap ("COLORMAP"); if (fakecmaps.Size() > 1) @@ -530,7 +526,7 @@ void R_InitColormaps () { int k, r, g, b; FWadLump lump = Wads.OpenLumpNum (fakecmaps[j].lump); - BYTE *const map = realcolormaps + NUMCOLORMAPS*256*j; + BYTE *const map = realcolormaps.Maps + NUMCOLORMAPS*256*j; for (k = 0; k < NUMCOLORMAPS; ++k) { @@ -557,19 +553,19 @@ void R_InitColormaps () } // [SP] Create a copy of the colormap - if (!realfbcolormaps) + if (!realfbcolormaps.Maps) { - realfbcolormaps = new BYTE[256*NUMCOLORMAPS*fakecmaps.Size()]; - memcpy(realfbcolormaps, realcolormaps, 256*NUMCOLORMAPS*fakecmaps.Size()); + realfbcolormaps.Maps = new BYTE[256*NUMCOLORMAPS*fakecmaps.Size()]; + memcpy(realfbcolormaps.Maps, realcolormaps.Maps, 256*NUMCOLORMAPS*fakecmaps.Size()); } NormalLight.Color = PalEntry (255, 255, 255); NormalLight.Fade = 0; - NormalLight.Maps = realcolormaps; + NormalLight.Maps = realcolormaps.Maps; FullNormalLight.Color = PalEntry (255, 255, 255); FullNormalLight.Fade = 0; - FullNormalLight.Maps = realfbcolormaps; - NormalLightHasFixedLights = R_CheckForFixedLights(realcolormaps); + FullNormalLight.Maps = realfbcolormaps.Maps; + NormalLightHasFixedLights = R_CheckForFixedLights(realcolormaps.Maps); numfakecmaps = fakecmaps.Size(); // build default special maps (e.g. invulnerability) diff --git a/src/r_data/colormaps.h b/src/r_data/colormaps.h index 09006fc1e..8b0bf187b 100644 --- a/src/r_data/colormaps.h +++ b/src/r_data/colormaps.h @@ -1,18 +1,26 @@ #ifndef __RES_CMAP_H #define __RES_CMAP_H +struct FSWColormap; + void R_InitColormaps (); void R_DeinitColormaps (); DWORD R_ColormapNumForName(const char *name); // killough 4/4/98 void R_SetDefaultColormap (const char *name); // [RH] change normal fadetable DWORD R_BlendForColormap (DWORD map); // [RH] return calculated blend for a colormap -extern BYTE *realcolormaps; // [RH] make the colormaps externally visible +extern FSWColormap realcolormaps; // [RH] make the colormaps externally visible extern size_t numfakecmaps; +struct FSWColormap +{ + BYTE *Maps = nullptr; + PalEntry Color = 0xffffffff; + PalEntry Fade = 0xff000000; + int Desaturate = 0; +}; - -struct FDynamicColormap +struct FDynamicColormap : FSWColormap { void ChangeFade (PalEntry fadecolor); void ChangeColor (PalEntry lightcolor, int desaturate); @@ -20,10 +28,6 @@ struct FDynamicColormap void BuildLights (); static void RebuildAllLights(); - BYTE *Maps; - PalEntry Color; - PalEntry Fade; - int Desaturate; FDynamicColormap *Next; }; @@ -43,8 +47,13 @@ enum }; -struct FSpecialColormap +struct FSpecialColormap : FSWColormap { + FSpecialColormap() + { + Maps = Colormap; + } + float ColorizeStart[3]; float ColorizeEnd[3]; BYTE Colormap[256]; diff --git a/src/r_data/r_interpolate.cpp b/src/r_data/r_interpolate.cpp index a202345a3..92dc683a8 100644 --- a/src/r_data/r_interpolate.cpp +++ b/src/r_data/r_interpolate.cpp @@ -247,9 +247,9 @@ void FInterpolator::RemoveInterpolation(DInterpolation *interp) if (interp->Prev != NULL) interp->Prev->Next = interp->Next; if (interp->Next != NULL) interp->Next->Prev = interp->Prev; } - interp->Next = NULL; - interp->Prev = NULL; - count--; + interp->Next = NULL; + interp->Prev = NULL; + count--; } //========================================================================== @@ -471,12 +471,12 @@ void DSectorPlaneInterpolation::Restore() if (!ceiling) { sector->floorplane.setD(bakheight); - sector->SetPlaneTexZ(sector_t::floor, baktexz); + sector->SetPlaneTexZ(sector_t::floor, baktexz, true); } else { sector->ceilingplane.setD(bakheight); - sector->SetPlaneTexZ(sector_t::ceiling, baktexz); + sector->SetPlaneTexZ(sector_t::ceiling, baktexz, true); } P_RecalculateAttached3DFloors(sector); sector->CheckPortalPlane(ceiling? sector_t::ceiling : sector_t::floor); @@ -514,8 +514,8 @@ void DSectorPlaneInterpolation::Interpolate(double smoothratio) else { pplane->setD(oldheight + (bakheight - oldheight) * smoothratio); - sector->SetPlaneTexZ(pos, oldtexz + (baktexz - oldtexz) * smoothratio); - P_RecalculateAttached3DFloors(sector); + sector->SetPlaneTexZ(pos, oldtexz + (baktexz - oldtexz) * smoothratio, true); + P_RecalculateAttached3DFloors(sector); sector->CheckPortalPlane(pos); } } diff --git a/src/r_data/r_translate.cpp b/src/r_data/r_translate.cpp index 3689d1c0f..78d6e22c9 100644 --- a/src/r_data/r_translate.cpp +++ b/src/r_data/r_translate.cpp @@ -861,6 +861,15 @@ void R_InitTranslationTables () remap->Remap[i] = IcePaletteRemap[v]; remap->Palette[i] = PalEntry(255, IcePalette[v][0], IcePalette[v][1], IcePalette[v][2]); } + + // The alphatexture translation. Since alphatextures use the red channel this is just a standard grayscale mapping. + PushIdentityTable(TRANSLATION_Standard); + remap = translationtables[TRANSLATION_Standard][8]; + for (i = 0; i < 256; i++) + { + remap->Remap[i] = i; + remap->Palette[i] = PalEntry(255, i, i, i); + } } //---------------------------------------------------------------------------- diff --git a/src/r_data/sprites.cpp b/src/r_data/sprites.cpp index 829703bb9..b384211fc 100644 --- a/src/r_data/sprites.cpp +++ b/src/r_data/sprites.cpp @@ -15,6 +15,8 @@ #include "r_data/voxels.h" #include "textures/textures.h" +void gl_InitModels(); + // variables used to look up // and range check thing_t sprites patches TArray sprites; @@ -987,6 +989,7 @@ void R_InitSprites () // [RH] Sort the skins, but leave base as skin 0 //qsort (&skins[PlayerClasses.Size ()], numskins-PlayerClasses.Size (), sizeof(FPlayerSkin), skinsorter); + gl_InitModels(); } void R_DeinitSpriteData() diff --git a/src/r_defs.h b/src/r_defs.h index f48a07ba3..36318be85 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -37,6 +37,10 @@ // to handle sound origins in sectors. // SECTORS do store MObjs anyway. #include "actor.h" +struct FLightNode; +struct FGLSection; +struct FPortal; +struct seg_t; #include "dthinker.h" @@ -136,6 +140,25 @@ public: return { p.X, p.Y }; } + angle_t viewangle; // precalculated angle for clipping + int angletime; // recalculation time for view angle + bool dirty; // something has changed and needs to be recalculated + int numheights; + int numsectors; + sector_t ** sectors; + float * heightlist; + + vertex_t() + { + p = { 0,0 }; + angletime = 0; + viewangle = 0; + dirty = true; + numheights = numsectors = 0; + sectors = NULL; + heightlist = NULL; + } + bool operator== (const vertex_t &other) { return p == other.p; @@ -150,6 +173,8 @@ public: { p.Zero(); } + + angle_t GetClipAngle(); }; // Forward of LineDefs, for Sectors. @@ -275,6 +300,7 @@ struct secplane_t // the plane is defined as a*x + b*y + c*z + d = 0 // ic is 1/c, for faster Z calculations +//private: DVector3 normal; double D, negiC; // negative iC because that also saves a negation in all methods using this. public: @@ -437,6 +463,11 @@ public: }; #include "p_3dfloors.h" +struct subsector_t; +struct sector_t; +struct side_t; +extern bool gl_plane_reflection_i; + // Ceiling/floor flags enum { @@ -540,6 +571,8 @@ struct extsector_t TArray lightlist; // 3D light list TArray attached; // 3D floors attached to this sector } XFloor; + + TArray vertices; }; struct FTransform @@ -795,9 +828,10 @@ public: return planes[pos].TexZ; } - void SetPlaneTexZ(int pos, double val) + void SetPlaneTexZ(int pos, double val, bool dirtify = false) // This mainly gets used by init code. The only place where it must set the vertex to dirty is the interpolation code. { planes[pos].TexZ = val; + if (dirtify) SetAllVerticesDirty(); } void ChangePlaneTexZ(int pos, double val) @@ -885,6 +919,7 @@ public: void ClearPortal(int plane) { Portals[plane] = 0; + portals[plane] = nullptr; } FSectorPortal *GetPortal(int plane) @@ -912,6 +947,18 @@ public: return sectorPortals[Portals[plane]].mDestination->PortalGroup; } + void SetVerticesDirty() + { + for (unsigned i = 0; i < e->vertices.Size(); i++) e->vertices[i]->dirty = true; + } + + void SetAllVerticesDirty() + { + SetVerticesDirty(); + for (unsigned i = 0; i < e->FakeFloor.Sectors.Size(); i++) e->FakeFloor.Sectors[i]->SetVerticesDirty(); + for (unsigned i = 0; i < e->XFloor.attached.Size(); i++) e->XFloor.attached[i]->SetVerticesDirty(); + } + int GetTerrain(int pos) const; void TransferSpecial(sector_t *model); @@ -1027,6 +1074,37 @@ public: int sectornum; // for comparing sector copies extsector_t * e; // This stores data that requires construction/destruction. Such data must not be copied by R_FakeFlat. + + // GL only stuff starts here + float reflect[2]; + + bool transdoor; // For transparent door hacks + int subsectorcount; // list of subsectors + double transdoorheight; // for transparent door hacks + subsector_t ** subsectors; + FPortal * portals[2]; // floor and ceiling portals + FLightNode * lighthead; + + enum + { + vbo_fakefloor = floor+2, + vbo_fakeceiling = ceiling+2, + }; + + int vboindex[4]; // VBO indices of the 4 planes this sector uses during rendering + double vboheight[2]; // Last calculated height for the 2 planes of this actual sector + int vbocount[2]; // Total count of vertices belonging to this sector's planes + + float GetReflect(int pos) { return gl_plane_reflection_i? reflect[pos] : 0; } + bool VBOHeightcheck(int pos) const { return vboheight[pos] == GetPlaneTexZ(pos); } + FPortal *GetGLPortal(int plane) { return portals[plane]; } + + enum + { + INVALIDATE_PLANES = 1, + INVALIDATE_OTHER = 2 + }; + }; struct ReverbContainer; @@ -1189,6 +1267,13 @@ struct side_t vertex_t *V1() const; vertex_t *V2() const; + + //For GL + FLightNode * lighthead; // all blended lights that may affect this wall + + seg_t **segs; // all segs belonging to this sidedef in ascending order. Used for precise rendering + int numsegs; + }; struct line_t @@ -1206,6 +1291,7 @@ struct line_t int validcount; // if == validcount, already checked int locknumber; // [Dusk] lock number for special unsigned portalindex; + unsigned portaltransferred; DVector2 Delta() const { @@ -1222,6 +1308,11 @@ struct line_t alpha = a; } + FSectorPortal *GetTransferredPortal() + { + return portaltransferred >= sectorPortals.Size() ? (FSectorPortal*)NULL : §orPortals[portaltransferred]; + } + FLinePortal *getPortal() const { return portalindex >= linePortals.Size() ? (FLinePortal*)NULL : &linePortals[portalindex]; @@ -1306,6 +1397,11 @@ struct seg_t // Sector references. Could be retrieved from linedef, too. sector_t* frontsector; sector_t* backsector; // NULL for one-sided lines + + seg_t* PartnerSeg; + subsector_t* Subsector; + + float sidefrac; // relative position of seg's ending vertex on owning sidedef }; struct glsegextra_t @@ -1314,6 +1410,9 @@ struct glsegextra_t subsector_t *Subsector; }; +extern seg_t *segs; + + // // A SubSector. // References a Sector. @@ -1328,6 +1427,12 @@ enum SSECF_POLYORG = 4, }; +struct FPortalCoverage +{ + DWORD * subsectors; + int sscount; +}; + struct subsector_t { sector_t *sector; @@ -1339,6 +1444,13 @@ struct subsector_t int flags; void BuildPolyBSP(); + // subsector related GL data + FLightNode * lighthead; // Light nodes (blended and additive) + int validcount; + short mapsection; + char hacked; // 1: is part of a render hack + // 2: has one-sided walls + FPortalCoverage portalcoverage[2]; }; @@ -1387,11 +1499,14 @@ struct FMiniBSP // typedef BYTE lighttable_t; // This could be wider for >8 bit display. +struct FSWColormap; // This encapsulates the fields of vissprite_t that can be altered by AlterWeaponSprite struct visstyle_t { - lighttable_t *colormap; + int ColormapNum; // Which colormap is rendered + FSWColormap *BaseColormap; // Base colormap used together with ColormapNum + lighttable_t *colormap; // [SP] Restored from GZDoom - will this work? float Alpha; FRenderStyle RenderStyle; }; diff --git a/src/r_draw.cpp b/src/r_draw.cpp index 2d320af6c..3e31c7e04 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -49,9 +49,12 @@ #include "r_data/colormaps.h" #include "r_plane.h" #include "r_draw.h" +#include "r_draw_rgba.h" #include "r_draw_pal.h" #include "r_thread.h" +CVAR(Bool, r_dynlights, 1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + namespace swrenderer { // Needed by R_DrawFogBoundary (which probably shouldn't be part of this file) @@ -61,6 +64,8 @@ namespace swrenderer extern int wallshade; double dc_texturemid; + FLightNode *dc_light_list; + visplane_light *ds_light_list; int ylookup[MAXHEIGHT]; uint8_t shadetables[NUMCOLORMAPS * 16 * 256]; @@ -75,6 +80,9 @@ namespace swrenderer { int dc_pitch; lighttable_t *dc_colormap; + FSWColormap *dc_fcolormap; + ShadeConstants dc_shade_constants; + fixed_t dc_light; int dc_x; int dc_yl; int dc_yh; @@ -96,6 +104,10 @@ namespace swrenderer uint8_t *dc_destorg; int dc_destheight; int dc_count; + FVector3 dc_viewpos; + FVector3 dc_viewpos_step; + TriLight *dc_lights; + int dc_num_lights; uint32_t dc_wall_texturefrac[4]; uint32_t dc_wall_iscale[4]; uint8_t *dc_wall_colormap[4]; @@ -109,6 +121,8 @@ namespace swrenderer int ds_x1; int ds_x2; lighttable_t * ds_colormap; + FSWColormap *ds_fcolormap; + ShadeConstants ds_shade_constants; dsfixed_t ds_light; dsfixed_t ds_xfrac; dsfixed_t ds_yfrac; @@ -119,7 +133,9 @@ namespace swrenderer fixed_t ds_alpha; double ds_lod; const uint8_t *ds_source; + bool ds_source_mipmapped; int ds_color; + bool drawer_needs_pal_input; unsigned int dc_tspans[4][MAXHEIGHT]; unsigned int *dc_ctspan[4]; unsigned int *horizspan[4]; @@ -131,9 +147,6 @@ namespace swrenderer fuzzcolfunc = R_DrawFuzzColumn; transcolfunc = R_DrawTranslatedColumn; spanfunc = R_DrawSpan; - hcolfunc_pre = R_DrawColumnHoriz; - hcolfunc_post1 = rt_map1col; - hcolfunc_post4 = rt_map4cols; } void R_InitShadeMaps() @@ -217,20 +230,15 @@ namespace swrenderer if (flags & STYLEF_ColorIsFixed) { colfunc = R_FillColumn; - hcolfunc_post1 = rt_copy1col; - hcolfunc_post4 = rt_copy4cols; } else if (dc_translation == NULL) { colfunc = basecolfunc; - hcolfunc_post1 = rt_map1col; - hcolfunc_post4 = rt_map4cols; } else { colfunc = transcolfunc; - hcolfunc_post1 = rt_tlate1col; - hcolfunc_post4 = rt_tlate4cols; + drawer_needs_pal_input = true; } return true; } @@ -267,20 +275,15 @@ namespace swrenderer if (flags & STYLEF_ColorIsFixed) { colfunc = R_FillAddColumn; - hcolfunc_post1 = rt_add1col; - hcolfunc_post4 = rt_add4cols; } else if (dc_translation == NULL) { colfunc = R_DrawAddColumn; - hcolfunc_post1 = rt_add1col; - hcolfunc_post4 = rt_add4cols; } else { colfunc = R_DrawTlatedAddColumn; - hcolfunc_post1 = rt_tlateadd1col; - hcolfunc_post4 = rt_tlateadd4cols; + drawer_needs_pal_input = true; } } else @@ -288,20 +291,15 @@ namespace swrenderer if (flags & STYLEF_ColorIsFixed) { colfunc = R_FillAddClampColumn; - hcolfunc_post1 = rt_addclamp1col; - hcolfunc_post4 = rt_addclamp4cols; } else if (dc_translation == NULL) { colfunc = R_DrawAddClampColumn; - hcolfunc_post1 = rt_addclamp1col; - hcolfunc_post4 = rt_addclamp4cols; } else { colfunc = R_DrawAddClampTranslatedColumn; - hcolfunc_post1 = rt_tlateaddclamp1col; - hcolfunc_post4 = rt_tlateaddclamp4cols; + drawer_needs_pal_input = true; } } return true; @@ -310,20 +308,15 @@ namespace swrenderer if (flags & STYLEF_ColorIsFixed) { colfunc = R_FillSubClampColumn; - hcolfunc_post1 = rt_subclamp1col; - hcolfunc_post4 = rt_subclamp4cols; } else if (dc_translation == NULL) { colfunc = R_DrawSubClampColumn; - hcolfunc_post1 = rt_subclamp1col; - hcolfunc_post4 = rt_subclamp4cols; } else { colfunc = R_DrawSubClampTranslatedColumn; - hcolfunc_post1 = rt_tlatesubclamp1col; - hcolfunc_post4 = rt_tlatesubclamp4cols; + drawer_needs_pal_input = true; } return true; @@ -335,20 +328,15 @@ namespace swrenderer if (flags & STYLEF_ColorIsFixed) { colfunc = R_FillRevSubClampColumn; - hcolfunc_post1 = rt_subclamp1col; - hcolfunc_post4 = rt_subclamp4cols; } else if (dc_translation == NULL) { colfunc = R_DrawRevSubClampColumn; - hcolfunc_post1 = rt_revsubclamp1col; - hcolfunc_post4 = rt_revsubclamp4cols; } else { colfunc = R_DrawRevSubClampTranslatedColumn; - hcolfunc_post1 = rt_tlaterevsubclamp1col; - hcolfunc_post4 = rt_tlaterevsubclamp4cols; + drawer_needs_pal_input = true; } return true; @@ -372,12 +360,14 @@ namespace swrenderer FDynamicColormap *basecolormapsave; } - ESPSResult R_SetPatchStyle(FRenderStyle style, fixed_t alpha, int translation, uint32_t color) + bool R_SetPatchStyle(FRenderStyle style, fixed_t alpha, int translation, uint32_t color) { using namespace drawerargs; fixed_t fglevel, bglevel; + drawer_needs_pal_input = false; + style.CheckFuzz(); if (style.BlendOp == STYLEOP_Shadow) @@ -412,34 +402,39 @@ namespace swrenderer FRemapTable *table = TranslationToTable(translation); if (table != NULL && !table->Inactive) { - dc_translation = table->Remap; + if (r_swtruecolor) + dc_translation = (uint8_t*)table->Palette; + else + dc_translation = table->Remap; } } } basecolormapsave = basecolormap; - hcolfunc_pre = R_DrawColumnHoriz; // Check for special modes if (style.BlendOp == STYLEOP_Fuzz) { colfunc = fuzzcolfunc; - return DoDraw0; + return true; } else if (style == LegacyRenderStyles[STYLE_Shaded]) { // Shaded drawer only gets 16 levels of alpha because it saves memory. if ((alpha >>= 12) == 0) - return DontDraw; + return false; colfunc = R_DrawShadedColumn; - hcolfunc_post1 = rt_shaded1col; - hcolfunc_post4 = rt_shaded4cols; - dc_color = fixedcolormap ? fixedcolormap[APART(color)] : basecolormap->Maps[APART(color)]; - dc_colormap = (basecolormap = &ShadeFakeColormap[16 - alpha])->Maps; + drawer_needs_pal_input = true; + dc_color = fixedcolormap ? fixedcolormap->Maps[APART(color)] : basecolormap->Maps[APART(color)]; + basecolormap = &ShadeFakeColormap[16 - alpha]; if (fixedlightlev >= 0 && fixedcolormap == NULL) { - dc_colormap += fixedlightlev; + R_SetColorMapLight(basecolormap, 0, FIXEDLIGHT2SHADE(fixedlightlev)); } - return r_columnmethod ? DoDraw1 : DoDraw0; + else + { + R_SetColorMapLight(basecolormap, 0, 0); + } + return true; } fglevel = GetAlpha(style.SrcAlpha, alpha); @@ -452,7 +447,7 @@ namespace swrenderer uint32_t g = GPART(color); uint32_t b = BPART(color); // dc_color is used by the rt_* routines. It is indexed into dc_srcblend. - dc_color = RGB32k.RGB[r >> 3][g >> 3][b >> 3]; + dc_color = RGB256k.RGB[r >> 2][g >> 2][b >> 2]; if (style.Flags & STYLEF_InvertSource) { r = 255 - r; @@ -464,18 +459,17 @@ namespace swrenderer // dc_srccolor is used by the R_Fill* routines. It is premultiplied // with the alpha. dc_srccolor = ((((r*x) >> 4) << 20) | ((g*x) >> 4) | ((((b)*x) >> 4) << 10)) & 0x3feffbff; - hcolfunc_pre = R_FillColumnHoriz; - R_SetColorMapLight(identitycolormap.Maps, 0, 0); + R_SetColorMapLight(&identitycolormap, 0, 0); } if (!R_SetBlendFunc(style.BlendOp, fglevel, bglevel, style.Flags)) { - return DontDraw; + return false; } - return r_columnmethod ? DoDraw1 : DoDraw0; + return true; } - ESPSResult R_SetPatchStyle(FRenderStyle style, float alpha, int translation, uint32_t color) + bool R_SetPatchStyle(FRenderStyle style, float alpha, int translation, uint32_t color) { return R_SetPatchStyle(style, FLOAT2FIXED(alpha), translation, color); } @@ -496,7 +490,10 @@ namespace swrenderer col = width + (col % width); } - return tex->GetColumn(col, nullptr); + if (r_swtruecolor) + return (const uint8_t *)tex->GetColumnBgra(col, nullptr); + else + return tex->GetColumn(col, nullptr); } bool R_GetTransMaskDrawers(void(**drawCol1)(), void(**drawCol4)()) @@ -528,216 +525,83 @@ namespace swrenderer return false; } - void R_SetColorMapLight(lighttable_t *base_colormap, float light, int shade) + void R_SetColorMapLight(FSWColormap *base_colormap, float light, int shade) { using namespace drawerargs; - dc_colormap = base_colormap + (GETPALOOKUP(light, shade) << COLORMAPSHIFT); + dc_fcolormap = base_colormap; + if (r_swtruecolor) + { + dc_shade_constants.light_red = dc_fcolormap->Color.r * 256 / 255; + dc_shade_constants.light_green = dc_fcolormap->Color.g * 256 / 255; + dc_shade_constants.light_blue = dc_fcolormap->Color.b * 256 / 255; + dc_shade_constants.light_alpha = dc_fcolormap->Color.a * 256 / 255; + dc_shade_constants.fade_red = dc_fcolormap->Fade.r; + dc_shade_constants.fade_green = dc_fcolormap->Fade.g; + dc_shade_constants.fade_blue = dc_fcolormap->Fade.b; + dc_shade_constants.fade_alpha = dc_fcolormap->Fade.a; + dc_shade_constants.desaturate = MIN(abs(dc_fcolormap->Desaturate), 255) * 255 / 256; + dc_shade_constants.simple_shade = (dc_fcolormap->Color.d == 0x00ffffff && dc_fcolormap->Fade.d == 0x00000000 && dc_fcolormap->Desaturate == 0); + dc_colormap = base_colormap->Maps; + dc_light = LIGHTSCALE(light, shade); + } + else + { + dc_colormap = base_colormap->Maps + (GETPALOOKUP(light, shade) << COLORMAPSHIFT); + } } - void R_SetColorMapLight(FDynamicColormap *base_colormap, float light, int shade) - { - R_SetColorMapLight(base_colormap->Maps, light, shade); - } - - void R_SetDSColorMapLight(lighttable_t *base_colormap, float light, int shade) + void R_SetDSColorMapLight(FSWColormap *base_colormap, float light, int shade) { using namespace drawerargs; - ds_colormap = base_colormap + (GETPALOOKUP(light, shade) << COLORMAPSHIFT); - } - - void R_SetDSColorMapLight(FDynamicColormap *base_colormap, float light, int shade) - { - R_SetDSColorMapLight(base_colormap->Maps, light, shade); + ds_fcolormap = base_colormap; + if (r_swtruecolor) + { + ds_shade_constants.light_red = ds_fcolormap->Color.r * 256 / 255; + ds_shade_constants.light_green = ds_fcolormap->Color.g * 256 / 255; + ds_shade_constants.light_blue = ds_fcolormap->Color.b * 256 / 255; + ds_shade_constants.light_alpha = ds_fcolormap->Color.a * 256 / 255; + ds_shade_constants.fade_red = ds_fcolormap->Fade.r; + ds_shade_constants.fade_green = ds_fcolormap->Fade.g; + ds_shade_constants.fade_blue = ds_fcolormap->Fade.b; + ds_shade_constants.fade_alpha = ds_fcolormap->Fade.a; + ds_shade_constants.desaturate = MIN(abs(ds_fcolormap->Desaturate), 255) * 255 / 256; + ds_shade_constants.simple_shade = (ds_fcolormap->Color.d == 0x00ffffff && ds_fcolormap->Fade.d == 0x00000000 && ds_fcolormap->Desaturate == 0); + ds_colormap = base_colormap->Maps; + ds_light = LIGHTSCALE(light, shade); + } + else + { + ds_colormap = base_colormap->Maps + (GETPALOOKUP(light, shade) << COLORMAPSHIFT); + } } void R_SetTranslationMap(lighttable_t *translation) { using namespace drawerargs; - dc_colormap = translation; - } - - void rt_initcols(uint8_t *buffer) - { - using namespace drawerargs; - - for (int y = 3; y >= 0; y--) - horizspan[y] = dc_ctspan[y] = &dc_tspans[y][0]; - - DrawerCommandQueue::QueueCommand(buffer); - } - - void rt_span_coverage(int x, int start, int stop) - { - using namespace drawerargs; - - unsigned int **tspan = &dc_ctspan[x & 3]; - (*tspan)[0] = start; - (*tspan)[1] = stop; - *tspan += 2; - } - - void rt_flip_posts() - { - using namespace drawerargs; - - unsigned int *front = horizspan[dc_x & 3]; - unsigned int *back = dc_ctspan[dc_x & 3] - 2; - - while (front < back) + if (r_swtruecolor) { - swapvalues(front[0], back[0]); - swapvalues(front[1], back[1]); - front += 2; - back -= 2; + dc_fcolormap = nullptr; + dc_colormap = nullptr; + dc_translation = translation; + dc_shade_constants.light_red = 256; + dc_shade_constants.light_green = 256; + dc_shade_constants.light_blue = 256; + dc_shade_constants.light_alpha = 256; + dc_shade_constants.fade_red = 0; + dc_shade_constants.fade_green = 0; + dc_shade_constants.fade_blue = 0; + dc_shade_constants.fade_alpha = 256; + dc_shade_constants.desaturate = 0; + dc_shade_constants.simple_shade = true; + dc_light = 0; } - } - - void rt_draw4cols(int sx) - { - using namespace drawerargs; - - int x, bad; - unsigned int maxtop, minbot, minnexttop; - - // Place a dummy "span" in each column. These don't get - // drawn. They're just here to avoid special cases in the - // max/min calculations below. - for (x = 0; x < 4; ++x) + else { - dc_ctspan[x][0] = screen->GetHeight()+1; - dc_ctspan[x][1] = screen->GetHeight(); - } - - for (;;) - { - // If a column is out of spans, mark it as such - bad = 0; - minnexttop = 0xffffffff; - for (x = 0; x < 4; ++x) - { - if (horizspan[x] >= dc_ctspan[x]) - { - bad |= 1 << x; - } - else if ((horizspan[x]+2)[0] < minnexttop) - { - minnexttop = (horizspan[x]+2)[0]; - } - } - // Once all columns are out of spans, we're done - if (bad == 15) - { - return; - } - - // Find the largest shared area for the spans in each column - maxtop = MAX (MAX (horizspan[0][0], horizspan[1][0]), - MAX (horizspan[2][0], horizspan[3][0])); - minbot = MIN (MIN (horizspan[0][1], horizspan[1][1]), - MIN (horizspan[2][1], horizspan[3][1])); - - // If there is no shared area with these spans, draw each span - // individually and advance to the next spans until we reach a shared area. - // However, only draw spans down to the highest span in the next set of - // spans. If we allow the entire height of a span to be drawn, it could - // prevent any more shared areas from being drawn in these four columns. - // - // Example: Suppose we have the following arrangement: - // A CD - // A CD - // B D - // B D - // aB D - // aBcD - // aBcD - // aBc - // - // If we draw the entire height of the spans, we end up drawing this first: - // A CD - // A CD - // B D - // B D - // B D - // B D - // B D - // B D - // B - // - // This leaves only the "a" and "c" columns to be drawn, and they are not - // part of a shared area, but if we can include B and D with them, we can - // get a shared area. So we cut off everything in the first set just - // above the "a" column and end up drawing this first: - // A CD - // A CD - // B D - // B D - // - // Then the next time through, we have the following arrangement with an - // easily shared area to draw: - // aB D - // aBcD - // aBcD - // aBc - if (bad != 0 || maxtop > minbot) - { - int drawcount = 0; - for (x = 0; x < 4; ++x) - { - if (!(bad & 1)) - { - if (horizspan[x][1] < minnexttop) - { - hcolfunc_post1 (x, sx+x, horizspan[x][0], horizspan[x][1]); - horizspan[x] += 2; - drawcount++; - } - else if (minnexttop > horizspan[x][0]) - { - hcolfunc_post1 (x, sx+x, horizspan[x][0], minnexttop-1); - horizspan[x][0] = minnexttop; - drawcount++; - } - } - bad >>= 1; - } - // Drawcount *should* always be non-zero. The reality is that some situations - // can make this not true. Unfortunately, I'm not sure what those situations are. - if (drawcount == 0) - { - return; - } - continue; - } - - // Draw any span fragments above the shared area. - for (x = 0; x < 4; ++x) - { - if (maxtop > horizspan[x][0]) - { - hcolfunc_post1 (x, sx+x, horizspan[x][0], maxtop-1); - } - } - - // Draw the shared area. - hcolfunc_post4 (sx, maxtop, minbot); - - // For each column, if part of the span is past the shared area, - // set its top to just below the shared area. Otherwise, advance - // to the next span in that column. - for (x = 0; x < 4; ++x) - { - if (minbot < horizspan[x][1]) - { - horizspan[x][0] = minbot+1; - } - else - { - horizspan[x] += 2; - } - } + dc_fcolormap = nullptr; + dc_colormap = translation; } } @@ -758,323 +622,207 @@ namespace swrenderer } } - void R_SetSpanColormap(lighttable_t *colormap) + void R_SetSpanColormap(FDynamicColormap *colormap, int shade) { - using namespace drawerargs; - - ds_colormap = colormap; + R_SetDSColorMapLight(colormap, 0, shade); } void R_SetSpanSource(FTexture *tex) { using namespace drawerargs; - ds_source = tex->GetPixels(); + ds_source = r_swtruecolor ? (const uint8_t*)tex->GetPixelsBgra() : tex->GetPixels(); + ds_source_mipmapped = tex->Mipmapped() && tex->GetWidth() > 1 && tex->GetHeight() > 1; } ///////////////////////////////////////////////////////////////////////// - void R_FillColumnHoriz() - { - using namespace drawerargs; - - if (dc_count <= 0) - return; - - int x = dc_x & 3; - unsigned int **span = &dc_ctspan[x]; - (*span)[0] = dc_yl; - (*span)[1] = dc_yh; - *span += 2; - - DrawerCommandQueue::QueueCommand(); - } - - void R_DrawColumnHoriz() - { - using namespace drawerargs; - - if (dc_count <= 0) - return; - - int x = dc_x & 3; - unsigned int **span = &dc_ctspan[x]; - (*span)[0] = dc_yl; - (*span)[1] = dc_yh; - *span += 2; - - DrawerCommandQueue::QueueCommand(); - } - - // Copies one span at hx to the screen at sx. - void rt_copy1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Copies all four spans to the screen starting at sx. - void rt_copy4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Maps one span at hx to the screen at sx. - void rt_map1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Maps all four spans to the screen starting at sx. - void rt_map4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Translates one span at hx to the screen at sx. - void rt_tlate1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - rt_map1col(hx, sx, yl, yh); - } - - // Translates all four spans to the screen starting at sx. - void rt_tlate4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - rt_map4cols(sx, yl, yh); - } - - // Adds one span at hx to the screen at sx without clamping. - void rt_add1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Adds all four spans to the screen starting at sx without clamping. - void rt_add4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Translates and adds one span at hx to the screen at sx without clamping. - void rt_tlateadd1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - rt_add1col(hx, sx, yl, yh); - } - - // Translates and adds all four spans to the screen starting at sx without clamping. - void rt_tlateadd4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - rt_add4cols(sx, yl, yh); - } - - // Shades one span at hx to the screen at sx. - void rt_shaded1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Shades all four spans to the screen starting at sx. - void rt_shaded4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Adds one span at hx to the screen at sx with clamping. - void rt_addclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Adds all four spans to the screen starting at sx with clamping. - void rt_addclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Translates and adds one span at hx to the screen at sx with clamping. - void rt_tlateaddclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - rt_addclamp1col(hx, sx, yl, yh); - } - - // Translates and adds all four spans to the screen starting at sx with clamping. - void rt_tlateaddclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - rt_addclamp4cols(sx, yl, yh); - } - - // Subtracts one span at hx to the screen at sx with clamping. - void rt_subclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Subtracts all four spans to the screen starting at sx with clamping. - void rt_subclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Translates and subtracts one span at hx to the screen at sx with clamping. - void rt_tlatesubclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - rt_subclamp1col(hx, sx, yl, yh); - } - - // Translates and subtracts all four spans to the screen starting at sx with clamping. - void rt_tlatesubclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - rt_subclamp4cols(sx, yl, yh); - } - - // Subtracts one span at hx from the screen at sx with clamping. - void rt_revsubclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - } - - // Subtracts all four spans from the screen starting at sx with clamping. - void rt_revsubclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - } - - // Translates and subtracts one span at hx from the screen at sx with clamping. - void rt_tlaterevsubclamp1col(int hx, int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(hx, sx, yl, yh); - rt_revsubclamp1col(hx, sx, yl, yh); - } - - // Translates and subtracts all four spans from the screen starting at sx with clamping. - void rt_tlaterevsubclamp4cols(int sx, int yl, int yh) - { - DrawerCommandQueue::QueueCommand(0, sx, yl, yh); - rt_revsubclamp4cols(sx, yl, yh); - } - void R_DrawWallCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallMaskedCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallMaskedCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallAddCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else if (drawerargs::dc_num_lights == 0) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallAddCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallAddClampCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallAddClampCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallSubClampCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallSubClampCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallRevSubClampCol1() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawWallRevSubClampCol4() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSingleSkyCol1(uint32_t solid_top, uint32_t solid_bottom) { - DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + else + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); } void R_DrawSingleSkyCol4(uint32_t solid_top, uint32_t solid_bottom) { - DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + else + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); } void R_DrawDoubleSkyCol1(uint32_t solid_top, uint32_t solid_bottom) { - DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + else + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); } void R_DrawDoubleSkyCol4(uint32_t solid_top, uint32_t solid_bottom) { - DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); + else + DrawerCommandQueue::QueueCommand(solid_top, solid_bottom); } void R_DrawColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillAddColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillAddClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillSubClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillRevSubClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawFuzzColumn() { using namespace drawerargs; - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); dc_yl = MAX(dc_yl, 1); dc_yh = MIN(dc_yh, fuzzviewheight); @@ -1084,112 +832,185 @@ namespace swrenderer void R_DrawAddColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawTranslatedColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawTlatedAddColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawShadedColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawAddClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawAddClampTranslatedColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSubClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSubClampTranslatedColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawRevSubClampColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawRevSubClampTranslatedColumn() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpan() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpanMasked() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpanTranslucent() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpanMaskedTranslucent() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpanAddClamp() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawSpanMaskedAddClamp() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_FillSpan() { - DrawerCommandQueue::QueueCommand(); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(); + else + DrawerCommandQueue::QueueCommand(); } void R_DrawTiltedSpan(int y, int x1, int x2, const FVector3 &plane_sz, const FVector3 &plane_su, const FVector3 &plane_sv, bool plane_shade, int planeshade, float planelightfloat, fixed_t pviewx, fixed_t pviewy) { - DrawerCommandQueue::QueueCommand(y, x1, x2, plane_sz, plane_su, plane_sv, plane_shade, planeshade, planelightfloat, pviewx, pviewy); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(y, x1, x2, plane_sz, plane_su, plane_sv, plane_shade, planeshade, planelightfloat, pviewx, pviewy); + else + DrawerCommandQueue::QueueCommand(y, x1, x2, plane_sz, plane_su, plane_sv, plane_shade, planeshade, planelightfloat, pviewx, pviewy); } void R_DrawColoredSpan(int y, int x1, int x2) { - DrawerCommandQueue::QueueCommand(y, x1, x2); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(y, x1, x2); + else + DrawerCommandQueue::QueueCommand(y, x1, x2); } namespace { - const uint8_t *slab_colormap; + ShadeConstants slab_rgba_shade_constants; + const uint8_t *slab_rgba_colormap; + fixed_t slab_rgba_light; } - void R_SetupDrawSlab(uint8_t *colormap) + void R_SetupDrawSlab(FSWColormap *base_colormap, float light, int shade) { - slab_colormap = colormap; + slab_rgba_shade_constants.light_red = base_colormap->Color.r * 256 / 255; + slab_rgba_shade_constants.light_green = base_colormap->Color.g * 256 / 255; + slab_rgba_shade_constants.light_blue = base_colormap->Color.b * 256 / 255; + slab_rgba_shade_constants.light_alpha = base_colormap->Color.a * 256 / 255; + slab_rgba_shade_constants.fade_red = base_colormap->Fade.r; + slab_rgba_shade_constants.fade_green = base_colormap->Fade.g; + slab_rgba_shade_constants.fade_blue = base_colormap->Fade.b; + slab_rgba_shade_constants.fade_alpha = base_colormap->Fade.a; + slab_rgba_shade_constants.desaturate = MIN(abs(base_colormap->Desaturate), 255) * 255 / 256; + slab_rgba_shade_constants.simple_shade = (base_colormap->Color.d == 0x00ffffff && base_colormap->Fade.d == 0x00000000 && base_colormap->Desaturate == 0); + slab_rgba_colormap = base_colormap->Maps; + slab_rgba_light = LIGHTSCALE(light, shade); } void R_DrawSlab(int dx, fixed_t v, int dy, fixed_t vi, const uint8_t *vptr, uint8_t *p) { - DrawerCommandQueue::QueueCommand(dx, v, dy, vi, vptr, p, slab_colormap); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(dx, v, dy, vi, vptr, p, slab_rgba_shade_constants, slab_rgba_colormap, slab_rgba_light); + else + DrawerCommandQueue::QueueCommand(dx, v, dy, vi, vptr, p, slab_rgba_colormap); } void R_DrawFogBoundarySection(int y, int y2, int x1) @@ -1197,7 +1018,10 @@ namespace swrenderer for (; y < y2; ++y) { int x2 = spanend[y]; - DrawerCommandQueue::QueueCommand(y, x1, x2); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(y, x1, x2); + else + DrawerCommandQueue::QueueCommand(y, x1, x2); } } @@ -1221,7 +1045,7 @@ namespace swrenderer fillshort(spanend + t2, b2 - t2, x); } - R_SetColorMapLight(basecolormap->Maps, (float)light, wallshade); + R_SetColorMapLight(basecolormap, (float)light, wallshade); uint8_t *fake_dc_colormap = basecolormap->Maps + (GETPALOOKUP(light, wallshade) << COLORMAPSHIFT); @@ -1248,7 +1072,7 @@ namespace swrenderer fillshort(spanend + t2, b2 - t2, x); } rcolormap = lcolormap; - R_SetColorMapLight(basecolormap->Maps, (float)light, wallshade); + R_SetColorMapLight(basecolormap, (float)light, wallshade); fake_dc_colormap = basecolormap->Maps + (GETPALOOKUP(light, wallshade) << COLORMAPSHIFT); } else @@ -1259,13 +1083,19 @@ namespace swrenderer while (t2 < stop) { int y = t2++; - DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); + else + DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); } stop = MAX(b1, t2); while (b2 > stop) { int y = --b2; - DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); + if (r_swtruecolor) + DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); + else + DrawerCommandQueue::QueueCommand(y, xr, spanend[y]); } } else @@ -1295,8 +1125,4 @@ namespace swrenderer } } - void R_DrawParticle(vissprite_t *sprite) - { - R_DrawParticle_C(sprite); - } } diff --git a/src/r_draw.h b/src/r_draw.h index c245034d7..c508aa268 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -3,22 +3,50 @@ #include "r_defs.h" +struct FSWColormap; +struct FLightNode; +struct TriLight; + EXTERN_CVAR(Bool, r_multithreaded); +EXTERN_CVAR(Bool, r_magfilter); +EXTERN_CVAR(Bool, r_minfilter); +EXTERN_CVAR(Bool, r_mipmap); +EXTERN_CVAR(Float, r_lod_bias); EXTERN_CVAR(Int, r_drawfuzz); EXTERN_CVAR(Bool, r_drawtrans); EXTERN_CVAR(Float, transsouls); -EXTERN_CVAR(Int, r_columnmethod); +EXTERN_CVAR(Bool, r_dynlights); namespace swrenderer { struct vissprite_t; + struct visplane_light; + + struct ShadeConstants + { + uint16_t light_alpha; + uint16_t light_red; + uint16_t light_green; + uint16_t light_blue; + uint16_t fade_alpha; + uint16_t fade_red; + uint16_t fade_green; + uint16_t fade_blue; + uint16_t desaturate; + bool simple_shade; + }; extern double dc_texturemid; + extern FLightNode *dc_light_list; + extern visplane_light *ds_light_list; namespace drawerargs { extern int dc_pitch; extern lighttable_t *dc_colormap; + extern FSWColormap *dc_fcolormap; + extern ShadeConstants dc_shade_constants; + extern fixed_t dc_light; extern int dc_x; extern int dc_yl; extern int dc_yh; @@ -40,6 +68,12 @@ namespace swrenderer extern uint8_t *dc_destorg; extern int dc_destheight; extern int dc_count; + extern FVector3 dc_viewpos; + extern FVector3 dc_viewpos_step; + extern TriLight *dc_lights; + extern int dc_num_lights; + + extern bool drawer_needs_pal_input; extern uint32_t dc_wall_texturefrac[4]; extern uint32_t dc_wall_iscale[4]; @@ -55,6 +89,8 @@ namespace swrenderer extern int ds_x1; extern int ds_x2; extern lighttable_t * ds_colormap; + extern FSWColormap *ds_fcolormap; + extern ShadeConstants ds_shade_constants; extern dsfixed_t ds_light; extern dsfixed_t ds_xfrac; extern dsfixed_t ds_yfrac; @@ -65,6 +101,7 @@ namespace swrenderer extern fixed_t ds_alpha; extern double ds_lod; extern const uint8_t *ds_source; + extern bool ds_source_mipmapped; extern int ds_color; extern unsigned int dc_tspans[4][MAXHEIGHT]; @@ -84,53 +121,19 @@ namespace swrenderer extern int fuzzpos; extern int fuzzviewheight; + extern bool r_swtruecolor; + void R_InitColumnDrawers(); void R_InitShadeMaps(); void R_InitFuzzTable(int fuzzoff); - enum ESPSResult - { - DontDraw, // not useful to draw this - DoDraw0, // draw this as if r_columnmethod is 0 - DoDraw1, // draw this as if r_columnmethod is 1 - }; - - ESPSResult R_SetPatchStyle(FRenderStyle style, fixed_t alpha, int translation, uint32_t color); - ESPSResult R_SetPatchStyle(FRenderStyle style, float alpha, int translation, uint32_t color); + bool R_SetPatchStyle(FRenderStyle style, fixed_t alpha, int translation, uint32_t color); + bool R_SetPatchStyle(FRenderStyle style, float alpha, int translation, uint32_t color); void R_FinishSetPatchStyle(); // Call this after finished drawing the current thing, in case its style was STYLE_Shade bool R_GetTransMaskDrawers(void(**drawCol1)(), void(**drawCol4)()); const uint8_t *R_GetColumn(FTexture *tex, int col); - void rt_initcols(uint8_t *buffer = nullptr); - void rt_span_coverage(int x, int start, int stop); - void rt_draw4cols(int sx); - void rt_flip_posts(); - void rt_copy1col(int hx, int sx, int yl, int yh); - void rt_copy4cols(int sx, int yl, int yh); - void rt_shaded1col(int hx, int sx, int yl, int yh); - void rt_shaded4cols(int sx, int yl, int yh); - void rt_map1col(int hx, int sx, int yl, int yh); - void rt_add1col(int hx, int sx, int yl, int yh); - void rt_addclamp1col(int hx, int sx, int yl, int yh); - void rt_subclamp1col(int hx, int sx, int yl, int yh); - void rt_revsubclamp1col(int hx, int sx, int yl, int yh); - void rt_tlate1col(int hx, int sx, int yl, int yh); - void rt_tlateadd1col(int hx, int sx, int yl, int yh); - void rt_tlateaddclamp1col(int hx, int sx, int yl, int yh); - void rt_tlatesubclamp1col(int hx, int sx, int yl, int yh); - void rt_tlaterevsubclamp1col(int hx, int sx, int yl, int yh); - void rt_map4cols(int sx, int yl, int yh); - void rt_add4cols(int sx, int yl, int yh); - void rt_addclamp4cols(int sx, int yl, int yh); - void rt_subclamp4cols(int sx, int yl, int yh); - void rt_revsubclamp4cols(int sx, int yl, int yh); - void rt_tlate4cols(int sx, int yl, int yh); - void rt_tlateadd4cols(int sx, int yl, int yh); - void rt_tlateaddclamp4cols(int sx, int yl, int yh); - void rt_tlatesubclamp4cols(int sx, int yl, int yh); - void rt_tlaterevsubclamp4cols(int sx, int yl, int yh); - void R_DrawColumnHoriz(); void R_DrawColumn(); void R_DrawFuzzColumn(); void R_DrawTranslatedColumn(); @@ -157,10 +160,9 @@ namespace swrenderer void R_FillSpan(); void R_DrawTiltedSpan(int y, int x1, int x2, const FVector3 &plane_sz, const FVector3 &plane_su, const FVector3 &plane_sv, bool plane_shade, int planeshade, float planelightfloat, fixed_t pviewx, fixed_t pviewy); void R_DrawColoredSpan(int y, int x1, int x2); - void R_SetupDrawSlab(uint8_t *colormap); + void R_SetupDrawSlab(FSWColormap *base_colormap, float light, int shade); void R_DrawSlab(int dx, fixed_t v, int dy, fixed_t vi, const uint8_t *vptr, uint8_t *p); void R_DrawFogBoundary(int x1, int x2, short *uclip, short *dclip); - void R_FillColumnHoriz(); void R_FillSpan(); void R_DrawWallCol1(); @@ -181,17 +183,15 @@ namespace swrenderer void R_DrawDoubleSkyCol1(uint32_t solid_top, uint32_t solid_bottom); void R_DrawDoubleSkyCol4(uint32_t solid_top, uint32_t solid_bottom); - void R_SetColorMapLight(lighttable_t *base_colormap, float light, int shade); - void R_SetColorMapLight(FDynamicColormap *base_colormap, float light, int shade); - void R_SetDSColorMapLight(lighttable_t *base_colormap, float light, int shade); - void R_SetDSColorMapLight(FDynamicColormap *base_colormap, float light, int shade); + // Sets dc_colormap and dc_light to their appropriate values depending on the output format (pal vs true color) + void R_SetColorMapLight(FSWColormap *base_colormap, float light, int shade); + void R_SetDSColorMapLight(FSWColormap *base_colormap, float light, int shade); void R_SetTranslationMap(lighttable_t *translation); void R_SetupSpanBits(FTexture *tex); - void R_SetSpanColormap(lighttable_t *colormap); + void R_SetSpanColormap(FDynamicColormap *colormap, int shade); void R_SetSpanSource(FTexture *tex); void R_MapTiltedPlane(int y, int x1); void R_MapColoredPlane(int y, int x1); - void R_DrawParticle(vissprite_t *); } diff --git a/src/r_draw_pal.cpp b/src/r_draw_pal.cpp index 2cdeba314..fbe372fb8 100644 --- a/src/r_draw_pal.cpp +++ b/src/r_draw_pal.cpp @@ -4,6 +4,7 @@ **--------------------------------------------------------------------------- ** Copyright 1998-2016 Randy Heit ** Copyright 2016 Magnus Norddahl +** Copyright 2016 Rachael Alexanderson ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without @@ -32,6 +33,7 @@ ** */ +#include #include "templates.h" #include "doomtype.h" #include "doomdef.h" @@ -42,6 +44,9 @@ #include "v_video.h" #include "r_draw_pal.h" +// [SP] r_blendmethod - false = rgb555 matching (ZDoom classic), true = rgb666 (refactored) +CVAR(Bool, r_blendmethod, false, CVAR_GLOBALCONFIG | CVAR_ARCHIVE) + /* [RH] This translucency algorithm is based on DOSDoom 0.65's, but uses a 32k RGB table instead of an 8k one. At least on my machine, it's @@ -99,6 +104,10 @@ namespace swrenderer _pitch = dc_pitch; _srcblend = dc_srcblend; _destblend = dc_destblend; + _dynlights = dc_lights; + _num_dynlights = dc_num_lights; + _viewpos_z = dc_viewpos.Z; + _step_viewpos_z = dc_viewpos_step.Z; } PalWall4Command::PalWall4Command() @@ -120,6 +129,43 @@ namespace swrenderer _destblend = dc_destblend; } + uint8_t PalWall1Command::AddLights(const TriLight *lights, int num_lights, float viewpos_z, uint8_t fg, uint8_t material) + { + uint32_t lit_r = GPalette.BaseColors[fg].r; + uint32_t lit_g = GPalette.BaseColors[fg].g; + uint32_t lit_b = GPalette.BaseColors[fg].b; + + uint32_t material_r = GPalette.BaseColors[material].r; + uint32_t material_g = GPalette.BaseColors[material].g; + uint32_t material_b = GPalette.BaseColors[material].b; + + for (int i = 0; i < num_lights; i++) + { + uint32_t light_color_r = RPART(lights[i].color); + uint32_t light_color_g = GPART(lights[i].color); + uint32_t light_color_b = BPART(lights[i].color); + + // L = light-pos + // dist = sqrt(dot(L, L)) + // attenuation = 1 - MIN(dist * (1/radius), 1) + float Lxy2 = lights[i].x; // L.x*L.x + L.y*L.y + float Lz = lights[i].z - viewpos_z; + float dist2 = Lxy2 + Lz * Lz; + float dist = dist2 * _mm_cvtss_f32(_mm_rsqrt_ss(_mm_load_ss(&dist2))); + uint32_t attenuation = (uint32_t)(256.0f - MIN(dist * lights[i].radius, 256.0f)); + + lit_r += (light_color_r * material_r * attenuation) >> 16; + lit_g += (light_color_g * material_g * attenuation) >> 16; + lit_b += (light_color_b * material_b * attenuation) >> 16; + } + + lit_r = MIN(lit_r, 255); + lit_g = MIN(lit_g, 255); + lit_b = MIN(lit_b, 255); + + return RGB256k.All[((lit_r >> 2) << 12) | ((lit_g >> 2) << 6) | (lit_b >> 2)]; + } + void DrawWall1PalCommand::Execute(DrawerThread *thread) { uint32_t fracstep = _iscale; @@ -130,6 +176,10 @@ namespace swrenderer uint8_t *dest = _dest; int bits = _fracbits; int pitch = _pitch; + TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; count = thread->count_for_thread(_dest_y, count); if (count <= 0) @@ -140,12 +190,31 @@ namespace swrenderer fracstep *= thread->num_cores; pitch *= thread->num_cores; - do + if (num_dynlights == 0) { - *dest = colormap[source[frac >> bits]]; - frac += fracstep; - dest += pitch; - } while (--count); + do + { + *dest = colormap[source[frac >> bits]]; + frac += fracstep; + dest += pitch; + } while (--count); + } + else + { + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; + + viewpos_z += step_viewpos_z * thread->skipped_by_thread(_dest_y); + step_viewpos_z *= thread->num_cores; + + do + { + *dest = AddLights(dynlights, num_dynlights, viewpos_z, colormap[source[frac >> bits]], source[frac >> bits]); + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWall4PalCommand::Execute(DrawerThread *thread) @@ -208,6 +277,10 @@ namespace swrenderer uint8_t *dest = _dest; int bits = _fracbits; int pitch = _pitch; + TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; count = thread->count_for_thread(_dest_y, count); if (count <= 0) @@ -218,16 +291,39 @@ namespace swrenderer fracstep *= thread->num_cores; pitch *= thread->num_cores; - do + if (num_dynlights == 0) { - uint8_t pix = source[frac >> bits]; - if (pix != 0) + do { - *dest = colormap[pix]; - } - frac += fracstep; - dest += pitch; - } while (--count); + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + *dest = colormap[pix]; + } + frac += fracstep; + dest += pitch; + } while (--count); + } + else + { + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; + + viewpos_z += step_viewpos_z * thread->skipped_by_thread(_dest_y); + step_viewpos_z *= thread->num_cores; + + do + { + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + *dest = AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix); + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWallMasked4PalCommand::Execute(DrawerThread *thread) @@ -305,19 +401,43 @@ namespace swrenderer fracstep *= thread->num_cores; pitch *= thread->num_cores; - do + if (!r_blendmethod) { - uint8_t pix = source[frac >> bits]; - if (pix != 0) + do { - uint32_t fg = fg2rgb[colormap[pix]]; - uint32_t bg = bg2rgb[*dest]; - fg = (fg + bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg >> 15)]; - } - frac += fracstep; - dest += pitch; - } while (--count); + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = colormap[pix]; + + uint32_t fg = fg2rgb[lit]; + uint32_t bg = bg2rgb[*dest]; + fg = (fg + bg) | 0x1f07c1f; + *dest = RGB32k.All[fg & (fg >> 15)]; + } + frac += fracstep; + dest += pitch; + } while (--count); + + } + else + { + do + { + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = colormap[pix]; + + uint32_t r = MIN(GPalette.BaseColors[lit].r + GPalette.BaseColors[*dest].r, 255); + uint32_t g = MIN(GPalette.BaseColors[lit].g + GPalette.BaseColors[*dest].g, 255); + uint32_t b = MIN(GPalette.BaseColors[lit].b + GPalette.BaseColors[*dest].b, 255); + *dest = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWallAdd4PalCommand::Execute(DrawerThread *thread) @@ -346,22 +466,44 @@ namespace swrenderer } pitch *= thread->num_cores; - do + if (!r_blendmethod) { - for (int i = 0; i < 4; ++i) + do { - uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; - if (pix != 0) + for (int i = 0; i < 4; ++i) { - uint32_t fg = fg2rgb[_colormap[i][pix]]; - uint32_t bg = bg2rgb[dest[i]]; - fg = (fg + bg) | 0x1f07c1f; - dest[i] = RGB32k.All[fg & (fg >> 15)]; + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + uint32_t fg = fg2rgb[_colormap[i][pix]]; + uint32_t bg = bg2rgb[dest[i]]; + fg = (fg + bg) | 0x1f07c1f; + dest[i] = RGB32k.All[fg & (fg >> 15)]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; } - dc_wall_texturefrac[i] += dc_wall_iscale[i]; - } - dest += pitch; - } while (--count); + dest += pitch; + } while (--count); + } + else + { + do + { + for (int i = 0; i < 4; ++i) + { + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + uint32_t r = MIN(GPalette.BaseColors[_colormap[i][pix]].r + GPalette.BaseColors[dest[i]].r, 255); + uint32_t g = MIN(GPalette.BaseColors[_colormap[i][pix]].g + GPalette.BaseColors[dest[i]].g, 255); + uint32_t b = MIN(GPalette.BaseColors[_colormap[i][pix]].b + GPalette.BaseColors[dest[i]].b, 255); + dest[i] = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; + } + dest += pitch; + } while (--count); + } } void DrawWallAddClamp1PalCommand::Execute(DrawerThread *thread) @@ -374,6 +516,10 @@ namespace swrenderer uint8_t *dest = _dest; int bits = _fracbits; int pitch = _pitch; + TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; @@ -386,25 +532,52 @@ namespace swrenderer frac += fracstep * thread->skipped_by_thread(_dest_y); fracstep *= thread->num_cores; pitch *= thread->num_cores; + viewpos_z += step_viewpos_z * thread->skipped_by_thread(_dest_y); + step_viewpos_z *= thread->num_cores; - do + if (!r_blendmethod) { - uint8_t pix = source[frac >> bits]; - if (pix != 0) + do { - uint32_t a = fg2rgb[colormap[pix]] + bg2rgb[*dest]; - uint32_t b = a; + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[a & (a >> 15)]; - } - frac += fracstep; - dest += pitch; - } while (--count); + uint32_t a = fg2rgb[lit] + bg2rgb[*dest]; + uint32_t b = a; + + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[a & (a >> 15)]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } + else + { + do + { + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; + + uint32_t r = MIN(GPalette.BaseColors[lit].r + GPalette.BaseColors[*dest].r, 255); + uint32_t g = MIN(GPalette.BaseColors[lit].g + GPalette.BaseColors[*dest].g, 255); + uint32_t b = MIN(GPalette.BaseColors[lit].b + GPalette.BaseColors[*dest].b, 255); + *dest = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWallAddClamp4PalCommand::Execute(DrawerThread *thread) @@ -440,15 +613,10 @@ namespace swrenderer uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; if (pix != 0) { - uint32_t a = fg2rgb[_colormap[i][pix]] + bg2rgb[dest[i]]; - uint32_t b = a; - - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - dest[i] = RGB32k.All[a & (a >> 15)]; + uint32_t r = MIN(GPalette.BaseColors[_colormap[i][pix]].r + GPalette.BaseColors[dest[i]].r, 255); + uint32_t g = MIN(GPalette.BaseColors[_colormap[i][pix]].g + GPalette.BaseColors[dest[i]].g, 255); + uint32_t b = MIN(GPalette.BaseColors[_colormap[i][pix]].b + GPalette.BaseColors[dest[i]].b, 255); + dest[i] = RGB256k.RGB[r>>2][g>>2][b>>2]; } dc_wall_texturefrac[i] += dc_wall_iscale[i]; } @@ -466,6 +634,10 @@ namespace swrenderer uint8_t *dest = _dest; int bits = _fracbits; int pitch = _pitch; + TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; @@ -478,24 +650,51 @@ namespace swrenderer frac += fracstep * thread->skipped_by_thread(_dest_y); fracstep *= thread->num_cores; pitch *= thread->num_cores; + viewpos_z += step_viewpos_z * thread->skipped_by_thread(_dest_y); + step_viewpos_z *= thread->num_cores; - do + if (!r_blendmethod) { - uint8_t pix = source[frac >> bits]; - if (pix != 0) + do { - uint32_t a = (fg2rgb[colormap[pix]] | 0x40100400) - bg2rgb[*dest]; - uint32_t b = a; + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - } - frac += fracstep; - dest += pitch; - } while (--count); + uint32_t a = (fg2rgb[lit] | 0x40100400) - bg2rgb[*dest]; + uint32_t b = a; + + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } + else + { + do + { + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; + + int r = clamp(-GPalette.BaseColors[lit].r + GPalette.BaseColors[*dest].r, 0, 255); + int g = clamp(-GPalette.BaseColors[lit].g + GPalette.BaseColors[*dest].g, 0, 255); + int b = clamp(-GPalette.BaseColors[lit].b + GPalette.BaseColors[*dest].b, 0, 255); + *dest = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWallSubClamp4PalCommand::Execute(DrawerThread *thread) @@ -524,26 +723,48 @@ namespace swrenderer } pitch *= thread->num_cores; - do + if (!r_blendmethod) { - for (int i = 0; i < 4; ++i) + do { - uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; - if (pix != 0) + for (int i = 0; i < 4; ++i) { - uint32_t a = (fg2rgb[_colormap[i][pix]] | 0x40100400) - bg2rgb[dest[i]]; - uint32_t b = a; + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + uint32_t a = (fg2rgb[_colormap[i][pix]] | 0x40100400) - bg2rgb[dest[i]]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[i] = RGB32k.All[a & (a >> 15)]; + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + dest[i] = RGB32k.All[a & (a >> 15)]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; } - dc_wall_texturefrac[i] += dc_wall_iscale[i]; - } - dest += pitch; - } while (--count); + dest += pitch; + } while (--count); + } + else + { + do + { + for (int i = 0; i < 4; ++i) + { + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + int r = clamp(-GPalette.BaseColors[_colormap[i][pix]].r + GPalette.BaseColors[dest[i]].r, 0, 255); + int g = clamp(-GPalette.BaseColors[_colormap[i][pix]].g + GPalette.BaseColors[dest[i]].g, 0, 255); + int b = clamp(-GPalette.BaseColors[_colormap[i][pix]].b + GPalette.BaseColors[dest[i]].b, 0, 255); + dest[i] = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; + } + dest += pitch; + } while (--count); + } } void DrawWallRevSubClamp1PalCommand::Execute(DrawerThread *thread) @@ -556,6 +777,10 @@ namespace swrenderer uint8_t *dest = _dest; int bits = _fracbits; int pitch = _pitch; + TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_z = _viewpos_z; + float step_viewpos_z = _step_viewpos_z; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; @@ -568,24 +793,51 @@ namespace swrenderer frac += fracstep * thread->skipped_by_thread(_dest_y); fracstep *= thread->num_cores; pitch *= thread->num_cores; + viewpos_z += step_viewpos_z * thread->skipped_by_thread(_dest_y); + step_viewpos_z *= thread->num_cores; - do + if (!r_blendmethod) { - uint8_t pix = source[frac >> bits]; - if (pix != 0) + do { - uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[pix]]; - uint32_t b = a; + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - } - frac += fracstep; - dest += pitch; - } while (--count); + uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[lit]; + uint32_t b = a; + + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } + else + { + do + { + uint8_t pix = source[frac >> bits]; + if (pix != 0) + { + uint8_t lit = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_z, colormap[pix], pix) : colormap[pix]; + + int r = clamp(GPalette.BaseColors[lit].r - GPalette.BaseColors[*dest].r, 0, 255); + int g = clamp(GPalette.BaseColors[lit].g - GPalette.BaseColors[*dest].g, 0, 255); + int b = clamp(GPalette.BaseColors[lit].b - GPalette.BaseColors[*dest].b, 0, 255); + *dest = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + viewpos_z += step_viewpos_z; + frac += fracstep; + dest += pitch; + } while (--count); + } } void DrawWallRevSubClamp4PalCommand::Execute(DrawerThread *thread) @@ -614,26 +866,48 @@ namespace swrenderer } pitch *= thread->num_cores; - do + if (!r_blendmethod) { - for (int i = 0; i < 4; ++i) + do { - uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; - if (pix != 0) + for (int i = 0; i < 4; ++i) { - uint32_t a = (bg2rgb[dest[i]] | 0x40100400) - fg2rgb[_colormap[i][pix]]; - uint32_t b = a; + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + uint32_t a = (bg2rgb[dest[i]] | 0x40100400) - fg2rgb[_colormap[i][pix]]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[i] = RGB32k.All[a & (a >> 15)]; + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + dest[i] = RGB32k.All[a & (a >> 15)]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; } - dc_wall_texturefrac[i] += dc_wall_iscale[i]; - } - dest += _pitch; - } while (--count); + dest += _pitch; + } while (--count); + } + else + { + do + { + for (int i = 0; i < 4; ++i) + { + uint8_t pix = _source[i][dc_wall_texturefrac[i] >> bits]; + if (pix != 0) + { + uint32_t r = clamp(GPalette.BaseColors[_colormap[i][pix]].r - GPalette.BaseColors[dest[i]].r, 0, 255); + uint32_t g = clamp(GPalette.BaseColors[_colormap[i][pix]].g - GPalette.BaseColors[dest[i]].g, 0, 255); + uint32_t b = clamp(GPalette.BaseColors[_colormap[i][pix]].b - GPalette.BaseColors[dest[i]].b, 0, 255); + dest[i] = RGB256k.RGB[r>>2][g>>2][b>>2]; + } + dc_wall_texturefrac[i] += dc_wall_iscale[i]; + } + dest += _pitch; + } while (--count); + } } ///////////////////////////////////////////////////////////////////////// @@ -712,7 +986,7 @@ namespace swrenderer c_red = (c_red * alpha_bottom + solid_bottom_r * inv_alpha_bottom) >> 8; c_green = (c_green * alpha_bottom + solid_bottom_g * inv_alpha_bottom) >> 8; c_blue = (c_blue * alpha_bottom + solid_bottom_b * inv_alpha_bottom) >> 8; - *dest = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; + *dest = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; } frac += fracstep; @@ -740,8 +1014,8 @@ namespace swrenderer int solid_bottom_r = RPART(solid_bottom); int solid_bottom_g = GPART(solid_bottom); int solid_bottom_b = BPART(solid_bottom); - uint32_t solid_top_fill = RGB32k.RGB[(solid_top_r >> 3)][(solid_top_g >> 3)][(solid_top_b >> 3)]; - uint32_t solid_bottom_fill = RGB32k.RGB[(solid_bottom_r >> 3)][(solid_bottom_g >> 3)][(solid_bottom_b >> 3)]; + uint32_t solid_top_fill = RGB256k.RGB[(solid_top_r >> 2)][(solid_top_g >> 2)][(solid_top_b >> 2)]; + uint32_t solid_bottom_fill = RGB256k.RGB[(solid_bottom_r >> 2)][(solid_bottom_g >> 2)][(solid_bottom_b >> 2)]; solid_top_fill = (solid_top_fill << 24) | (solid_top_fill << 16) | (solid_top_fill << 8) | solid_top_fill; solid_bottom_fill = (solid_bottom_fill << 24) | (solid_bottom_fill << 16) | (solid_bottom_fill << 8) | solid_bottom_fill; @@ -801,8 +1075,7 @@ namespace swrenderer c_red = (c_red * alpha_top + solid_top_r * inv_alpha_top) >> 8; c_green = (c_green * alpha_top + solid_top_g * inv_alpha_top) >> 8; c_blue = (c_blue * alpha_top + solid_top_b * inv_alpha_top) >> 8; - output[col] = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; - + output[col] = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; frac[col] += fracstep[col]; } *((uint32_t*)dest) = *((uint32_t*)output); @@ -843,7 +1116,7 @@ namespace swrenderer c_red = (c_red * alpha_bottom + solid_bottom_r * inv_alpha_bottom) >> 8; c_green = (c_green * alpha_bottom + solid_bottom_g * inv_alpha_bottom) >> 8; c_blue = (c_blue * alpha_bottom + solid_bottom_b * inv_alpha_bottom) >> 8; - output[col] = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; + output[col] = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; frac[col] += fracstep[col]; } @@ -925,7 +1198,7 @@ namespace swrenderer c_red = (c_red * alpha_bottom + solid_bottom_r * inv_alpha_bottom) >> 8; c_green = (c_green * alpha_bottom + solid_bottom_g * inv_alpha_bottom) >> 8; c_blue = (c_blue * alpha_bottom + solid_bottom_b * inv_alpha_bottom) >> 8; - *dest = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; + *dest = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; } frac += fracstep; @@ -955,8 +1228,8 @@ namespace swrenderer int solid_bottom_r = RPART(solid_bottom); int solid_bottom_g = GPART(solid_bottom); int solid_bottom_b = BPART(solid_bottom); - uint32_t solid_top_fill = RGB32k.RGB[(solid_top_r >> 3)][(solid_top_g >> 3)][(solid_top_b >> 3)]; - uint32_t solid_bottom_fill = RGB32k.RGB[(solid_bottom_r >> 3)][(solid_bottom_g >> 3)][(solid_bottom_b >> 3)]; + uint32_t solid_top_fill = RGB256k.RGB[(solid_top_r >> 2)][(solid_top_g >> 2)][(solid_top_b >> 2)]; + uint32_t solid_bottom_fill = RGB256k.RGB[(solid_bottom_r >> 2)][(solid_bottom_g >> 2)][(solid_bottom_b >> 2)]; solid_top_fill = (solid_top_fill << 24) | (solid_top_fill << 16) | (solid_top_fill << 8) | solid_top_fill; solid_bottom_fill = (solid_bottom_fill << 24) | (solid_bottom_fill << 16) | (solid_bottom_fill << 8) | solid_bottom_fill; @@ -1022,7 +1295,7 @@ namespace swrenderer c_red = (c_red * alpha_top + solid_top_r * inv_alpha_top) >> 8; c_green = (c_green * alpha_top + solid_top_g * inv_alpha_top) >> 8; c_blue = (c_blue * alpha_top + solid_top_b * inv_alpha_top) >> 8; - output[col] = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; + output[col] = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; frac[col] += fracstep[col]; } @@ -1076,7 +1349,7 @@ namespace swrenderer c_red = (c_red * alpha_bottom + solid_bottom_r * inv_alpha_bottom) >> 8; c_green = (c_green * alpha_bottom + solid_bottom_g * inv_alpha_bottom) >> 8; c_blue = (c_blue * alpha_bottom + solid_bottom_b * inv_alpha_bottom) >> 8; - output[col] = RGB32k.RGB[(c_red >> 3)][(c_green >> 3)][(c_blue >> 3)]; + output[col] = RGB256k.RGB[(c_red >> 2)][(c_green >> 2)][(c_blue >> 2)]; frac[col] += fracstep[col]; } @@ -1112,6 +1385,8 @@ namespace swrenderer _srcblend = dc_srcblend; _destblend = dc_destblend; _srccolor = dc_srccolor; + _srcalpha = dc_srcalpha; + _destalpha = dc_destalpha; } void DrawColumnPalCommand::Execute(DrawerThread *thread) @@ -1206,14 +1481,32 @@ namespace swrenderer dest = thread->dest_for_thread(_dest_y, pitch, dest); pitch *= thread->num_cores; - do - { - uint32_t bg; - bg = (fg + bg2rgb[*dest]) | 0x1f07c1f; - *dest = RGB32k.All[bg & (bg >> 15)]; - dest += pitch; - } while (--count); + const PalEntry* pal = GPalette.BaseColors; + if (!r_blendmethod) + { + do + { + uint32_t bg; + bg = (fg + bg2rgb[*dest]) | 0x1f07c1f; + *dest = RGB32k.All[bg & (bg >> 15)]; + dest += pitch; + } while (--count); + } + else + { + int src_r = ((_srccolor >> 16) & 0xff) * _srcalpha; + int src_g = ((_srccolor >> 0) & 0xff) * _srcalpha; + int src_b = ((_srccolor >> 8) & 0xff) * _srcalpha; + do + { + int r = clamp((src_r + pal[*dest].r * _destalpha)>>18, 0, 255); + int g = clamp((src_g + pal[*dest].g * _destalpha)>>18, 0, 255); + int b = clamp((src_b + pal[*dest].b * _destalpha)>>18, 0, 255); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + } while (--count); + } } void FillColumnAddClampPalCommand::Execute(DrawerThread *thread) @@ -1238,19 +1531,38 @@ namespace swrenderer dest = thread->dest_for_thread(_dest_y, pitch, dest); pitch *= thread->num_cores; - do - { - uint32_t a = fg + bg2rgb[*dest]; - uint32_t b = a; + const PalEntry* pal = GPalette.BaseColors; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - } while (--count); + if (!r_blendmethod) + { + do + { + uint32_t a = fg + bg2rgb[*dest]; + uint32_t b = a; + + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + } while (--count); + } + else + { + int src_r = ((_srccolor >> 16) & 0xff) * _srcalpha; + int src_g = ((_srccolor >> 0) & 0xff) * _srcalpha; + int src_b = ((_srccolor >> 8) & 0xff) * _srcalpha; + do + { + int r = clamp((src_r + pal[*dest].r * _destalpha)>>18, 0, 255); + int g = clamp((src_g + pal[*dest].g * _destalpha)>>18, 0, 255); + int b = clamp((src_b + pal[*dest].b * _destalpha)>>18, 0, 255); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + } while (--count); + } } void FillColumnSubClampPalCommand::Execute(DrawerThread *thread) @@ -1261,11 +1573,9 @@ namespace swrenderer count = _count; dest = _dest; - uint32_t *bg2rgb; - uint32_t fg; + uint32_t *bg2rgb = _destblend; + uint32_t fg = _srccolor; - bg2rgb = _destblend; - fg = _srccolor | 0x40100400; int pitch = _pitch; count = thread->count_for_thread(_dest_y, count); @@ -1275,18 +1585,39 @@ namespace swrenderer dest = thread->dest_for_thread(_dest_y, pitch, dest); pitch *= thread->num_cores; - do - { - uint32_t a = fg - bg2rgb[*dest]; - uint32_t b = a; + const PalEntry* palette = GPalette.BaseColors; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - } while (--count); + if (!r_blendmethod) + { + do + { + uint32_t a = fg - bg2rgb[*dest]; + uint32_t b = a; + + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + } while (--count); + } + else + { + do + { + int src_r = ((_srccolor >> 16) & 0xff) * _srcalpha; + int src_g = ((_srccolor >> 0) & 0xff) * _srcalpha; + int src_b = ((_srccolor >> 8) & 0xff) * _srcalpha; + int bg = *dest; + int r = MAX((-src_r + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((-src_g + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((-src_b + palette[bg].b * _destalpha)>>18, 0); + + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + } while (--count); + } } void FillColumnRevSubClampPalCommand::Execute(DrawerThread *thread) @@ -1299,11 +1630,9 @@ namespace swrenderer return; dest = _dest; - uint32_t *bg2rgb; - uint32_t fg; + uint32_t *bg2rgb = _destblend; + uint32_t fg = _srccolor; - bg2rgb = _destblend; - fg = _srccolor; int pitch = _pitch; count = thread->count_for_thread(_dest_y, count); @@ -1313,18 +1642,39 @@ namespace swrenderer dest = thread->dest_for_thread(_dest_y, pitch, dest); pitch *= thread->num_cores; - do - { - uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg; - uint32_t b = a; + const PalEntry *palette = GPalette.BaseColors; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - } while (--count); + if (!r_blendmethod) + { + do + { + uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg; + uint32_t b = a; + + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + } while (--count); + } + else + { + do + { + int src_r = ((_srccolor >> 16) & 0xff) * _srcalpha; + int src_g = ((_srccolor >> 0) & 0xff) * _srcalpha; + int src_b = ((_srccolor >> 8) & 0xff) * _srcalpha; + int bg = *dest; + int r = MAX((src_r - palette[bg].r * _destalpha)>>18, 0); + int g = MAX((src_g - palette[bg].g * _destalpha)>>18, 0); + int b = MAX((src_b - palette[bg].b * _destalpha)>>18, 0); + + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + } while (--count); + } } void DrawColumnAddPalCommand::Execute(DrawerThread *thread) @@ -1354,19 +1704,37 @@ namespace swrenderer uint32_t *bg2rgb = _destblend; const uint8_t *colormap = _colormap; const uint8_t *source = _source; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t fg = colormap[source[frac >> FRACBITS]]; - uint32_t bg = *dest; + do + { + uint32_t fg = colormap[source[frac >> FRACBITS]]; + uint32_t bg = *dest; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest = RGB32k.All[fg & (fg >> 15)]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + uint32_t fg = colormap[source[frac >> FRACBITS]]; + uint32_t bg = *dest; + uint32_t r = MIN((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 63); + uint32_t g = MIN((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 63); + uint32_t b = MIN((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 63); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnTranslatedPalCommand::Execute(DrawerThread *thread) @@ -1436,18 +1804,37 @@ namespace swrenderer const uint8_t *colormap = _colormap; const uint8_t *source = _source; - do - { - uint32_t fg = colormap[translation[source[frac >> FRACBITS]]]; - uint32_t bg = *dest; + const PalEntry *palette = GPalette.BaseColors; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + if (!r_blendmethod) + { + do + { + uint32_t fg = colormap[translation[source[frac >> FRACBITS]]]; + uint32_t bg = *dest; + + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest = RGB32k.All[fg & (fg >> 15)]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + uint32_t fg = colormap[translation[source[frac >> FRACBITS]]]; + uint32_t bg = *dest; + uint32_t r = MIN((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 63); + uint32_t g = MIN((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 63); + uint32_t b = MIN((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 63); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnShadedPalCommand::Execute(DrawerThread *thread) @@ -1475,17 +1862,36 @@ namespace swrenderer const uint8_t *source = _source; const uint8_t *colormap = _colormap; uint32_t *fgstart = &Col2RGB8[0][_color]; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t val = colormap[source[frac >> FRACBITS]]; - uint32_t fg = fgstart[val << 8]; - val = (Col2RGB8[64 - val][*dest] + fg) | 0x1f07c1f; - *dest = RGB32k.All[val & (val >> 15)]; + do + { + uint32_t val = colormap[source[frac >> FRACBITS]]; + uint32_t fg = fgstart[val << 8]; + val = (Col2RGB8[64 - val][*dest] + fg) | 0x1f07c1f; + *dest = RGB32k.All[val & (val >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + uint32_t val = source[frac >> FRACBITS]; + + int r = (palette[*dest].r * (255-val) + palette[_color].r * val) >> 10; + int g = (palette[*dest].g * (255-val) + palette[_color].g * val) >> 10; + int b = (palette[*dest].b * (255-val) + palette[_color].b * val) >> 10; + *dest = RGB256k.RGB[clamp(r,0,63)][clamp(g,0,63)][clamp(b,0,63)]; + + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnAddClampPalCommand::Execute(DrawerThread *thread) @@ -1515,21 +1921,39 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = fg2rgb[colormap[source[frac >> FRACBITS]]] + bg2rgb[*dest]; - uint32_t b = a; + do + { + uint32_t a = fg2rgb[colormap[source[frac >> FRACBITS]]] + bg2rgb[*dest]; + uint32_t b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[source[frac >> FRACBITS]]; + int bg = *dest; + int r = MIN((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 63); + int g = MIN((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 63); + int b = MIN((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 63); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnAddClampTranslatedPalCommand::Execute(DrawerThread *thread) @@ -1560,21 +1984,39 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = fg2rgb[colormap[translation[source[frac >> FRACBITS]]]] + bg2rgb[*dest]; - uint32_t b = a; + do + { + uint32_t a = fg2rgb[colormap[translation[source[frac >> FRACBITS]]]] + bg2rgb[*dest]; + uint32_t b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[(a >> 15) & a]; - dest += pitch; - frac += fracstep; - } while (--count); + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[(a >> 15) & a]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[translation[source[frac >> FRACBITS]]]; + int bg = *dest; + int r = MIN((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 63); + int g = MIN((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 63); + int b = MIN((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 63); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnSubClampPalCommand::Execute(DrawerThread *thread) @@ -1604,20 +2046,38 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = (fg2rgb[colormap[source[frac >> FRACBITS]]] | 0x40100400) - bg2rgb[*dest]; - uint32_t b = a; + do + { + uint32_t a = (fg2rgb[colormap[source[frac >> FRACBITS]]] | 0x40100400) - bg2rgb[*dest]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[source[frac >> FRACBITS]]; + int bg = *dest; + int r = MAX((palette[fg].r * _srcalpha - palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha - palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha - palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnSubClampTranslatedPalCommand::Execute(DrawerThread *thread) @@ -1648,20 +2108,38 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = (fg2rgb[colormap[translation[source[frac >> FRACBITS]]]] | 0x40100400) - bg2rgb[*dest]; - uint32_t b = a; + do + { + uint32_t a = (fg2rgb[colormap[translation[source[frac >> FRACBITS]]]] | 0x40100400) - bg2rgb[*dest]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[(a >> 15) & a]; - dest += pitch; - frac += fracstep; - } while (--count); + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[(a >> 15) & a]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[translation[source[frac >> FRACBITS]]]; + int bg = *dest; + int r = MAX((palette[fg].r * _srcalpha - palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha - palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha - palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnRevSubClampPalCommand::Execute(DrawerThread *thread) @@ -1691,20 +2169,38 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[source[frac >> FRACBITS]]]; - uint32_t b = a; + do + { + uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[source[frac >> FRACBITS]]]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[a & (a >> 15)]; - dest += pitch; - frac += fracstep; - } while (--count); + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[a & (a >> 15)]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[source[frac >> FRACBITS]]; + int bg = *dest; + int r = MAX((-palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((-palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((-palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } void DrawColumnRevSubClampTranslatedPalCommand::Execute(DrawerThread *thread) @@ -1735,20 +2231,38 @@ namespace swrenderer const uint8_t *source = _source; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; - do + if (!r_blendmethod) { - uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[translation[source[frac >> FRACBITS]]]]; - uint32_t b = a; + do + { + uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[translation[source[frac >> FRACBITS]]]]; + uint32_t b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[(a >> 15) & a]; - dest += pitch; - frac += fracstep; - } while (--count); + b &= 0x40100400; + b = b - (b >> 5); + a &= b; + a |= 0x01f07c1f; + *dest = RGB32k.All[(a >> 15) & a]; + dest += pitch; + frac += fracstep; + } while (--count); + } + else + { + do + { + int fg = colormap[translation[source[frac >> FRACBITS]]]; + int bg = *dest; + int r = MAX((-palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((-palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((-palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + dest += pitch; + frac += fracstep; + } while (--count); + } } ///////////////////////////////////////////////////////////////////////// @@ -1861,6 +2375,49 @@ namespace swrenderer _srcblend = dc_srcblend; _destblend = dc_destblend; _color = ds_color; + _srcalpha = dc_srcalpha; + _destalpha = dc_destalpha; + _dynlights = dc_lights; + _num_dynlights = dc_num_lights; + _viewpos_x = dc_viewpos.X; + _step_viewpos_x = dc_viewpos_step.X; + } + + uint8_t PalSpanCommand::AddLights(const TriLight *lights, int num_lights, float viewpos_x, uint8_t fg, uint8_t material) + { + uint32_t lit_r = GPalette.BaseColors[fg].r; + uint32_t lit_g = GPalette.BaseColors[fg].g; + uint32_t lit_b = GPalette.BaseColors[fg].b; + + uint32_t material_r = GPalette.BaseColors[material].r; + uint32_t material_g = GPalette.BaseColors[material].g; + uint32_t material_b = GPalette.BaseColors[material].b; + + for (int i = 0; i < num_lights; i++) + { + uint32_t light_color_r = RPART(lights[i].color); + uint32_t light_color_g = GPART(lights[i].color); + uint32_t light_color_b = BPART(lights[i].color); + + // L = light-pos + // dist = sqrt(dot(L, L)) + // attenuation = 1 - MIN(dist * (1/radius), 1) + float Lyz2 = lights[i].y; // L.y*L.y + L.z*L.z + float Lx = lights[i].x - viewpos_x; + float dist2 = Lyz2 + Lx * Lx; + float dist = dist2 * _mm_cvtss_f32(_mm_rsqrt_ss(_mm_load_ss(&dist2))); + uint32_t attenuation = (uint32_t)(256.0f - MIN(dist * lights[i].radius, 256.0f)); + + lit_r += (light_color_r * material_r * attenuation) >> 16; + lit_g += (light_color_g * material_g * attenuation) >> 16; + lit_b += (light_color_b * material_b * attenuation) >> 16; + } + + lit_r = MIN(lit_r, 255); + lit_g = MIN(lit_g, 255); + lit_b = MIN(lit_b, 255); + + return RGB256k.All[((lit_r >> 2) << 12) | ((lit_g >> 2) << 6) | (lit_b >> 2)]; } void DrawSpanPalCommand::Execute(DrawerThread *thread) @@ -1888,7 +2445,12 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; - if (_xbits == 6 && _ybits == 6) + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; + + if (_xbits == 6 && _ybits == 6 && num_dynlights == 0) { // 64x64 is the most common case by far, so special case it. do @@ -1905,6 +2467,24 @@ namespace swrenderer yfrac += ystep; } while (--count); } + else if (_xbits == 6 && _ybits == 6) + { + // 64x64 is the most common case by far, so special case it. + do + { + // Current texture index in u,v. + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + + // Lookup pixel from flat texture tile, + // re-index using light/colormap. + *dest++ = AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]); + + // Next step in u,v. + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } else { uint8_t yshift = 32 - _ybits; @@ -1918,11 +2498,12 @@ namespace swrenderer // Lookup pixel from flat texture tile, // re-index using light/colormap. - *dest++ = colormap[source[spot]]; + *dest++ = AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]); // Next step in u,v. xfrac += xstep; yfrac += ystep; + viewpos_x += step_viewpos_x; } while (--count); } } @@ -1952,6 +2533,11 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; + if (_xbits == 6 && _ybits == 6) { // 64x64 is the most common case by far, so special case it. @@ -1963,11 +2549,12 @@ namespace swrenderer texdata = source[spot]; if (texdata != 0) { - *dest = colormap[texdata]; + *dest = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; } dest++; xfrac += xstep; yfrac += ystep; + viewpos_x += step_viewpos_x; } while (--count); } else @@ -1983,11 +2570,12 @@ namespace swrenderer texdata = source[spot]; if (texdata != 0) { - *dest = colormap[texdata]; + *dest = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; } dest++; xfrac += xstep; yfrac += ystep; + viewpos_x += step_viewpos_x; } while (--count); } } @@ -2019,39 +2607,92 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; - if (_xbits == 6 && _ybits == 6) + const PalEntry *palette = GPalette.BaseColors; + + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; + + if (!r_blendmethod) { - // 64x64 is the most common case by far, so special case it. - do + if (_xbits == 6 && _ybits == 6) { - spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); - uint32_t fg = colormap[source[spot]]; - uint32_t bg = *dest; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest++ = RGB32k.All[fg & (fg >> 15)]; - xfrac += xstep; - yfrac += ystep; - } while (--count); + // 64x64 is the most common case by far, so special case it. + do + { + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest++ = RGB32k.All[fg & (fg >> 15)]; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest++ = RGB32k.All[fg & (fg >> 15)]; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } else { - uint8_t yshift = 32 - _ybits; - uint8_t xshift = yshift - _xbits; - int xmask = ((1 << _xbits) - 1) << _ybits; - do + if (_xbits == 6 && _ybits == 6) { - spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); - uint32_t fg = colormap[source[spot]]; - uint32_t bg = *dest; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest++ = RGB32k.All[fg & (fg >> 15)]; - xfrac += xstep; - yfrac += ystep; - } while (--count); + // 64x64 is the most common case by far, so special case it. + do + { + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest++ = RGB256k.RGB[r][g][b]; + + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest++ = RGB256k.RGB[r][g][b]; + + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } } @@ -2072,6 +2713,13 @@ namespace swrenderer uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; + + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; + xfrac = _xfrac; yfrac = _yfrac; @@ -2082,53 +2730,111 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; - if (_xbits == 6 && _ybits == 6) + if (!r_blendmethod) { - // 64x64 is the most common case by far, so special case it. - do + if (_xbits == 6 && _ybits == 6) { - uint8_t texdata; - - spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); - texdata = source[spot]; - if (texdata != 0) + // 64x64 is the most common case by far, so special case it. + do { - uint32_t fg = colormap[texdata]; - uint32_t bg = *dest; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg >> 15)]; - } - dest++; - xfrac += xstep; - yfrac += ystep; - } while (--count); + uint8_t texdata; + + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest = RGB32k.All[fg & (fg >> 15)]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + uint8_t texdata; + + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + fg = fg2rgb[fg]; + bg = bg2rgb[bg]; + fg = (fg + bg) | 0x1f07c1f; + *dest = RGB32k.All[fg & (fg >> 15)]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } else { - uint8_t yshift = 32 - _ybits; - uint8_t xshift = yshift - _xbits; - int xmask = ((1 << _xbits) - 1) << _ybits; - do + if (_xbits == 6 && _ybits == 6) { - uint8_t texdata; - - spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); - texdata = source[spot]; - if (texdata != 0) + // 64x64 is the most common case by far, so special case it. + do { - uint32_t fg = colormap[texdata]; - uint32_t bg = *dest; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg + bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg >> 15)]; - } - dest++; - xfrac += xstep; - yfrac += ystep; - } while (--count); + uint8_t texdata; + + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + uint8_t texdata; + + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } } @@ -2148,6 +2854,12 @@ namespace swrenderer int spot; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; + + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; xfrac = _xfrac; yfrac = _yfrac; @@ -2159,45 +2871,93 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; - if (_xbits == 6 && _ybits == 6) + if (!r_blendmethod) { - // 64x64 is the most common case by far, so special case it. - do + if (_xbits == 6 && _ybits == 6) { - spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); - uint32_t a = fg2rgb[colormap[source[spot]]] + bg2rgb[*dest]; - uint32_t b = a; + // 64x64 is the most common case by far, so special case it. + do + { + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t a = fg2rgb[fg] + bg2rgb[*dest]; + uint32_t b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest++ = RGB32k.All[a & (a >> 15)]; - xfrac += xstep; - yfrac += ystep; - } while (--count); + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest++ = RGB32k.All[a & (a >> 15)]; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t a = fg2rgb[fg] + bg2rgb[*dest]; + uint32_t b = a; + + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest++ = RGB32k.All[a & (a >> 15)]; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } else { - uint8_t yshift = 32 - _ybits; - uint8_t xshift = yshift - _xbits; - int xmask = ((1 << _xbits) - 1) << _ybits; - do + if (_xbits == 6 && _ybits == 6) { - spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); - uint32_t a = fg2rgb[colormap[source[spot]]] + bg2rgb[*dest]; - uint32_t b = a; + // 64x64 is the most common case by far, so special case it. + do + { + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest++ = RGB256k.RGB[r][g][b]; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest++ = RGB32k.All[a & (a >> 15)]; - xfrac += xstep; - yfrac += ystep; - } while (--count); + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[source[spot]], source[spot]) : colormap[source[spot]]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest++ = RGB256k.RGB[r][g][b]; + + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } } @@ -2217,6 +2977,12 @@ namespace swrenderer int spot; uint32_t *fg2rgb = _srcblend; uint32_t *bg2rgb = _destblend; + const PalEntry *palette = GPalette.BaseColors; + + const TriLight *dynlights = _dynlights; + int num_dynlights = _num_dynlights; + float viewpos_x = _viewpos_x; + float step_viewpos_x = _step_viewpos_x; xfrac = _xfrac; yfrac = _yfrac; @@ -2228,59 +2994,119 @@ namespace swrenderer xstep = _xstep; ystep = _ystep; - if (_xbits == 6 && _ybits == 6) + if (!r_blendmethod) { - // 64x64 is the most common case by far, so special case it. - do + if (_xbits == 6 && _ybits == 6) { - uint8_t texdata; - - spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); - texdata = source[spot]; - if (texdata != 0) + // 64x64 is the most common case by far, so special case it. + do { - uint32_t a = fg2rgb[colormap[texdata]] + bg2rgb[*dest]; - uint32_t b = a; + uint8_t texdata; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[a & (a >> 15)]; - } - dest++; - xfrac += xstep; - yfrac += ystep; - } while (--count); + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t a = fg2rgb[fg] + bg2rgb[*dest]; + uint32_t b = a; + + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[a & (a >> 15)]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + uint8_t texdata; + + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t a = fg2rgb[fg] + bg2rgb[*dest]; + uint32_t b = a; + + a |= 0x01f07c1f; + b &= 0x40100400; + a &= 0x3fffffff; + b = b - (b >> 5); + a |= b; + *dest = RGB32k.All[a & (a >> 15)]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } else { - uint8_t yshift = 32 - _ybits; - uint8_t xshift = yshift - _xbits; - int xmask = ((1 << _xbits) - 1) << _ybits; - do + if (_xbits == 6 && _ybits == 6) { - uint8_t texdata; - - spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); - texdata = source[spot]; - if (texdata != 0) + // 64x64 is the most common case by far, so special case it. + do { - uint32_t a = fg2rgb[colormap[texdata]] + bg2rgb[*dest]; - uint32_t b = a; + uint8_t texdata; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[a & (a >> 15)]; - } - dest++; - xfrac += xstep; - yfrac += ystep; - } while (--count); + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } + else + { + uint8_t yshift = 32 - _ybits; + uint8_t xshift = yshift - _xbits; + int xmask = ((1 << _xbits) - 1) << _ybits; + do + { + uint8_t texdata; + + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + texdata = source[spot]; + if (texdata != 0) + { + uint32_t fg = num_dynlights != 0 ? AddLights(dynlights, num_dynlights, viewpos_x, colormap[texdata], texdata) : colormap[texdata]; + uint32_t bg = *dest; + int r = MAX((palette[fg].r * _srcalpha + palette[bg].r * _destalpha)>>18, 0); + int g = MAX((palette[fg].g * _srcalpha + palette[bg].g * _destalpha)>>18, 0); + int b = MAX((palette[fg].b * _srcalpha + palette[bg].b * _destalpha)>>18, 0); + *dest = RGB256k.RGB[r][g][b]; + } + dest++; + xfrac += xstep; + yfrac += ystep; + viewpos_x += step_viewpos_x; + } while (--count); + } } } @@ -2619,4 +3445,85 @@ namespace swrenderer dest[x] = colormap[dest[x]]; } while (++x <= x2); } + + ///////////////////////////////////////////////////////////////////////////// + + namespace + { + static uint32_t particle_texture[16 * 16] = + { + 1 * 1, 2 * 1, 3 * 1, 4 * 1, 5 * 1, 6 * 1, 7 * 1, 8 * 1, 8 * 1, 7 * 1, 6 * 1, 5 * 1, 4 * 1, 3 * 1, 2 * 1, 1 * 1, + 1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2, 6 * 2, 7 * 2, 8 * 2, 8 * 2, 7 * 2, 6 * 2, 5 * 2, 4 * 2, 3 * 2, 2 * 2, 1 * 2, + 1 * 3, 2 * 3, 3 * 3, 4 * 3, 5 * 3, 6 * 3, 7 * 3, 8 * 3, 8 * 3, 7 * 3, 6 * 3, 5 * 3, 4 * 3, 3 * 3, 2 * 3, 1 * 3, + 1 * 4, 2 * 4, 3 * 4, 4 * 4, 5 * 4, 6 * 4, 7 * 4, 8 * 4, 8 * 4, 7 * 4, 6 * 4, 5 * 4, 4 * 4, 3 * 4, 2 * 4, 1 * 4, + 1 * 5, 2 * 5, 3 * 5, 4 * 5, 5 * 5, 6 * 5, 7 * 5, 8 * 5, 8 * 5, 7 * 5, 6 * 5, 5 * 5, 4 * 5, 3 * 5, 2 * 5, 1 * 5, + 1 * 6, 2 * 6, 3 * 6, 4 * 6, 5 * 6, 6 * 6, 7 * 6, 8 * 6, 8 * 6, 7 * 6, 6 * 6, 5 * 6, 4 * 6, 3 * 6, 2 * 6, 1 * 6, + 1 * 7, 2 * 7, 3 * 7, 4 * 7, 5 * 7, 6 * 7, 7 * 7, 8 * 7, 8 * 7, 7 * 7, 6 * 7, 5 * 7, 4 * 7, 3 * 7, 2 * 7, 1 * 7, + 1 * 8, 2 * 8, 3 * 8, 4 * 8, 5 * 8, 6 * 8, 7 * 8, 8 * 8, 8 * 8, 7 * 8, 6 * 8, 5 * 8, 4 * 8, 3 * 8, 2 * 8, 1 * 8, + 1 * 8, 2 * 8, 3 * 8, 4 * 8, 5 * 8, 6 * 8, 7 * 8, 8 * 8, 8 * 8, 7 * 8, 6 * 8, 5 * 8, 4 * 8, 3 * 8, 2 * 8, 1 * 8, + 1 * 7, 2 * 7, 3 * 7, 4 * 7, 5 * 7, 6 * 7, 7 * 7, 8 * 7, 8 * 7, 7 * 7, 6 * 7, 5 * 7, 4 * 7, 3 * 7, 2 * 7, 1 * 7, + 1 * 6, 2 * 6, 3 * 6, 4 * 6, 5 * 6, 6 * 6, 7 * 6, 8 * 6, 8 * 6, 7 * 6, 6 * 6, 5 * 6, 4 * 6, 3 * 6, 2 * 6, 1 * 6, + 1 * 5, 2 * 5, 3 * 5, 4 * 5, 5 * 5, 6 * 5, 7 * 5, 8 * 5, 8 * 5, 7 * 5, 6 * 5, 5 * 5, 4 * 5, 3 * 5, 2 * 5, 1 * 5, + 1 * 4, 2 * 4, 3 * 4, 4 * 4, 5 * 4, 6 * 4, 7 * 4, 8 * 4, 8 * 4, 7 * 4, 6 * 4, 5 * 4, 4 * 4, 3 * 4, 2 * 4, 1 * 4, + 1 * 3, 2 * 3, 3 * 3, 4 * 3, 5 * 3, 6 * 3, 7 * 3, 8 * 3, 8 * 3, 7 * 3, 6 * 3, 5 * 3, 4 * 3, 3 * 3, 2 * 3, 1 * 3, + 1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2, 6 * 2, 7 * 2, 8 * 2, 8 * 2, 7 * 2, 6 * 2, 5 * 2, 4 * 2, 3 * 2, 2 * 2, 1 * 2, + 1 * 1, 2 * 1, 3 * 1, 4 * 1, 5 * 1, 6 * 1, 7 * 1, 8 * 1, 8 * 1, 7 * 1, 6 * 1, 5 * 1, 4 * 1, 3 * 1, 2 * 1, 1 * 1 + }; + } + + DrawParticleColumnPalCommand::DrawParticleColumnPalCommand(uint8_t *dest, int dest_y, int pitch, int count, uint32_t fg, uint32_t alpha, uint32_t fracposx) + { + _dest = dest; + _pitch = pitch; + _count = count; + _fg = fg; + _alpha = alpha; + _fracposx = fracposx; + _dest_y = dest_y; + } + + void DrawParticleColumnPalCommand::Execute(DrawerThread *thread) + { + int count = thread->count_for_thread(_dest_y, _count); + if (count <= 0) + return; + + uint8_t *dest = thread->dest_for_thread(_dest_y, _pitch, _dest); + int pitch = _pitch * thread->num_cores; + + const uint32_t *source = &particle_texture[(_fracposx >> FRACBITS) * 16]; + uint32_t particle_alpha = _alpha; + + uint32_t fracstep = 16 * FRACUNIT / _count; + uint32_t fracpos = fracstep * thread->skipped_by_thread(_dest_y) + fracstep / 2; + fracstep *= thread->num_cores; + + uint32_t fg_red = (_fg >> 16) & 0xff; + uint32_t fg_green = (_fg >> 8) & 0xff; + uint32_t fg_blue = _fg & 0xff; + + for (int y = 0; y < count; y++) + { + uint32_t alpha = (source[fracpos >> FRACBITS] * particle_alpha) >> 6; + uint32_t inv_alpha = 256 - alpha; + + int bg = *dest; + uint32_t bg_red = GPalette.BaseColors[bg].r; + uint32_t bg_green = GPalette.BaseColors[bg].g; + uint32_t bg_blue = GPalette.BaseColors[bg].b; + + uint32_t red = (fg_red * alpha + bg_red * inv_alpha) / 256; + uint32_t green = (fg_green * alpha + bg_green * inv_alpha) / 256; + uint32_t blue = (fg_blue * alpha + bg_blue * inv_alpha) / 256; + + *dest = RGB256k.All[((red >> 2) << 12) | ((green >> 2) << 6) | (blue >> 2)]; + dest += pitch; + fracpos += fracstep; + } + } + + FString DrawParticleColumnPalCommand::DebugInfo() + { + return "DrawParticle"; + } } diff --git a/src/r_draw_pal.h b/src/r_draw_pal.h index ab3c98327..79152665c 100644 --- a/src/r_draw_pal.h +++ b/src/r_draw_pal.h @@ -14,6 +14,8 @@ namespace swrenderer FString DebugInfo() override { return "PalWallCommand"; } protected: + inline static uint8_t AddLights(const TriLight *lights, int num_lights, float viewpos_z, uint8_t fg, uint8_t material); + uint32_t _iscale; uint32_t _texturefrac; uint8_t *_colormap; @@ -24,6 +26,10 @@ namespace swrenderer int _pitch; uint32_t *_srcblend; uint32_t *_destblend; + TriLight *_dynlights; + int _num_dynlights; + float _viewpos_z; + float _step_viewpos_z; }; class PalWall4Command : public DrawerCommand @@ -102,6 +108,8 @@ namespace swrenderer uint32_t *_srcblend; uint32_t *_destblend; uint32_t _srccolor; + fixed_t _srcalpha; + fixed_t _destalpha; }; class DrawColumnPalCommand : public PalColumnCommand { public: void Execute(DrawerThread *thread) override; }; @@ -145,6 +153,8 @@ namespace swrenderer FString DebugInfo() override { return "PalSpanCommand"; } protected: + inline static uint8_t AddLights(const TriLight *lights, int num_lights, float viewpos_x, uint8_t fg, uint8_t material); + const uint8_t *_source; const uint8_t *_colormap; dsfixed_t _xfrac; @@ -160,6 +170,12 @@ namespace swrenderer uint32_t *_srcblend; uint32_t *_destblend; int _color; + fixed_t _srcalpha; + fixed_t _destalpha; + TriLight *_dynlights; + int _num_dynlights; + float _viewpos_x; + float _step_viewpos_x; }; class DrawSpanPalCommand : public PalSpanCommand { public: void Execute(DrawerThread *thread) override; }; @@ -244,86 +260,20 @@ namespace swrenderer const uint8_t *_colormap; uint8_t *_destorg; }; - - class RtInitColsPalCommand : public DrawerCommand + + class DrawParticleColumnPalCommand : public DrawerCommand { public: - RtInitColsPalCommand(uint8_t *buff); + DrawParticleColumnPalCommand(uint8_t *dest, int dest_y, int pitch, int count, uint32_t fg, uint32_t alpha, uint32_t fracposx); void Execute(DrawerThread *thread) override; - FString DebugInfo() override { return "RtInitColsPalCommand"; } - + FString DebugInfo() override; + private: - uint8_t *buff; - }; - - class PalColumnHorizCommand : public DrawerCommand - { - public: - PalColumnHorizCommand(); - - protected: - const uint8_t *_source; - fixed_t _iscale; - fixed_t _texturefrac; - int _count; - int _color; - int _x; - int _yl; - }; - - class DrawColumnHorizPalCommand : public PalColumnHorizCommand - { - public: - void Execute(DrawerThread *thread) override; - FString DebugInfo() override { return "DrawColumnHorizPalCommand"; } - }; - - class FillColumnHorizPalCommand : public PalColumnHorizCommand - { - public: - void Execute(DrawerThread *thread) override; - FString DebugInfo() override { return "FillColumnHorizPalCommand"; } - }; - - class PalRtCommand : public DrawerCommand - { - public: - PalRtCommand(int hx, int sx, int yl, int yh); - FString DebugInfo() override { return "PalRtCommand"; } - - protected: - int hx, sx, yl, yh; - uint8_t *_destorg; + uint8_t *_dest; int _pitch; - const uint8_t *_colormap; - const uint32_t *_srcblend; - const uint32_t *_destblend; - const uint8_t *_translation; - int _color; + int _count; + uint32_t _fg; + uint32_t _alpha; + uint32_t _fracposx; }; - - class DrawColumnRt1CopyPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4CopyPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1PalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4PalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1TranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4TranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1AddPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4AddPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt1AddTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt4AddTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1ShadedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4ShadedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1AddClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4AddClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt1AddClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt4AddClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1SubClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4SubClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt1SubClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt4SubClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt1RevSubClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - class DrawColumnRt4RevSubClampPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt1RevSubClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; - //class DrawColumnRt4RevSubClampTranslatedPalCommand : public PalRtCommand { public: using PalRtCommand::PalRtCommand; void Execute(DrawerThread *thread) override; }; } diff --git a/src/r_draw_rgba.cpp b/src/r_draw_rgba.cpp new file mode 100644 index 000000000..4b5685608 --- /dev/null +++ b/src/r_draw_rgba.cpp @@ -0,0 +1,1206 @@ +// Emacs style mode select -*- C++ -*- +//----------------------------------------------------------------------------- +// +// $Id:$ +// +// Copyright (C) 1993-1996 by id Software, Inc. +// +// This source is available for distribution and/or modification +// only under the terms of the DOOM Source Code License as +// published by id Software. All rights reserved. +// +// The source is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License +// for more details. +// +// $Log:$ +// +// DESCRIPTION: +// True color span/column drawing functions. +// +//----------------------------------------------------------------------------- + +#include + +#include "templates.h" +#include "doomdef.h" +#include "i_system.h" +#include "w_wad.h" +#include "r_local.h" +#include "v_video.h" +#include "doomstat.h" +#include "st_stuff.h" +#include "g_game.h" +#include "g_level.h" +#include "r_data/r_translate.h" +#include "v_palette.h" +#include "r_data/colormaps.h" +#include "r_plane.h" +#include "r_draw_rgba.h" +#include "r_drawers.h" +#include "gl/data/gl_matrix.h" + +#include "gi.h" +#include "stats.h" +#include "x86.h" +#include + +// Use linear filtering when scaling up +CVAR(Bool, r_magfilter, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +// Use linear filtering when scaling down +CVAR(Bool, r_minfilter, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +// Use mipmapped textures +CVAR(Bool, r_mipmap, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); + +// Level of detail texture bias +CVAR(Float, r_lod_bias, -1.5, 0); // To do: add CVAR_ARCHIVE | CVAR_GLOBALCONFIG when a good default has been decided + +namespace swrenderer +{ + extern "C" short spanend[MAXHEIGHT]; + extern float rw_light; + extern float rw_lightstep; + extern int wallshade; + + ///////////////////////////////////////////////////////////////////////////// + + DrawSpanLLVMCommand::DrawSpanLLVMCommand() + { + using namespace drawerargs; + + args.xfrac = ds_xfrac; + args.yfrac = ds_yfrac; + args.xstep = ds_xstep; + args.ystep = ds_ystep; + args.x1 = ds_x1; + args.x2 = ds_x2; + args.y = ds_y; + args.xbits = ds_xbits; + args.ybits = ds_ybits; + args.destorg = (uint32_t*)dc_destorg; + args.destpitch = dc_pitch; + args.source = (const uint32_t*)ds_source; + args.light = LightBgra::calc_light_multiplier(ds_light); + args.light_red = ds_shade_constants.light_red; + args.light_green = ds_shade_constants.light_green; + args.light_blue = ds_shade_constants.light_blue; + args.light_alpha = ds_shade_constants.light_alpha; + args.fade_red = ds_shade_constants.fade_red; + args.fade_green = ds_shade_constants.fade_green; + args.fade_blue = ds_shade_constants.fade_blue; + args.fade_alpha = ds_shade_constants.fade_alpha; + args.desaturate = ds_shade_constants.desaturate; + args.srcalpha = dc_srcalpha >> (FRACBITS - 8); + args.destalpha = dc_destalpha >> (FRACBITS - 8); + args.flags = 0; + if (ds_shade_constants.simple_shade) + args.flags |= DrawSpanArgs::simple_shade; + if (!sampler_setup(args.source, args.xbits, args.ybits, ds_source_mipmapped)) + args.flags |= DrawSpanArgs::nearest_filter; + + args.viewpos_x = dc_viewpos.X; + args.step_viewpos_x = dc_viewpos_step.X; + args.dynlights = dc_lights; + args.num_dynlights = dc_num_lights; + } + + void DrawSpanLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpan(&args); + } + + FString DrawSpanLLVMCommand::DebugInfo() + { + return "DrawSpan\n" + args.ToString(); + } + + bool DrawSpanLLVMCommand::sampler_setup(const uint32_t * &source, int &xbits, int &ybits, bool mipmapped) + { + using namespace drawerargs; + + bool magnifying = ds_lod < 0.0f; + if (r_mipmap && mipmapped) + { + int level = (int)ds_lod; + while (level > 0) + { + if (xbits <= 2 || ybits <= 2) + break; + + source += (1 << (xbits)) * (1 << (ybits)); + xbits -= 1; + ybits -= 1; + level--; + } + } + + return (magnifying && r_magfilter) || (!magnifying && r_minfilter); + } + + ///////////////////////////////////////////////////////////////////////////// + + void DrawSpanMaskedLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpanMasked(&args); + } + + void DrawSpanTranslucentLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpanTranslucent(&args); + } + + void DrawSpanMaskedTranslucentLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpanMaskedTranslucent(&args); + } + + void DrawSpanAddClampLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpanAddClamp(&args); + } + + void DrawSpanMaskedAddClampLLVMCommand::Execute(DrawerThread *thread) + { + if (thread->skipped_by_thread(args.y)) + return; + Drawers::Instance()->DrawSpanMaskedAddClamp(&args); + } + + ///////////////////////////////////////////////////////////////////////////// + + WorkerThreadData DrawWall4LLVMCommand::ThreadData(DrawerThread *thread) + { + WorkerThreadData d; + d.core = thread->core; + d.num_cores = thread->num_cores; + d.pass_start_y = thread->pass_start_y; + d.pass_end_y = thread->pass_end_y; + return d; + } + + DrawWall4LLVMCommand::DrawWall4LLVMCommand() + { + using namespace drawerargs; + + args.dest = (uint32_t*)dc_dest; + args.dest_y = _dest_y; + args.count = dc_count; + args.pitch = dc_pitch; + args.light_red = dc_shade_constants.light_red; + args.light_green = dc_shade_constants.light_green; + args.light_blue = dc_shade_constants.light_blue; + args.light_alpha = dc_shade_constants.light_alpha; + args.fade_red = dc_shade_constants.fade_red; + args.fade_green = dc_shade_constants.fade_green; + args.fade_blue = dc_shade_constants.fade_blue; + args.fade_alpha = dc_shade_constants.fade_alpha; + args.desaturate = dc_shade_constants.desaturate; + for (int i = 0; i < 4; i++) + { + args.texturefrac[i] = dc_wall_texturefrac[i]; + args.iscale[i] = dc_wall_iscale[i]; + args.texturefracx[i] = dc_wall_texturefracx[i]; + args.textureheight[i] = dc_wall_sourceheight[i]; + args.source[i] = (const uint32_t *)dc_wall_source[i]; + args.source2[i] = (const uint32_t *)dc_wall_source2[i]; + args.light[i] = LightBgra::calc_light_multiplier(dc_wall_light[i]); + } + args.srcalpha = dc_srcalpha >> (FRACBITS - 8); + args.destalpha = dc_destalpha >> (FRACBITS - 8); + args.flags = 0; + if (dc_shade_constants.simple_shade) + args.flags |= DrawWallArgs::simple_shade; + if (args.source2[0] == nullptr) + args.flags |= DrawWallArgs::nearest_filter; + + args.z = 0.0f; + args.step_z = 0.0f; + args.dynlights = nullptr; + args.num_dynlights = 0; + + DetectRangeError(args.dest, args.dest_y, args.count); + } + + void DrawWall4LLVMCommand::Execute(DrawerThread *thread) + { + WorkerThreadData d = ThreadData(thread); + Drawers::Instance()->vlinec4(&args, &d); + } + + FString DrawWall4LLVMCommand::DebugInfo() + { + return "DrawWall4\n" + args.ToString(); + } + + ///////////////////////////////////////////////////////////////////////////// + + WorkerThreadData DrawWall1LLVMCommand::ThreadData(DrawerThread *thread) + { + WorkerThreadData d; + d.core = thread->core; + d.num_cores = thread->num_cores; + d.pass_start_y = thread->pass_start_y; + d.pass_end_y = thread->pass_end_y; + return d; + } + + DrawWall1LLVMCommand::DrawWall1LLVMCommand() + { + using namespace drawerargs; + + args.dest = (uint32_t*)dc_dest; + args.dest_y = _dest_y; + args.pitch = dc_pitch; + args.count = dc_count; + args.texturefrac[0] = dc_texturefrac; + args.texturefracx[0] = dc_texturefracx; + args.iscale[0] = dc_iscale; + args.textureheight[0] = dc_textureheight; + args.source[0] = (const uint32 *)dc_source; + args.source2[0] = (const uint32 *)dc_source2; + args.light[0] = LightBgra::calc_light_multiplier(dc_light); + args.light_red = dc_shade_constants.light_red; + args.light_green = dc_shade_constants.light_green; + args.light_blue = dc_shade_constants.light_blue; + args.light_alpha = dc_shade_constants.light_alpha; + args.fade_red = dc_shade_constants.fade_red; + args.fade_green = dc_shade_constants.fade_green; + args.fade_blue = dc_shade_constants.fade_blue; + args.fade_alpha = dc_shade_constants.fade_alpha; + args.desaturate = dc_shade_constants.desaturate; + args.srcalpha = dc_srcalpha >> (FRACBITS - 8); + args.destalpha = dc_destalpha >> (FRACBITS - 8); + args.flags = 0; + if (dc_shade_constants.simple_shade) + args.flags |= DrawWallArgs::simple_shade; + if (args.source2[0] == nullptr) + args.flags |= DrawWallArgs::nearest_filter; + + args.z = dc_viewpos.Z; + args.step_z = dc_viewpos_step.Z; + args.dynlights = dc_lights; + args.num_dynlights = dc_num_lights; + + DetectRangeError(args.dest, args.dest_y, args.count); + } + + void DrawWall1LLVMCommand::Execute(DrawerThread *thread) + { + WorkerThreadData d = ThreadData(thread); + Drawers::Instance()->vlinec1(&args, &d); + } + + FString DrawWall1LLVMCommand::DebugInfo() + { + return "DrawWall1\n" + args.ToString(); + } + + ///////////////////////////////////////////////////////////////////////////// + + WorkerThreadData DrawColumnLLVMCommand::ThreadData(DrawerThread *thread) + { + WorkerThreadData d; + d.core = thread->core; + d.num_cores = thread->num_cores; + d.pass_start_y = thread->pass_start_y; + d.pass_end_y = thread->pass_end_y; + return d; + } + + FString DrawColumnLLVMCommand::DebugInfo() + { + return "DrawColumn\n" + args.ToString(); + } + + DrawColumnLLVMCommand::DrawColumnLLVMCommand() + { + using namespace drawerargs; + + args.dest = (uint32_t*)dc_dest; + args.source = dc_source; + args.source2 = dc_source2; + args.colormap = dc_colormap; + args.translation = dc_translation; + args.basecolors = (const uint32_t *)GPalette.BaseColors; + args.pitch = dc_pitch; + args.count = dc_count; + args.dest_y = _dest_y; + args.iscale = dc_iscale; + args.texturefracx = dc_texturefracx; + args.textureheight = dc_textureheight; + args.texturefrac = dc_texturefrac; + args.light = LightBgra::calc_light_multiplier(dc_light); + args.color = LightBgra::shade_pal_index_simple(dc_color, args.light); + args.srccolor = dc_srccolor_bgra; + args.srcalpha = dc_srcalpha >> (FRACBITS - 8); + args.destalpha = dc_destalpha >> (FRACBITS - 8); + args.light_red = dc_shade_constants.light_red; + args.light_green = dc_shade_constants.light_green; + args.light_blue = dc_shade_constants.light_blue; + args.light_alpha = dc_shade_constants.light_alpha; + args.fade_red = dc_shade_constants.fade_red; + args.fade_green = dc_shade_constants.fade_green; + args.fade_blue = dc_shade_constants.fade_blue; + args.fade_alpha = dc_shade_constants.fade_alpha; + args.desaturate = dc_shade_constants.desaturate; + args.flags = 0; + if (dc_shade_constants.simple_shade) + args.flags |= DrawColumnArgs::simple_shade; + if (args.source2 == nullptr) + args.flags |= DrawColumnArgs::nearest_filter; + + DetectRangeError(args.dest, args.dest_y, args.count); + } + + void DrawColumnLLVMCommand::Execute(DrawerThread *thread) + { + WorkerThreadData d = ThreadData(thread); + Drawers::Instance()->DrawColumn(&args, &d); + } + + ///////////////////////////////////////////////////////////////////////////// + + WorkerThreadData DrawSkyLLVMCommand::ThreadData(DrawerThread *thread) + { + WorkerThreadData d; + d.core = thread->core; + d.num_cores = thread->num_cores; + d.pass_start_y = thread->pass_start_y; + d.pass_end_y = thread->pass_end_y; + return d; + } + + DrawSkyLLVMCommand::DrawSkyLLVMCommand(uint32_t solid_top, uint32_t solid_bottom) + { + using namespace drawerargs; + + args.dest = (uint32_t*)dc_dest; + args.dest_y = _dest_y; + args.count = dc_count; + args.pitch = dc_pitch; + for (int i = 0; i < 4; i++) + { + args.texturefrac[i] = dc_wall_texturefrac[i]; + args.iscale[i] = dc_wall_iscale[i]; + args.source0[i] = (const uint32_t *)dc_wall_source[i]; + args.source1[i] = (const uint32_t *)dc_wall_source2[i]; + } + args.textureheight0 = dc_wall_sourceheight[0]; + args.textureheight1 = dc_wall_sourceheight[1]; + args.top_color = solid_top; + args.bottom_color = solid_bottom; + + DetectRangeError(args.dest, args.dest_y, args.count); + } + + FString DrawSkyLLVMCommand::DebugInfo() + { + return "DrawSky\n" + args.ToString(); + } + + ///////////////////////////////////////////////////////////////////////////// + + DrawFuzzColumnRGBACommand::DrawFuzzColumnRGBACommand() + { + using namespace drawerargs; + + _x = dc_x; + _yl = dc_yl; + _yh = dc_yh; + _destorg = dc_destorg; + _pitch = dc_pitch; + _fuzzpos = fuzzpos; + _fuzzviewheight = fuzzviewheight; + } + + void DrawFuzzColumnRGBACommand::Execute(DrawerThread *thread) + { + int yl = MAX(_yl, 1); + int yh = MIN(_yh, _fuzzviewheight); + + int count = thread->count_for_thread(yl, yh - yl + 1); + + // Zero length. + if (count <= 0) + return; + + uint32_t *dest = thread->dest_for_thread(yl, _pitch, ylookup[yl] + _x + (uint32_t*)_destorg); + + int pitch = _pitch * thread->num_cores; + int fuzzstep = thread->num_cores; + int fuzz = (_fuzzpos + thread->skipped_by_thread(yl)) % FUZZTABLE; + + yl += thread->skipped_by_thread(yl); + + // Handle the case where we would go out of bounds at the top: + if (yl < fuzzstep) + { + uint32_t *srcdest = dest + fuzzoffset[fuzz] * fuzzstep + pitch; + //assert(static_cast((srcdest - (uint32_t*)dc_destorg) / (_pitch)) < viewheight); + + uint32_t bg = *srcdest; + + uint32_t red = RPART(bg) * 3 / 4; + uint32_t green = GPART(bg) * 3 / 4; + uint32_t blue = BPART(bg) * 3 / 4; + + *dest = 0xff000000 | (red << 16) | (green << 8) | blue; + dest += pitch; + fuzz += fuzzstep; + fuzz %= FUZZTABLE; + + count--; + if (count == 0) + return; + } + + bool lowerbounds = (yl + (count + fuzzstep - 1) * fuzzstep > _fuzzviewheight); + if (lowerbounds) + count--; + + // Fuzz where fuzzoffset stays within bounds + while (count > 0) + { + int available = (FUZZTABLE - fuzz); + int next_wrap = available / fuzzstep; + if (available % fuzzstep != 0) + next_wrap++; + + int cnt = MIN(count, next_wrap); + count -= cnt; + do + { + uint32_t *srcdest = dest + fuzzoffset[fuzz] * fuzzstep; + //assert(static_cast((srcdest - (uint32_t*)dc_destorg) / (_pitch)) < viewheight); + + uint32_t bg = *srcdest; + + uint32_t red = RPART(bg) * 3 / 4; + uint32_t green = GPART(bg) * 3 / 4; + uint32_t blue = BPART(bg) * 3 / 4; + + *dest = 0xff000000 | (red << 16) | (green << 8) | blue; + dest += pitch; + fuzz += fuzzstep; + } while (--cnt); + + fuzz %= FUZZTABLE; + } + + // Handle the case where we would go out of bounds at the bottom + if (lowerbounds) + { + uint32_t *srcdest = dest + fuzzoffset[fuzz] * fuzzstep - pitch; + //assert(static_cast((srcdest - (uint32_t*)dc_destorg) / (_pitch)) < viewheight); + + uint32_t bg = *srcdest; + + uint32_t red = RPART(bg) * 3 / 4; + uint32_t green = GPART(bg) * 3 / 4; + uint32_t blue = BPART(bg) * 3 / 4; + + *dest = 0xff000000 | (red << 16) | (green << 8) | blue; + } + } + + FString DrawFuzzColumnRGBACommand::DebugInfo() + { + return "DrawFuzzColumn"; + } + + ///////////////////////////////////////////////////////////////////////////// + + FillSpanRGBACommand::FillSpanRGBACommand() + { + using namespace drawerargs; + + _x1 = ds_x1; + _x2 = ds_x2; + _y = ds_y; + _destorg = dc_destorg; + _light = ds_light; + _color = ds_color; + } + + void FillSpanRGBACommand::Execute(DrawerThread *thread) + { + if (thread->line_skipped_by_thread(_y)) + return; + + uint32_t *dest = ylookup[_y] + _x1 + (uint32_t*)_destorg; + int count = (_x2 - _x1 + 1); + uint32_t light = LightBgra::calc_light_multiplier(_light); + uint32_t color = LightBgra::shade_pal_index_simple(_color, light); + for (int i = 0; i < count; i++) + dest[i] = color; + } + + FString FillSpanRGBACommand::DebugInfo() + { + return "FillSpan"; + } + + ///////////////////////////////////////////////////////////////////////////// + + DrawSlabRGBACommand::DrawSlabRGBACommand(int dx, fixed_t v, int dy, fixed_t vi, const uint8_t *vptr, uint8_t *p, ShadeConstants shade_constants, const uint8_t *colormap, fixed_t light) + { + using namespace drawerargs; + + _dx = dx; + _v = v; + _dy = dy; + _vi = vi; + _voxelptr = vptr; + _p = (uint32_t *)p; + _shade_constants = shade_constants; + _colormap = colormap; + _light = light; + _pitch = dc_pitch; + _start_y = static_cast((p - dc_destorg) / (dc_pitch * 4)); + assert(dx > 0); + } + + void DrawSlabRGBACommand::Execute(DrawerThread *thread) + { + int dx = _dx; + fixed_t v = _v; + int dy = _dy; + fixed_t vi = _vi; + const uint8_t *vptr = _voxelptr; + uint32_t *p = _p; + ShadeConstants shade_constants = _shade_constants; + const uint8_t *colormap = _colormap; + uint32_t light = LightBgra::calc_light_multiplier(_light); + int pitch = _pitch; + int x; + + dy = thread->count_for_thread(_start_y, dy); + p = thread->dest_for_thread(_start_y, pitch, p); + v += vi * thread->skipped_by_thread(_start_y); + vi *= thread->num_cores; + pitch *= thread->num_cores; + + if (dx == 1) + { + while (dy > 0) + { + *p = LightBgra::shade_pal_index(colormap[vptr[v >> FRACBITS]], light, shade_constants); + p += pitch; + v += vi; + dy--; + } + } + else if (dx == 2) + { + while (dy > 0) + { + uint32_t color = LightBgra::shade_pal_index(colormap[vptr[v >> FRACBITS]], light, shade_constants); + p[0] = color; + p[1] = color; + p += pitch; + v += vi; + dy--; + } + } + else if (dx == 3) + { + while (dy > 0) + { + uint32_t color = LightBgra::shade_pal_index(colormap[vptr[v >> FRACBITS]], light, shade_constants); + p[0] = color; + p[1] = color; + p[2] = color; + p += pitch; + v += vi; + dy--; + } + } + else if (dx == 4) + { + while (dy > 0) + { + uint32_t color = LightBgra::shade_pal_index(colormap[vptr[v >> FRACBITS]], light, shade_constants); + p[0] = color; + p[1] = color; + p[2] = color; + p[3] = color; + p += pitch; + v += vi; + dy--; + } + } + else while (dy > 0) + { + uint32_t color = LightBgra::shade_pal_index(colormap[vptr[v >> FRACBITS]], light, shade_constants); + // The optimizer will probably turn this into a memset call. + // Since dx is not likely to be large, I'm not sure that's a good thing, + // hence the alternatives above. + for (x = 0; x < dx; x++) + { + p[x] = color; + } + p += pitch; + v += vi; + dy--; + } + } + + FString DrawSlabRGBACommand::DebugInfo() + { + return "DrawSlab"; + } + + ///////////////////////////////////////////////////////////////////////////// + + DrawFogBoundaryLineRGBACommand::DrawFogBoundaryLineRGBACommand(int y, int x, int x2) + { + using namespace drawerargs; + + _y = y; + _x = x; + _x2 = x2; + + _destorg = dc_destorg; + _light = dc_light; + _shade_constants = dc_shade_constants; + } + + void DrawFogBoundaryLineRGBACommand::Execute(DrawerThread *thread) + { + if (thread->line_skipped_by_thread(_y)) + return; + + int y = _y; + int x = _x; + int x2 = _x2; + + uint32_t *dest = ylookup[y] + (uint32_t*)_destorg; + + uint32_t light = LightBgra::calc_light_multiplier(_light); + ShadeConstants constants = _shade_constants; + + do + { + uint32_t red = (dest[x] >> 16) & 0xff; + uint32_t green = (dest[x] >> 8) & 0xff; + uint32_t blue = dest[x] & 0xff; + + if (constants.simple_shade) + { + red = red * light / 256; + green = green * light / 256; + blue = blue * light / 256; + } + else + { + uint32_t inv_light = 256 - light; + uint32_t inv_desaturate = 256 - constants.desaturate; + + uint32_t intensity = ((red * 77 + green * 143 + blue * 37) >> 8) * constants.desaturate; + + red = (red * inv_desaturate + intensity) / 256; + green = (green * inv_desaturate + intensity) / 256; + blue = (blue * inv_desaturate + intensity) / 256; + + red = (constants.fade_red * inv_light + red * light) / 256; + green = (constants.fade_green * inv_light + green * light) / 256; + blue = (constants.fade_blue * inv_light + blue * light) / 256; + + red = (red * constants.light_red) / 256; + green = (green * constants.light_green) / 256; + blue = (blue * constants.light_blue) / 256; + } + + dest[x] = 0xff000000 | (red << 16) | (green << 8) | blue; + } while (++x <= x2); + } + + FString DrawFogBoundaryLineRGBACommand::DebugInfo() + { + return "DrawFogBoundaryLine"; + } + + ///////////////////////////////////////////////////////////////////////////// + + DrawTiltedSpanRGBACommand::DrawTiltedSpanRGBACommand(int y, int x1, int x2, const FVector3 &plane_sz, const FVector3 &plane_su, const FVector3 &plane_sv, bool plane_shade, int planeshade, float planelightfloat, fixed_t pviewx, fixed_t pviewy) + { + using namespace drawerargs; + + _x1 = x1; + _x2 = x2; + _y = y; + _destorg = dc_destorg; + _light = ds_light; + _shade_constants = ds_shade_constants; + _plane_sz = plane_sz; + _plane_su = plane_su; + _plane_sv = plane_sv; + _plane_shade = plane_shade; + _planeshade = planeshade; + _planelightfloat = planelightfloat; + _pviewx = pviewx; + _pviewy = pviewy; + _source = (const uint32_t*)ds_source; + _xbits = ds_xbits; + _ybits = ds_ybits; + } + + void DrawTiltedSpanRGBACommand::Execute(DrawerThread *thread) + { + if (thread->line_skipped_by_thread(_y)) + return; + + //#define SPANSIZE 32 + //#define INVSPAN 0.03125f + //#define SPANSIZE 8 + //#define INVSPAN 0.125f + #define SPANSIZE 16 + #define INVSPAN 0.0625f + + int source_width = 1 << _xbits; + int source_height = 1 << _ybits; + + uint32_t *dest = ylookup[_y] + _x1 + (uint32_t*)_destorg; + int count = _x2 - _x1 + 1; + + // Depth (Z) change across the span + double iz = _plane_sz[2] + _plane_sz[1] * (centery - _y) + _plane_sz[0] * (_x1 - centerx); + + // Light change across the span + fixed_t lightstart = _light; + fixed_t lightend = lightstart; + if (_plane_shade) + { + double vis_start = iz * _planelightfloat; + double vis_end = (iz + _plane_sz[0] * count) * _planelightfloat; + + lightstart = LIGHTSCALE(vis_start, _planeshade); + lightend = LIGHTSCALE(vis_end, _planeshade); + } + fixed_t light = lightstart; + fixed_t steplight = (lightend - lightstart) / count; + + // Texture coordinates + double uz = _plane_su[2] + _plane_su[1] * (centery - _y) + _plane_su[0] * (_x1 - centerx); + double vz = _plane_sv[2] + _plane_sv[1] * (centery - _y) + _plane_sv[0] * (_x1 - centerx); + double startz = 1.f / iz; + double startu = uz*startz; + double startv = vz*startz; + double izstep = _plane_sz[0] * SPANSIZE; + double uzstep = _plane_su[0] * SPANSIZE; + double vzstep = _plane_sv[0] * SPANSIZE; + + // Linear interpolate in sizes of SPANSIZE to increase speed + while (count >= SPANSIZE) + { + iz += izstep; + uz += uzstep; + vz += vzstep; + + double endz = 1.f / iz; + double endu = uz*endz; + double endv = vz*endz; + uint32_t stepu = (uint32_t)(SQWORD((endu - startu) * INVSPAN)); + uint32_t stepv = (uint32_t)(SQWORD((endv - startv) * INVSPAN)); + uint32_t u = (uint32_t)(SQWORD(startu) + _pviewx); + uint32_t v = (uint32_t)(SQWORD(startv) + _pviewy); + + for (int i = 0; i < SPANSIZE; i++) + { + uint32_t sx = ((u >> 16) * source_width) >> 16; + uint32_t sy = ((v >> 16) * source_height) >> 16; + uint32_t fg = _source[sy + sx * source_height]; + + if (_shade_constants.simple_shade) + *(dest++) = LightBgra::shade_bgra_simple(fg, LightBgra::calc_light_multiplier(light)); + else + *(dest++) = LightBgra::shade_bgra(fg, LightBgra::calc_light_multiplier(light), _shade_constants); + + u += stepu; + v += stepv; + light += steplight; + } + startu = endu; + startv = endv; + count -= SPANSIZE; + } + + // The last few pixels at the end + while (count > 0) + { + double endz = 1.f / iz; + startu = uz*endz; + startv = vz*endz; + uint32_t u = (uint32_t)(SQWORD(startu) + _pviewx); + uint32_t v = (uint32_t)(SQWORD(startv) + _pviewy); + + uint32_t sx = ((u >> 16) * source_width) >> 16; + uint32_t sy = ((v >> 16) * source_height) >> 16; + uint32_t fg = _source[sy + sx * source_height]; + + if (_shade_constants.simple_shade) + *(dest++) = LightBgra::shade_bgra_simple(fg, LightBgra::calc_light_multiplier(light)); + else + *(dest++) = LightBgra::shade_bgra(fg, LightBgra::calc_light_multiplier(light), _shade_constants); + + iz += _plane_sz[0]; + uz += _plane_su[0]; + vz += _plane_sv[0]; + light += steplight; + count--; + } + } + + FString DrawTiltedSpanRGBACommand::DebugInfo() + { + return "DrawTiltedSpan"; + } + + ///////////////////////////////////////////////////////////////////////////// + + DrawColoredSpanRGBACommand::DrawColoredSpanRGBACommand(int y, int x1, int x2) + { + using namespace drawerargs; + + _y = y; + _x1 = x1; + _x2 = x2; + + _destorg = dc_destorg; + _light = ds_light; + _color = ds_color; + } + + void DrawColoredSpanRGBACommand::Execute(DrawerThread *thread) + { + if (thread->line_skipped_by_thread(_y)) + return; + + int y = _y; + int x1 = _x1; + int x2 = _x2; + + uint32_t *dest = ylookup[y] + x1 + (uint32_t*)_destorg; + int count = (x2 - x1 + 1); + uint32_t light = LightBgra::calc_light_multiplier(_light); + uint32_t color = LightBgra::shade_pal_index_simple(_color, light); + for (int i = 0; i < count; i++) + dest[i] = color; + } + + FString DrawColoredSpanRGBACommand::DebugInfo() + { + return "DrawColoredSpan"; + } + + ///////////////////////////////////////////////////////////////////////////// + + FillTransColumnRGBACommand::FillTransColumnRGBACommand(int x, int y1, int y2, int color, int a) + { + using namespace drawerargs; + + _x = x; + _y1 = y1; + _y2 = y2; + _color = color; + _a = a; + + _destorg = dc_destorg; + _pitch = dc_pitch; + } + + void FillTransColumnRGBACommand::Execute(DrawerThread *thread) + { + int x = _x; + int y1 = _y1; + int y2 = _y2; + int color = _color; + int a = _a; + + int ycount = thread->count_for_thread(y1, y2 - y1 + 1); + if (ycount <= 0) + return; + + uint32_t fg = GPalette.BaseColors[color].d; + uint32_t fg_red = (fg >> 16) & 0xff; + uint32_t fg_green = (fg >> 8) & 0xff; + uint32_t fg_blue = fg & 0xff; + + uint32_t alpha = a + 1; + uint32_t inv_alpha = 256 - alpha; + + fg_red *= alpha; + fg_green *= alpha; + fg_blue *= alpha; + + int spacing = _pitch * thread->num_cores; + uint32_t *dest = thread->dest_for_thread(y1, _pitch, ylookup[y1] + x + (uint32_t*)_destorg); + + for (int y = 0; y < ycount; y++) + { + uint32_t bg_red = (*dest >> 16) & 0xff; + uint32_t bg_green = (*dest >> 8) & 0xff; + uint32_t bg_blue = (*dest) & 0xff; + + uint32_t red = (fg_red + bg_red * inv_alpha) / 256; + uint32_t green = (fg_green + bg_green * inv_alpha) / 256; + uint32_t blue = (fg_blue + bg_blue * inv_alpha) / 256; + + *dest = 0xff000000 | (red << 16) | (green << 8) | blue; + dest += spacing; + } + } + + FString FillTransColumnRGBACommand::DebugInfo() + { + return "FillTransColumn"; + } + + ///////////////////////////////////////////////////////////////////////////// + + ApplySpecialColormapRGBACommand::ApplySpecialColormapRGBACommand(FSpecialColormap *colormap, DFrameBuffer *screen) + { + buffer = screen->GetBuffer(); + pitch = screen->GetPitch(); + width = screen->GetWidth(); + height = screen->GetHeight(); + + start_red = (int)(colormap->ColorizeStart[0] * 255); + start_green = (int)(colormap->ColorizeStart[1] * 255); + start_blue = (int)(colormap->ColorizeStart[2] * 255); + end_red = (int)(colormap->ColorizeEnd[0] * 255); + end_green = (int)(colormap->ColorizeEnd[1] * 255); + end_blue = (int)(colormap->ColorizeEnd[2] * 255); + } + +#ifdef NO_SSE + void ApplySpecialColormapRGBACommand::Execute(DrawerThread *thread) + { + int y = thread->skipped_by_thread(0); + int count = thread->count_for_thread(0, height); + while (count > 0) + { + uint8_t *pixels = buffer + y * pitch * 4; + for (int x = 0; x < width; x++) + { + int fg_red = pixels[2]; + int fg_green = pixels[1]; + int fg_blue = pixels[0]; + + int gray = (fg_red * 77 + fg_green * 143 + fg_blue * 37) >> 8; + gray += (gray >> 7); // gray*=256/255 + int inv_gray = 256 - gray; + + int red = clamp((start_red * inv_gray + end_red * gray) >> 8, 0, 255); + int green = clamp((start_green * inv_gray + end_green * gray) >> 8, 0, 255); + int blue = clamp((start_blue * inv_gray + end_blue * gray) >> 8, 0, 255); + + pixels[0] = (uint8_t)blue; + pixels[1] = (uint8_t)green; + pixels[2] = (uint8_t)red; + pixels[3] = 0xff; + + pixels += 4; + } + y += thread->num_cores; + count--; + } + } +#else + void ApplySpecialColormapRGBACommand::Execute(DrawerThread *thread) + { + int y = thread->skipped_by_thread(0); + int count = thread->count_for_thread(0, height); + __m128i gray_weight = _mm_set_epi16(256, 77, 143, 37, 256, 77, 143, 37); + __m128i start_end = _mm_set_epi16(255, start_red, start_green, start_blue, 255, end_red, end_green, end_blue); + while (count > 0) + { + uint8_t *pixels = buffer + y * pitch * 4; + int sse_length = width / 4; + for (int x = 0; x < sse_length; x++) + { + // Unpack to integers: + __m128i p = _mm_loadu_si128((const __m128i*)pixels); + + __m128i p16_0 = _mm_unpacklo_epi8(p, _mm_setzero_si128()); + __m128i p16_1 = _mm_unpackhi_epi8(p, _mm_setzero_si128()); + + // Add gray weighting to colors + __m128i mullo0 = _mm_mullo_epi16(p16_0, gray_weight); + __m128i mullo1 = _mm_mullo_epi16(p16_1, gray_weight); + __m128i p32_0 = _mm_unpacklo_epi16(mullo0, _mm_setzero_si128()); + __m128i p32_1 = _mm_unpackhi_epi16(mullo0, _mm_setzero_si128()); + __m128i p32_2 = _mm_unpacklo_epi16(mullo1, _mm_setzero_si128()); + __m128i p32_3 = _mm_unpackhi_epi16(mullo1, _mm_setzero_si128()); + + // Transpose to get color components in individual vectors: + __m128 tmpx = _mm_castsi128_ps(p32_0); + __m128 tmpy = _mm_castsi128_ps(p32_1); + __m128 tmpz = _mm_castsi128_ps(p32_2); + __m128 tmpw = _mm_castsi128_ps(p32_3); + _MM_TRANSPOSE4_PS(tmpx, tmpy, tmpz, tmpw); + __m128i blue = _mm_castps_si128(tmpx); + __m128i green = _mm_castps_si128(tmpy); + __m128i red = _mm_castps_si128(tmpz); + __m128i alpha = _mm_castps_si128(tmpw); + + // Calculate gray and 256-gray values: + __m128i gray = _mm_srli_epi32(_mm_add_epi32(_mm_add_epi32(red, green), blue), 8); + __m128i inv_gray = _mm_sub_epi32(_mm_set1_epi32(256), gray); + + // p32 = start * inv_gray + end * gray: + __m128i gray0 = _mm_shuffle_epi32(gray, _MM_SHUFFLE(0, 0, 0, 0)); + __m128i gray1 = _mm_shuffle_epi32(gray, _MM_SHUFFLE(1, 1, 1, 1)); + __m128i gray2 = _mm_shuffle_epi32(gray, _MM_SHUFFLE(2, 2, 2, 2)); + __m128i gray3 = _mm_shuffle_epi32(gray, _MM_SHUFFLE(3, 3, 3, 3)); + __m128i inv_gray0 = _mm_shuffle_epi32(inv_gray, _MM_SHUFFLE(0, 0, 0, 0)); + __m128i inv_gray1 = _mm_shuffle_epi32(inv_gray, _MM_SHUFFLE(1, 1, 1, 1)); + __m128i inv_gray2 = _mm_shuffle_epi32(inv_gray, _MM_SHUFFLE(2, 2, 2, 2)); + __m128i inv_gray3 = _mm_shuffle_epi32(inv_gray, _MM_SHUFFLE(3, 3, 3, 3)); + __m128i gray16_0 = _mm_packs_epi32(gray0, inv_gray0); + __m128i gray16_1 = _mm_packs_epi32(gray1, inv_gray1); + __m128i gray16_2 = _mm_packs_epi32(gray2, inv_gray2); + __m128i gray16_3 = _mm_packs_epi32(gray3, inv_gray3); + __m128i gray16_0_mullo = _mm_mullo_epi16(gray16_0, start_end); + __m128i gray16_1_mullo = _mm_mullo_epi16(gray16_1, start_end); + __m128i gray16_2_mullo = _mm_mullo_epi16(gray16_2, start_end); + __m128i gray16_3_mullo = _mm_mullo_epi16(gray16_3, start_end); + __m128i gray16_0_mulhi = _mm_mulhi_epi16(gray16_0, start_end); + __m128i gray16_1_mulhi = _mm_mulhi_epi16(gray16_1, start_end); + __m128i gray16_2_mulhi = _mm_mulhi_epi16(gray16_2, start_end); + __m128i gray16_3_mulhi = _mm_mulhi_epi16(gray16_3, start_end); + p32_0 = _mm_srli_epi32(_mm_add_epi32(_mm_unpacklo_epi16(gray16_0_mullo, gray16_0_mulhi), _mm_unpackhi_epi16(gray16_0_mullo, gray16_0_mulhi)), 8); + p32_1 = _mm_srli_epi32(_mm_add_epi32(_mm_unpacklo_epi16(gray16_1_mullo, gray16_1_mulhi), _mm_unpackhi_epi16(gray16_1_mullo, gray16_1_mulhi)), 8); + p32_2 = _mm_srli_epi32(_mm_add_epi32(_mm_unpacklo_epi16(gray16_2_mullo, gray16_2_mulhi), _mm_unpackhi_epi16(gray16_2_mullo, gray16_2_mulhi)), 8); + p32_3 = _mm_srli_epi32(_mm_add_epi32(_mm_unpacklo_epi16(gray16_3_mullo, gray16_3_mulhi), _mm_unpackhi_epi16(gray16_3_mullo, gray16_3_mulhi)), 8); + + p16_0 = _mm_packs_epi32(p32_0, p32_1); + p16_1 = _mm_packs_epi32(p32_2, p32_3); + p = _mm_packus_epi16(p16_0, p16_1); + + _mm_storeu_si128((__m128i*)pixels, p); + pixels += 16; + } + + for (int x = sse_length * 4; x < width; x++) + { + int fg_red = pixels[2]; + int fg_green = pixels[1]; + int fg_blue = pixels[0]; + + int gray = (fg_red * 77 + fg_green * 143 + fg_blue * 37) >> 8; + gray += (gray >> 7); // gray*=256/255 + int inv_gray = 256 - gray; + + int red = clamp((start_red * inv_gray + end_red * gray) >> 8, 0, 255); + int green = clamp((start_green * inv_gray + end_green * gray) >> 8, 0, 255); + int blue = clamp((start_blue * inv_gray + end_blue * gray) >> 8, 0, 255); + + pixels[0] = (uint8_t)blue; + pixels[1] = (uint8_t)green; + pixels[2] = (uint8_t)red; + pixels[3] = 0xff; + + pixels += 4; + } + + y += thread->num_cores; + count--; + } + } +#endif + + ///////////////////////////////////////////////////////////////////////////// + + namespace + { + static uint32_t particle_texture[16 * 16] = + { + 1 * 1, 2 * 1, 3 * 1, 4 * 1, 5 * 1, 6 * 1, 7 * 1, 8 * 1, 8 * 1, 7 * 1, 6 * 1, 5 * 1, 4 * 1, 3 * 1, 2 * 1, 1 * 1, + 1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2, 6 * 2, 7 * 2, 8 * 2, 8 * 2, 7 * 2, 6 * 2, 5 * 2, 4 * 2, 3 * 2, 2 * 2, 1 * 2, + 1 * 3, 2 * 3, 3 * 3, 4 * 3, 5 * 3, 6 * 3, 7 * 3, 8 * 3, 8 * 3, 7 * 3, 6 * 3, 5 * 3, 4 * 3, 3 * 3, 2 * 3, 1 * 3, + 1 * 4, 2 * 4, 3 * 4, 4 * 4, 5 * 4, 6 * 4, 7 * 4, 8 * 4, 8 * 4, 7 * 4, 6 * 4, 5 * 4, 4 * 4, 3 * 4, 2 * 4, 1 * 4, + 1 * 5, 2 * 5, 3 * 5, 4 * 5, 5 * 5, 6 * 5, 7 * 5, 8 * 5, 8 * 5, 7 * 5, 6 * 5, 5 * 5, 4 * 5, 3 * 5, 2 * 5, 1 * 5, + 1 * 6, 2 * 6, 3 * 6, 4 * 6, 5 * 6, 6 * 6, 7 * 6, 8 * 6, 8 * 6, 7 * 6, 6 * 6, 5 * 6, 4 * 6, 3 * 6, 2 * 6, 1 * 6, + 1 * 7, 2 * 7, 3 * 7, 4 * 7, 5 * 7, 6 * 7, 7 * 7, 8 * 7, 8 * 7, 7 * 7, 6 * 7, 5 * 7, 4 * 7, 3 * 7, 2 * 7, 1 * 7, + 1 * 8, 2 * 8, 3 * 8, 4 * 8, 5 * 8, 6 * 8, 7 * 8, 8 * 8, 8 * 8, 7 * 8, 6 * 8, 5 * 8, 4 * 8, 3 * 8, 2 * 8, 1 * 8, + 1 * 8, 2 * 8, 3 * 8, 4 * 8, 5 * 8, 6 * 8, 7 * 8, 8 * 8, 8 * 8, 7 * 8, 6 * 8, 5 * 8, 4 * 8, 3 * 8, 2 * 8, 1 * 8, + 1 * 7, 2 * 7, 3 * 7, 4 * 7, 5 * 7, 6 * 7, 7 * 7, 8 * 7, 8 * 7, 7 * 7, 6 * 7, 5 * 7, 4 * 7, 3 * 7, 2 * 7, 1 * 7, + 1 * 6, 2 * 6, 3 * 6, 4 * 6, 5 * 6, 6 * 6, 7 * 6, 8 * 6, 8 * 6, 7 * 6, 6 * 6, 5 * 6, 4 * 6, 3 * 6, 2 * 6, 1 * 6, + 1 * 5, 2 * 5, 3 * 5, 4 * 5, 5 * 5, 6 * 5, 7 * 5, 8 * 5, 8 * 5, 7 * 5, 6 * 5, 5 * 5, 4 * 5, 3 * 5, 2 * 5, 1 * 5, + 1 * 4, 2 * 4, 3 * 4, 4 * 4, 5 * 4, 6 * 4, 7 * 4, 8 * 4, 8 * 4, 7 * 4, 6 * 4, 5 * 4, 4 * 4, 3 * 4, 2 * 4, 1 * 4, + 1 * 3, 2 * 3, 3 * 3, 4 * 3, 5 * 3, 6 * 3, 7 * 3, 8 * 3, 8 * 3, 7 * 3, 6 * 3, 5 * 3, 4 * 3, 3 * 3, 2 * 3, 1 * 3, + 1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2, 6 * 2, 7 * 2, 8 * 2, 8 * 2, 7 * 2, 6 * 2, 5 * 2, 4 * 2, 3 * 2, 2 * 2, 1 * 2, + 1 * 1, 2 * 1, 3 * 1, 4 * 1, 5 * 1, 6 * 1, 7 * 1, 8 * 1, 8 * 1, 7 * 1, 6 * 1, 5 * 1, 4 * 1, 3 * 1, 2 * 1, 1 * 1 + }; + } + + DrawParticleColumnRGBACommand::DrawParticleColumnRGBACommand(uint32_t *dest, int dest_y, int pitch, int count, uint32_t fg, uint32_t alpha, uint32_t fracposx) + { + _dest = dest; + _pitch = pitch; + _count = count; + _fg = fg; + _alpha = alpha; + _fracposx = fracposx; + _dest_y = dest_y; + } + + void DrawParticleColumnRGBACommand::Execute(DrawerThread *thread) + { + int count = thread->count_for_thread(_dest_y, _count); + if (count <= 0) + return; + + uint32_t *dest = thread->dest_for_thread(_dest_y, _pitch, _dest); + int pitch = _pitch * thread->num_cores; + + const uint32_t *source = &particle_texture[(_fracposx >> FRACBITS) * 16]; + uint32_t particle_alpha = _alpha; + + uint32_t fracstep = 16 * FRACUNIT / _count; + uint32_t fracpos = fracstep * thread->skipped_by_thread(_dest_y) + fracstep / 2; + fracstep *= thread->num_cores; + + uint32_t fg_red = (_fg >> 16) & 0xff; + uint32_t fg_green = (_fg >> 8) & 0xff; + uint32_t fg_blue = _fg & 0xff; + + for (int y = 0; y < count; y++) + { + uint32_t alpha = (source[fracpos >> FRACBITS] * particle_alpha) >> 6; + uint32_t inv_alpha = 256 - alpha; + + uint32_t bg_red = (*dest >> 16) & 0xff; + uint32_t bg_green = (*dest >> 8) & 0xff; + uint32_t bg_blue = (*dest) & 0xff; + + uint32_t red = (fg_red * alpha + bg_red * inv_alpha) / 256; + uint32_t green = (fg_green * alpha + bg_green * inv_alpha) / 256; + uint32_t blue = (fg_blue * alpha + bg_blue * inv_alpha) / 256; + + *dest = 0xff000000 | (red << 16) | (green << 8) | blue; + dest += pitch; + fracpos += fracstep; + } + } + + FString DrawParticleColumnRGBACommand::DebugInfo() + { + return "DrawParticle"; + } + +} diff --git a/src/r_draw_rgba.h b/src/r_draw_rgba.h new file mode 100644 index 000000000..1364d537b --- /dev/null +++ b/src/r_draw_rgba.h @@ -0,0 +1,487 @@ +/* +** Drawer commands for the RT family of drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_draw.h" +#include "v_palette.h" +#include "r_thread.h" +#include "r_drawers.h" + +#ifndef NO_SSE +#include +#endif + +struct FSpecialColormap; + +EXTERN_CVAR(Bool, r_mipmap) +EXTERN_CVAR(Float, r_lod_bias) + +namespace swrenderer +{ + // Give the compiler a strong hint we want these functions inlined: + #ifndef FORCEINLINE + #if defined(_MSC_VER) + #define FORCEINLINE __forceinline + #elif defined(__GNUC__) + #define FORCEINLINE __attribute__((always_inline)) inline + #else + #define FORCEINLINE inline + #endif + #endif + + // Promise compiler we have no aliasing of this pointer + #ifndef RESTRICT + #if defined(_MSC_VER) + #define RESTRICT __restrict + #elif defined(__GNUC__) + #define RESTRICT __restrict__ + #else + #define RESTRICT + #endif + #endif + + #define DECLARE_DRAW_COMMAND(name, func, base) \ + class name##LLVMCommand : public base \ + { \ + public: \ + using base::base; \ + void Execute(DrawerThread *thread) override \ + { \ + WorkerThreadData d = ThreadData(thread); \ + Drawers::Instance()->func(&args, &d); \ + } \ + }; + + class DrawSpanLLVMCommand : public DrawerCommand + { + public: + DrawSpanLLVMCommand(); + + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + + protected: + DrawSpanArgs args; + + private: + inline static bool sampler_setup(const uint32_t * &source, int &xbits, int &ybits, bool mipmapped); + }; + + class DrawSpanMaskedLLVMCommand : public DrawSpanLLVMCommand + { + public: + void Execute(DrawerThread *thread) override; + }; + + class DrawSpanTranslucentLLVMCommand : public DrawSpanLLVMCommand + { + public: + void Execute(DrawerThread *thread) override; + }; + + class DrawSpanMaskedTranslucentLLVMCommand : public DrawSpanLLVMCommand + { + public: + void Execute(DrawerThread *thread) override; + }; + + class DrawSpanAddClampLLVMCommand : public DrawSpanLLVMCommand + { + public: + void Execute(DrawerThread *thread) override; + }; + + class DrawSpanMaskedAddClampLLVMCommand : public DrawSpanLLVMCommand + { + public: + void Execute(DrawerThread *thread) override; + }; + + class DrawWall4LLVMCommand : public DrawerCommand + { + protected: + DrawWallArgs args; + + WorkerThreadData ThreadData(DrawerThread *thread); + + public: + DrawWall4LLVMCommand(); + + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawWall1LLVMCommand : public DrawerCommand + { + protected: + DrawWallArgs args; + + WorkerThreadData ThreadData(DrawerThread *thread); + + public: + DrawWall1LLVMCommand(); + + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawColumnLLVMCommand : public DrawerCommand + { + protected: + DrawColumnArgs args; + + WorkerThreadData ThreadData(DrawerThread *thread); + FString DebugInfo() override; + + public: + DrawColumnLLVMCommand(); + + void Execute(DrawerThread *thread) override; + }; + + class DrawSkyLLVMCommand : public DrawerCommand + { + protected: + DrawSkyArgs args; + + WorkerThreadData ThreadData(DrawerThread *thread); + + public: + DrawSkyLLVMCommand(uint32_t solid_top, uint32_t solid_bottom); + FString DebugInfo() override; + }; + + DECLARE_DRAW_COMMAND(DrawWallMasked4, mvlinec4, DrawWall4LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallAdd4, tmvline4_add, DrawWall4LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallAddClamp4, tmvline4_addclamp, DrawWall4LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallSubClamp4, tmvline4_subclamp, DrawWall4LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallRevSubClamp4, tmvline4_revsubclamp, DrawWall4LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallMasked1, mvlinec1, DrawWall1LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallAdd1, tmvline1_add, DrawWall1LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallAddClamp1, tmvline1_addclamp, DrawWall1LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallSubClamp1, tmvline1_subclamp, DrawWall1LLVMCommand); + DECLARE_DRAW_COMMAND(DrawWallRevSubClamp1, tmvline1_revsubclamp, DrawWall1LLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnAdd, DrawColumnAdd, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnTranslated, DrawColumnTranslated, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnTlatedAdd, DrawColumnTlatedAdd, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnShaded, DrawColumnShaded, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnAddClamp, DrawColumnAddClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnAddClampTranslated, DrawColumnAddClampTranslated, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnSubClamp, DrawColumnSubClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnSubClampTranslated, DrawColumnSubClampTranslated, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnRevSubClamp, DrawColumnRevSubClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawColumnRevSubClampTranslated, DrawColumnRevSubClampTranslated, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(FillColumn, FillColumn, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(FillColumnAdd, FillColumnAdd, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(FillColumnAddClamp, FillColumnAddClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(FillColumnSubClamp, FillColumnSubClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(FillColumnRevSubClamp, FillColumnRevSubClamp, DrawColumnLLVMCommand); + DECLARE_DRAW_COMMAND(DrawSingleSky1, DrawSky1, DrawSkyLLVMCommand); + DECLARE_DRAW_COMMAND(DrawSingleSky4, DrawSky4, DrawSkyLLVMCommand); + DECLARE_DRAW_COMMAND(DrawDoubleSky1, DrawDoubleSky1, DrawSkyLLVMCommand); + DECLARE_DRAW_COMMAND(DrawDoubleSky4, DrawDoubleSky4, DrawSkyLLVMCommand); + + class DrawFuzzColumnRGBACommand : public DrawerCommand + { + int _x; + int _yl; + int _yh; + uint8_t * RESTRICT _destorg; + int _pitch; + int _fuzzpos; + int _fuzzviewheight; + + public: + DrawFuzzColumnRGBACommand(); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class FillSpanRGBACommand : public DrawerCommand + { + int _x1; + int _x2; + int _y; + uint8_t * RESTRICT _destorg; + fixed_t _light; + int _color; + + public: + FillSpanRGBACommand(); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawSlabRGBACommand : public DrawerCommand + { + int _dx; + fixed_t _v; + int _dy; + fixed_t _vi; + const uint8_t *_voxelptr; + uint32_t *_p; + ShadeConstants _shade_constants; + const uint8_t *_colormap; + fixed_t _light; + int _pitch; + int _start_y; + + public: + DrawSlabRGBACommand(int dx, fixed_t v, int dy, fixed_t vi, const uint8_t *vptr, uint8_t *p, ShadeConstants shade_constants, const uint8_t *colormap, fixed_t light); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawFogBoundaryLineRGBACommand : public DrawerCommand + { + int _y; + int _x; + int _x2; + uint8_t * RESTRICT _destorg; + fixed_t _light; + ShadeConstants _shade_constants; + + public: + DrawFogBoundaryLineRGBACommand(int y, int x, int x2); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawTiltedSpanRGBACommand : public DrawerCommand + { + int _x1; + int _x2; + int _y; + uint8_t * RESTRICT _destorg; + fixed_t _light; + ShadeConstants _shade_constants; + FVector3 _plane_sz; + FVector3 _plane_su; + FVector3 _plane_sv; + bool _plane_shade; + int _planeshade; + float _planelightfloat; + fixed_t _pviewx; + fixed_t _pviewy; + int _xbits; + int _ybits; + const uint32_t * RESTRICT _source; + + public: + DrawTiltedSpanRGBACommand(int y, int x1, int x2, const FVector3 &plane_sz, const FVector3 &plane_su, const FVector3 &plane_sv, bool plane_shade, int planeshade, float planelightfloat, fixed_t pviewx, fixed_t pviewy); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class DrawColoredSpanRGBACommand : public DrawerCommand + { + int _y; + int _x1; + int _x2; + uint8_t * RESTRICT _destorg; + fixed_t _light; + int _color; + + public: + DrawColoredSpanRGBACommand(int y, int x1, int x2); + + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class FillTransColumnRGBACommand : public DrawerCommand + { + int _x; + int _y1; + int _y2; + int _color; + int _a; + uint8_t * RESTRICT _destorg; + int _pitch; + fixed_t _light; + + public: + FillTransColumnRGBACommand(int x, int y1, int y2, int color, int a); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + }; + + class ApplySpecialColormapRGBACommand : public DrawerCommand + { + uint8_t *buffer; + int pitch; + int width; + int height; + int start_red; + int start_green; + int start_blue; + int end_red; + int end_green; + int end_blue; + + public: + ApplySpecialColormapRGBACommand(FSpecialColormap *colormap, DFrameBuffer *screen); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override { return "ApplySpecialColormapRGBACommand"; } + }; + + template + class DrawerBlendCommand : public CommandType + { + public: + void Execute(DrawerThread *thread) override + { + typename CommandType::LoopIterator loop(this, thread); + if (!loop) return; + BlendMode blend(*this, loop); + do + { + blend.Blend(*this, loop); + } while (loop.next()); + } + }; + + ///////////////////////////////////////////////////////////////////////////// + + class DrawParticleColumnRGBACommand : public DrawerCommand + { + public: + DrawParticleColumnRGBACommand(uint32_t *dest, int dest_y, int pitch, int count, uint32_t fg, uint32_t alpha, uint32_t fracposx); + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + + private: + uint32_t *_dest; + int _pitch; + int _count; + uint32_t _fg; + uint32_t _alpha; + uint32_t _fracposx; + }; + + ///////////////////////////////////////////////////////////////////////////// + // Pixel shading inline functions: + + class LightBgra + { + public: + // calculates the light constant passed to the shade_pal_index function + FORCEINLINE static uint32_t calc_light_multiplier(dsfixed_t light) + { + return 256 - (light >> (FRACBITS - 8)); + } + + // Calculates a ARGB8 color for the given palette index and light multiplier + FORCEINLINE static uint32_t shade_pal_index_simple(uint32_t index, uint32_t light) + { + const PalEntry &color = GPalette.BaseColors[index]; + uint32_t red = color.r; + uint32_t green = color.g; + uint32_t blue = color.b; + + red = red * light / 256; + green = green * light / 256; + blue = blue * light / 256; + + return 0xff000000 | (red << 16) | (green << 8) | blue; + } + + // Calculates a ARGB8 color for the given palette index, light multiplier and dynamic colormap + FORCEINLINE static uint32_t shade_pal_index(uint32_t index, uint32_t light, const ShadeConstants &constants) + { + const PalEntry &color = GPalette.BaseColors[index]; + uint32_t alpha = color.d & 0xff000000; + uint32_t red = color.r; + uint32_t green = color.g; + uint32_t blue = color.b; + if (constants.simple_shade) + { + red = red * light / 256; + green = green * light / 256; + blue = blue * light / 256; + } + else + { + uint32_t inv_light = 256 - light; + uint32_t inv_desaturate = 256 - constants.desaturate; + + uint32_t intensity = ((red * 77 + green * 143 + blue * 37) >> 8) * constants.desaturate; + + red = (red * inv_desaturate + intensity) / 256; + green = (green * inv_desaturate + intensity) / 256; + blue = (blue * inv_desaturate + intensity) / 256; + + red = (constants.fade_red * inv_light + red * light) / 256; + green = (constants.fade_green * inv_light + green * light) / 256; + blue = (constants.fade_blue * inv_light + blue * light) / 256; + + red = (red * constants.light_red) / 256; + green = (green * constants.light_green) / 256; + blue = (blue * constants.light_blue) / 256; + } + return alpha | (red << 16) | (green << 8) | blue; + } + + FORCEINLINE static uint32_t shade_bgra_simple(uint32_t color, uint32_t light) + { + uint32_t red = RPART(color) * light / 256; + uint32_t green = GPART(color) * light / 256; + uint32_t blue = BPART(color) * light / 256; + return 0xff000000 | (red << 16) | (green << 8) | blue; + } + + FORCEINLINE static uint32_t shade_bgra(uint32_t color, uint32_t light, const ShadeConstants &constants) + { + uint32_t alpha = color & 0xff000000; + uint32_t red = (color >> 16) & 0xff; + uint32_t green = (color >> 8) & 0xff; + uint32_t blue = color & 0xff; + if (constants.simple_shade) + { + red = red * light / 256; + green = green * light / 256; + blue = blue * light / 256; + } + else + { + uint32_t inv_light = 256 - light; + uint32_t inv_desaturate = 256 - constants.desaturate; + + uint32_t intensity = ((red * 77 + green * 143 + blue * 37) >> 8) * constants.desaturate; + + red = (red * inv_desaturate + intensity) / 256; + green = (green * inv_desaturate + intensity) / 256; + blue = (blue * inv_desaturate + intensity) / 256; + + red = (constants.fade_red * inv_light + red * light) / 256; + green = (constants.fade_green * inv_light + green * light) / 256; + blue = (constants.fade_blue * inv_light + blue * light) / 256; + + red = (red * constants.light_red) / 256; + green = (green * constants.light_green) / 256; + blue = (blue * constants.light_blue) / 256; + } + return alpha | (red << 16) | (green << 8) | blue; + } + }; +} diff --git a/src/r_drawers.cpp b/src/r_drawers.cpp new file mode 100644 index 000000000..e61e95183 --- /dev/null +++ b/src/r_drawers.cpp @@ -0,0 +1,294 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "i_system.h" +#include "r_drawers.h" +#include "x86.h" +#include "c_cvars.h" +#include "version.h" +#include "m_misc.h" + +///////////////////////////////////////////////////////////////////////////// + +extern "C" +{ + void DrawColumn_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnAdd_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnShaded_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnAddClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRevSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnTlatedAdd_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnAddClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnSubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRevSubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void FillColumn_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void FillColumnAdd_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void FillColumnAddClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void FillColumnSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void FillColumnRevSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1Copy_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1Add_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1Shaded_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1AddClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1SubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1RevSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1Translated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1TlatedAdd_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1AddClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1SubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt1RevSubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4Copy_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4Add_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4Shaded_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4AddClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4SubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4RevSubClamp_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4Translated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4TlatedAdd_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4AddClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4SubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawColumnRt4RevSubClampTranslated_SSE2(const DrawColumnArgs *, const WorkerThreadData *); + void DrawSpan_SSE2(const DrawSpanArgs *); + void DrawSpanMasked_SSE2(const DrawSpanArgs *); + void DrawSpanTranslucent_SSE2(const DrawSpanArgs *); + void DrawSpanMaskedTranslucent_SSE2(const DrawSpanArgs *); + void DrawSpanAddClamp_SSE2(const DrawSpanArgs *); + void DrawSpanMaskedAddClamp_SSE2(const DrawSpanArgs *); + void vlinec1_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void vlinec4_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void mvlinec1_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void mvlinec4_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline1_add_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline4_add_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline1_addclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline4_addclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline1_subclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline4_subclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline1_revsubclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void tmvline4_revsubclamp_SSE2(const DrawWallArgs *, const WorkerThreadData *); + void DrawSky1_SSE2(const DrawSkyArgs *, const WorkerThreadData *); + void DrawSky4_SSE2(const DrawSkyArgs *, const WorkerThreadData *); + void DrawDoubleSky1_SSE2(const DrawSkyArgs *, const WorkerThreadData *); + void DrawDoubleSky4_SSE2(const DrawSkyArgs *, const WorkerThreadData *); + void TriDraw8_0_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_1_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_2_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_3_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_4_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_5_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_6_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_7_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_8_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_9_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_10_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_11_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_12_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_13_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw8_14_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_0_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_1_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_2_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_3_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_4_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_5_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_6_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_7_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_8_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_9_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_10_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_11_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_12_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_13_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriDraw32_14_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_0_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_1_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_2_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_3_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_4_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_5_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_6_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_7_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_8_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_9_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_10_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_11_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_12_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_13_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill8_14_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_0_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_1_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_2_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_3_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_4_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_5_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_6_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_7_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_8_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_9_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_10_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_11_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_12_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_13_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); + void TriFill32_14_SSE2(const TriDrawTriangleArgs *, WorkerThreadData *); +} + +///////////////////////////////////////////////////////////////////////////// + +Drawers::Drawers() +{ + DrawColumn = DrawColumn_SSE2; + DrawColumnAdd = DrawColumnAdd_SSE2; + DrawColumnShaded = DrawColumnShaded_SSE2; + DrawColumnAddClamp = DrawColumnAddClamp_SSE2; + DrawColumnSubClamp = DrawColumnSubClamp_SSE2; + DrawColumnRevSubClamp = DrawColumnRevSubClamp_SSE2; + DrawColumnTranslated = DrawColumnTranslated_SSE2; + DrawColumnTlatedAdd = DrawColumnTlatedAdd_SSE2; + DrawColumnAddClampTranslated = DrawColumnAddClampTranslated_SSE2; + DrawColumnSubClampTranslated = DrawColumnSubClampTranslated_SSE2; + DrawColumnRevSubClampTranslated = DrawColumnRevSubClampTranslated_SSE2; + FillColumn = FillColumn_SSE2; + FillColumnAdd = FillColumnAdd_SSE2; + FillColumnAddClamp = FillColumnAddClamp_SSE2; + FillColumnSubClamp = FillColumnSubClamp_SSE2; + FillColumnRevSubClamp = FillColumnRevSubClamp_SSE2; + DrawSpan = DrawSpan_SSE2; + DrawSpanMasked = DrawSpanMasked_SSE2; + DrawSpanTranslucent = DrawSpanTranslucent_SSE2; + DrawSpanMaskedTranslucent = DrawSpanMaskedTranslucent_SSE2; + DrawSpanAddClamp = DrawSpanAddClamp_SSE2; + DrawSpanMaskedAddClamp = DrawSpanMaskedAddClamp_SSE2; + vlinec1 = vlinec1_SSE2; + vlinec4 = vlinec4_SSE2; + mvlinec1 = mvlinec1_SSE2; + mvlinec4 = mvlinec4_SSE2; + tmvline1_add = tmvline1_add_SSE2; + tmvline4_add = tmvline4_add_SSE2; + tmvline1_addclamp = tmvline1_addclamp_SSE2; + tmvline4_addclamp = tmvline4_addclamp_SSE2; + tmvline1_subclamp = tmvline1_subclamp_SSE2; + tmvline4_subclamp = tmvline4_subclamp_SSE2; + tmvline1_revsubclamp = tmvline1_revsubclamp_SSE2; + tmvline4_revsubclamp = tmvline4_revsubclamp_SSE2; + DrawSky1 = DrawSky1_SSE2; + DrawSky4 = DrawSky4_SSE2; + DrawDoubleSky1 = DrawDoubleSky1_SSE2; + DrawDoubleSky4 = DrawDoubleSky4_SSE2; + TriDraw8.push_back(TriDraw8_0_SSE2); + TriDraw8.push_back(TriDraw8_1_SSE2); + TriDraw8.push_back(TriDraw8_2_SSE2); + TriDraw8.push_back(TriDraw8_3_SSE2); + TriDraw8.push_back(TriDraw8_4_SSE2); + TriDraw8.push_back(TriDraw8_5_SSE2); + TriDraw8.push_back(TriDraw8_6_SSE2); + TriDraw8.push_back(TriDraw8_7_SSE2); + TriDraw8.push_back(TriDraw8_8_SSE2); + TriDraw8.push_back(TriDraw8_9_SSE2); + TriDraw8.push_back(TriDraw8_10_SSE2); + TriDraw8.push_back(TriDraw8_11_SSE2); + TriDraw8.push_back(TriDraw8_12_SSE2); + TriDraw8.push_back(TriDraw8_13_SSE2); + TriDraw8.push_back(TriDraw8_14_SSE2); + TriDraw32.push_back(TriDraw32_0_SSE2); + TriDraw32.push_back(TriDraw32_1_SSE2); + TriDraw32.push_back(TriDraw32_2_SSE2); + TriDraw32.push_back(TriDraw32_3_SSE2); + TriDraw32.push_back(TriDraw32_4_SSE2); + TriDraw32.push_back(TriDraw32_5_SSE2); + TriDraw32.push_back(TriDraw32_6_SSE2); + TriDraw32.push_back(TriDraw32_7_SSE2); + TriDraw32.push_back(TriDraw32_8_SSE2); + TriDraw32.push_back(TriDraw32_9_SSE2); + TriDraw32.push_back(TriDraw32_10_SSE2); + TriDraw32.push_back(TriDraw32_11_SSE2); + TriDraw32.push_back(TriDraw32_12_SSE2); + TriDraw32.push_back(TriDraw32_13_SSE2); + TriDraw32.push_back(TriDraw32_14_SSE2); + TriFill8.push_back(TriFill8_0_SSE2); + TriFill8.push_back(TriFill8_1_SSE2); + TriFill8.push_back(TriFill8_2_SSE2); + TriFill8.push_back(TriFill8_3_SSE2); + TriFill8.push_back(TriFill8_4_SSE2); + TriFill8.push_back(TriFill8_5_SSE2); + TriFill8.push_back(TriFill8_6_SSE2); + TriFill8.push_back(TriFill8_7_SSE2); + TriFill8.push_back(TriFill8_8_SSE2); + TriFill8.push_back(TriFill8_9_SSE2); + TriFill8.push_back(TriFill8_10_SSE2); + TriFill8.push_back(TriFill8_11_SSE2); + TriFill8.push_back(TriFill8_12_SSE2); + TriFill8.push_back(TriFill8_13_SSE2); + TriFill8.push_back(TriFill8_14_SSE2); + TriFill32.push_back(TriFill32_0_SSE2); + TriFill32.push_back(TriFill32_1_SSE2); + TriFill32.push_back(TriFill32_2_SSE2); + TriFill32.push_back(TriFill32_3_SSE2); + TriFill32.push_back(TriFill32_4_SSE2); + TriFill32.push_back(TriFill32_5_SSE2); + TriFill32.push_back(TriFill32_6_SSE2); + TriFill32.push_back(TriFill32_7_SSE2); + TriFill32.push_back(TriFill32_8_SSE2); + TriFill32.push_back(TriFill32_9_SSE2); + TriFill32.push_back(TriFill32_10_SSE2); + TriFill32.push_back(TriFill32_11_SSE2); + TriFill32.push_back(TriFill32_12_SSE2); + TriFill32.push_back(TriFill32_13_SSE2); + TriFill32.push_back(TriFill32_14_SSE2); +} + +Drawers *Drawers::Instance() +{ + static Drawers drawers; + return &drawers; +} + +FString DrawWallArgs::ToString() +{ + FString info; + info.Format("dest_y = %i, count = %i, flags = %i, texturefrac[0] = %u, textureheight[0] = %u", dest_y, count, flags, texturefrac[0], textureheight[0]); + return info; +} + +FString DrawSpanArgs::ToString() +{ + FString info; + info.Format("x1 = %i, x2 = %i, y = %i, flags = %i", x1, x2, y, flags); + return info; +} + +FString DrawColumnArgs::ToString() +{ + FString info; + info.Format("dest_y = %i, count = %i, flags = %i, iscale = %i (%f), texturefrac = %i (%f)", dest_y, count, flags, iscale, ((fixed_t)iscale) / (float)FRACUNIT, texturefrac, ((fixed_t)texturefrac) / (float)FRACUNIT); + return info; +} + +FString DrawSkyArgs::ToString() +{ + FString info; + info.Format("dest_y = %i, count = %i", dest_y, count); + return info; +} diff --git a/src/r_drawers.h b/src/r_drawers.h new file mode 100644 index 000000000..7a94c82dd --- /dev/null +++ b/src/r_drawers.h @@ -0,0 +1,344 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include +#include + +class FString; + +struct TriFullSpan +{ + uint16_t X; + uint16_t Y; + uint32_t Length; +}; + +struct TriPartialBlock +{ + uint16_t X; + uint16_t Y; + uint32_t Mask0; + uint32_t Mask1; +}; + +struct WorkerThreadData +{ + int32_t core; + int32_t num_cores; + int32_t pass_start_y; + int32_t pass_end_y; + uint32_t *temp; + + // Triangle working data: + TriFullSpan *FullSpans; + TriPartialBlock *PartialBlocks; + uint32_t NumFullSpans; + uint32_t NumPartialBlocks; + int32_t StartX; + int32_t StartY; +}; + +struct TriLight +{ + uint32_t color; + float x, y, z; + float radius; +}; + +struct DrawWallArgs +{ + uint32_t *dest; + const uint32_t *source[4]; + const uint32_t *source2[4]; + int32_t pitch; + int32_t count; + int32_t dest_y; + uint32_t texturefrac[4]; + uint32_t texturefracx[4]; + uint32_t iscale[4]; + uint32_t textureheight[4]; + uint32_t light[4]; + uint32_t srcalpha; + uint32_t destalpha; + + uint16_t light_alpha; + uint16_t light_red; + uint16_t light_green; + uint16_t light_blue; + uint16_t fade_alpha; + uint16_t fade_red; + uint16_t fade_green; + uint16_t fade_blue; + uint16_t desaturate; + uint32_t flags; + enum Flags + { + simple_shade = 1, + nearest_filter = 2 + }; + + float z, step_z; + TriLight *dynlights; + uint32_t num_dynlights; + + FString ToString(); +}; + +struct DrawSpanArgs +{ + uint32_t *destorg; + const uint32_t *source; + int32_t destpitch; + int32_t xfrac; + int32_t yfrac; + int32_t xstep; + int32_t ystep; + int32_t x1; + int32_t x2; + int32_t y; + int32_t xbits; + int32_t ybits; + uint32_t light; + uint32_t srcalpha; + uint32_t destalpha; + + uint16_t light_alpha; + uint16_t light_red; + uint16_t light_green; + uint16_t light_blue; + uint16_t fade_alpha; + uint16_t fade_red; + uint16_t fade_green; + uint16_t fade_blue; + uint16_t desaturate; + uint32_t flags; + enum Flags + { + simple_shade = 1, + nearest_filter = 2 + }; + + float viewpos_x, step_viewpos_x; + TriLight *dynlights; + uint32_t num_dynlights; + + FString ToString(); +}; + +struct DrawColumnArgs +{ + uint32_t *dest; + const uint8_t *source; + const uint8_t *source2; + uint8_t *colormap; + uint8_t *translation; + const uint32_t *basecolors; + int32_t pitch; + int32_t count; + int32_t dest_y; + uint32_t iscale; + uint32_t texturefracx; + uint32_t textureheight; + uint32_t texturefrac; + uint32_t light; + uint32_t color; + uint32_t srccolor; + uint32_t srcalpha; + uint32_t destalpha; + + uint16_t light_alpha; + uint16_t light_red; + uint16_t light_green; + uint16_t light_blue; + uint16_t fade_alpha; + uint16_t fade_red; + uint16_t fade_green; + uint16_t fade_blue; + uint16_t desaturate; + uint32_t flags; + enum Flags + { + simple_shade = 1, + nearest_filter = 2 + }; + + FString ToString(); +}; + +struct DrawSkyArgs +{ + uint32_t *dest; + const uint32_t *source0[4]; + const uint32_t *source1[4]; + int32_t pitch; + int32_t count; + int32_t dest_y; + uint32_t texturefrac[4]; + uint32_t iscale[4]; + uint32_t textureheight0; + uint32_t textureheight1; + uint32_t top_color; + uint32_t bottom_color; + + FString ToString(); +}; + +struct TriVertex +{ + TriVertex() { } + TriVertex(float x, float y, float z, float w, float u, float v) : x(x), y(y), z(z), w(w) { varying[0] = u; varying[1] = v; } + + enum { NumVarying = 2 }; + float x, y, z, w; + float varying[NumVarying]; +}; + +struct TriUniforms +{ + uint32_t light; + uint32_t subsectorDepth; + uint32_t color; + uint32_t srcalpha; + uint32_t destalpha; + uint16_t light_alpha; + uint16_t light_red; + uint16_t light_green; + uint16_t light_blue; + uint16_t fade_alpha; + uint16_t fade_red; + uint16_t fade_green; + uint16_t fade_blue; + uint16_t desaturate; + uint32_t flags; + enum Flags + { + simple_shade = 1, + nearest_filter = 2, + fixed_light = 4 + }; +}; + +struct TriDrawTriangleArgs +{ + uint8_t *dest; + int32_t pitch; + TriVertex *v1; + TriVertex *v2; + TriVertex *v3; + int32_t clipleft; + int32_t clipright; + int32_t cliptop; + int32_t clipbottom; + const uint8_t *texturePixels; + uint32_t textureWidth; + uint32_t textureHeight; + const uint8_t *translation; + const TriUniforms *uniforms; + uint8_t *stencilValues; + uint32_t *stencilMasks; + int32_t stencilPitch; + uint8_t stencilTestValue; + uint8_t stencilWriteValue; + uint32_t *subsectorGBuffer; + const uint8_t *colormaps; + const uint8_t *RGB256k; + const uint8_t *BaseColors; +}; + +enum class TriBlendMode +{ + Copy, // blend_copy(shade(fg)) + AlphaBlend, // blend_alpha_blend(shade(fg), bg) + AddSolid, // blend_add(shade(fg), bg, srcalpha, destalpha) + Add, // blend_add(shade(fg), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + Sub, // blend_sub(shade(fg), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + RevSub, // blend_revsub(shade(fg), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + Stencil, // blend_stencil(shade(color), fg.a, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + Shaded, // blend_stencil(shade(color), fg.index, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + TranslateCopy, // blend_copy(shade(translate(fg))) + TranslateAlphaBlend, // blend_alpha_blend(shade(translate(fg)), bg) + TranslateAdd, // blend_add(shade(translate(fg)), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + TranslateSub, // blend_sub(shade(translate(fg)), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + TranslateRevSub,// blend_revsub(shade(translate(fg)), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)) + AddSrcColorOneMinusSrcColor, // glBlendMode(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR) used by GZDoom's fullbright additive sprites + Skycap // Fade to sky color when the V texture coordinate go beyond the [-1, 1] range +}; + +inline int NumTriBlendModes() { return (int)TriBlendMode::Skycap + 1; } + +class Drawers +{ +public: + static Drawers *Instance(); + + void(*DrawColumn)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnAdd)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnShaded)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnAddClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnSubClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnRevSubClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnTranslated)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnTlatedAdd)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnAddClampTranslated)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnSubClampTranslated)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*DrawColumnRevSubClampTranslated)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*FillColumn)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*FillColumnAdd)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*FillColumnAddClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*FillColumnSubClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + void(*FillColumnRevSubClamp)(const DrawColumnArgs *, const WorkerThreadData *) = nullptr; + + void(*DrawSpan)(const DrawSpanArgs *) = nullptr; + void(*DrawSpanMasked)(const DrawSpanArgs *) = nullptr; + void(*DrawSpanTranslucent)(const DrawSpanArgs *) = nullptr; + void(*DrawSpanMaskedTranslucent)(const DrawSpanArgs *) = nullptr; + void(*DrawSpanAddClamp)(const DrawSpanArgs *) = nullptr; + void(*DrawSpanMaskedAddClamp)(const DrawSpanArgs *) = nullptr; + + void(*vlinec1)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*vlinec4)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*mvlinec1)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*mvlinec4)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline1_add)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline4_add)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline1_addclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline4_addclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline1_subclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline4_subclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline1_revsubclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + void(*tmvline4_revsubclamp)(const DrawWallArgs *, const WorkerThreadData *) = nullptr; + + void(*DrawSky1)(const DrawSkyArgs *, const WorkerThreadData *) = nullptr; + void(*DrawSky4)(const DrawSkyArgs *, const WorkerThreadData *) = nullptr; + void(*DrawDoubleSky1)(const DrawSkyArgs *, const WorkerThreadData *) = nullptr; + void(*DrawDoubleSky4)(const DrawSkyArgs *, const WorkerThreadData *) = nullptr; + + std::vector TriDraw8; + std::vector TriDraw32; + std::vector TriFill8; + std::vector TriFill32; + +private: + Drawers(); +}; diff --git a/src/r_drawt_pal.cpp b/src/r_drawt_pal.cpp deleted file mode 100644 index 3356592d2..000000000 --- a/src/r_drawt_pal.cpp +++ /dev/null @@ -1,867 +0,0 @@ -/* -** r_drawt.cpp -** Faster column drawers for modern processors -** -**--------------------------------------------------------------------------- -** Copyright 1998-2006 Randy Heit -** 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 author 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. -**--------------------------------------------------------------------------- -** -** These functions stretch columns into a temporary buffer and then -** map them to the screen. On modern machines, this is faster than drawing -** them directly to the screen. -** -** Will I be able to even understand any of this if I come back to it later? -** Let's hope so. :-) -*/ - -#include "templates.h" -#include "doomtype.h" -#include "doomdef.h" -#include "r_defs.h" -#include "r_draw.h" -#include "r_main.h" -#include "r_things.h" -#include "v_video.h" -#include "r_draw_pal.h" - -// I should have commented this stuff better. -// -// dc_temp is the buffer R_DrawColumnHoriz writes into. -// dc_tspans points into it. -// dc_ctspan points into dc_tspans. -// horizspan also points into dc_tspans. - -// dc_ctspan is advanced while drawing into dc_temp. -// horizspan is advanced up to dc_ctspan when drawing from dc_temp to the screen. - -namespace swrenderer -{ - RtInitColsPalCommand::RtInitColsPalCommand(uint8_t *buff) : buff(buff) - { - } - - void RtInitColsPalCommand::Execute(DrawerThread *thread) - { - thread->dc_temp = buff == nullptr ? thread->dc_temp_buff : buff; - } - - ///////////////////////////////////////////////////////////////////// - - PalColumnHorizCommand::PalColumnHorizCommand() - { - using namespace drawerargs; - - _source = dc_source; - _iscale = dc_iscale; - _texturefrac = dc_texturefrac; - _count = dc_count; - _color = dc_color; - _x = dc_x; - _yl = dc_yl; - } - - void DrawColumnHorizPalCommand::Execute(DrawerThread *thread) - { - int count = _count; - uint8_t *dest; - fixed_t fracstep; - fixed_t frac; - - count = thread->count_for_thread(_yl, count); - if (count <= 0) - return; - - fracstep = _iscale; - frac = _texturefrac; - - const uint8_t *source = _source; - - int x = _x & 3; - dest = &thread->dc_temp[x + thread->temp_line_for_thread(_yl) * 4]; - frac += fracstep * thread->skipped_by_thread(_yl); - fracstep *= thread->num_cores; - - if (count & 1) { - *dest = source[frac >> FRACBITS]; dest += 4; frac += fracstep; - } - if (count & 2) { - dest[0] = source[frac >> FRACBITS]; frac += fracstep; - dest[4] = source[frac >> FRACBITS]; frac += fracstep; - dest += 8; - } - if (count & 4) { - dest[0] = source[frac >> FRACBITS]; frac += fracstep; - dest[4] = source[frac >> FRACBITS]; frac += fracstep; - dest[8] = source[frac >> FRACBITS]; frac += fracstep; - dest[12] = source[frac >> FRACBITS]; frac += fracstep; - dest += 16; - } - count >>= 3; - if (!count) return; - - do - { - dest[0] = source[frac >> FRACBITS]; frac += fracstep; - dest[4] = source[frac >> FRACBITS]; frac += fracstep; - dest[8] = source[frac >> FRACBITS]; frac += fracstep; - dest[12] = source[frac >> FRACBITS]; frac += fracstep; - dest[16] = source[frac >> FRACBITS]; frac += fracstep; - dest[20] = source[frac >> FRACBITS]; frac += fracstep; - dest[24] = source[frac >> FRACBITS]; frac += fracstep; - dest[28] = source[frac >> FRACBITS]; frac += fracstep; - dest += 32; - } while (--count); - } - - void FillColumnHorizPalCommand::Execute(DrawerThread *thread) - { - int count = _count; - uint8_t color = _color; - uint8_t *dest; - - count = thread->count_for_thread(_yl, count); - if (count <= 0) - return; - - int x = _x & 3; - dest = &thread->dc_temp[x + thread->temp_line_for_thread(_yl) * 4]; - - if (count & 1) { - *dest = color; - dest += 4; - } - if (!(count >>= 1)) - return; - do { - dest[0] = color; dest[4] = color; - dest += 8; - } while (--count); - } - - ///////////////////////////////////////////////////////////////////// - - PalRtCommand::PalRtCommand(int hx, int sx, int yl, int yh) : hx(hx), sx(sx), yl(yl), yh(yh) - { - using namespace drawerargs; - - _destorg = dc_destorg; - _pitch = dc_pitch; - _colormap = dc_colormap; - _srcblend = dc_srcblend; - _destblend = dc_destblend; - _translation = dc_translation; - _color = dc_color; - } - - void DrawColumnRt1CopyPalCommand::Execute(DrawerThread *thread) - { - uint8_t *source; - uint8_t *dest; - int count; - int pitch; - - count = yh - yl + 1; - - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - - if (count & 1) { - *dest = *source; - source += 4; - dest += pitch; - } - if (count & 2) { - dest[0] = source[0]; - dest[pitch] = source[4]; - source += 8; - dest += pitch*2; - } - if (!(count >>= 2)) - return; - - do { - dest[0] = source[0]; - dest[pitch] = source[4]; - dest[pitch*2] = source[8]; - dest[pitch*3] = source[12]; - source += 16; - dest += pitch*4; - } while (--count); - } - - void DrawColumnRt4CopyPalCommand::Execute(DrawerThread *thread) - { - int *source; - int *dest; - int count; - int pitch; - - count = yh - yl + 1; - - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - dest = (int *)(ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg); - source = (int *)(&thread->dc_temp[thread->temp_line_for_thread(yl)*4]); - pitch = _pitch*thread->num_cores/sizeof(int); - - if (count & 1) { - *dest = *source; - source += 4/sizeof(int); - dest += pitch; - } - if (!(count >>= 1)) - return; - - do { - dest[0] = source[0]; - dest[pitch] = source[4/sizeof(int)]; - source += 8/sizeof(int); - dest += pitch*2; - } while (--count); - } - - void DrawColumnRt1PalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int count; - int pitch; - - count = yh - yl + 1; - - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - colormap = _colormap; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl) *4 + hx]; - pitch = _pitch*thread->num_cores; - - if (count & 1) { - *dest = colormap[*source]; - source += 4; - dest += pitch; - } - if (!(count >>= 1)) - return; - - do { - dest[0] = colormap[source[0]]; - dest[pitch] = colormap[source[4]]; - source += 8; - dest += pitch*2; - } while (--count); - } - - void DrawColumnRt4PalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int count; - int pitch; - - count = yh - yl + 1; - - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - colormap = _colormap; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch*thread->num_cores; - - if (count & 1) { - dest[0] = colormap[source[0]]; - dest[1] = colormap[source[1]]; - dest[2] = colormap[source[2]]; - dest[3] = colormap[source[3]]; - source += 4; - dest += pitch; - } - if (!(count >>= 1)) - return; - - do { - dest[0] = colormap[source[0]]; - dest[1] = colormap[source[1]]; - dest[2] = colormap[source[2]]; - dest[3] = colormap[source[3]]; - dest[pitch] = colormap[source[4]]; - dest[pitch+1] = colormap[source[5]]; - dest[pitch+2] = colormap[source[6]]; - dest[pitch+3] = colormap[source[7]]; - source += 8; - dest += pitch*2; - } while (--count); - } - - void DrawColumnRt1TranslatedPalCommand::Execute(DrawerThread *thread) - { - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - uint8_t *source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - const uint8_t *translation = _translation; - - // Things we do to hit the compiler's optimizer with a clue bat: - // 1. Parallelism is explicitly spelled out by using a separate - // C instruction for each assembly instruction. GCC lets me - // have four temporaries, but VC++ spills to the stack with - // more than two. Two is probably optimal, anyway. - // 2. The results of the translation lookups are explicitly - // stored in byte-sized variables. This causes the VC++ code - // to use byte mov instructions in most cases; for apparently - // random reasons, it will use movzx for some places. GCC - // ignores this and uses movzx always. - - // Do 8 rows at a time. - for (int count8 = count >> 3; count8; --count8) - { - int c0, c1; - uint8_t b0, b1; - - c0 = source[0]; c1 = source[4]; - b0 = translation[c0]; b1 = translation[c1]; - source[0] = b0; source[4] = b1; - - c0 = source[8]; c1 = source[12]; - b0 = translation[c0]; b1 = translation[c1]; - source[8] = b0; source[12] = b1; - - c0 = source[16]; c1 = source[20]; - b0 = translation[c0]; b1 = translation[c1]; - source[16] = b0; source[20] = b1; - - c0 = source[24]; c1 = source[28]; - b0 = translation[c0]; b1 = translation[c1]; - source[24] = b0; source[28] = b1; - - source += 32; - } - // Finish by doing 1 row at a time. - for (count &= 7; count; --count, source += 4) - { - source[0] = translation[source[0]]; - } - } - - void DrawColumnRt4TranslatedPalCommand::Execute(DrawerThread *thread) - { - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - uint8_t *source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - const uint8_t *translation = _translation; - int c0, c1; - uint8_t b0, b1; - - // Do 2 rows at a time. - for (int count8 = count >> 1; count8; --count8) - { - c0 = source[0]; c1 = source[1]; - b0 = translation[c0]; b1 = translation[c1]; - source[0] = b0; source[1] = b1; - - c0 = source[2]; c1 = source[3]; - b0 = translation[c0]; b1 = translation[c1]; - source[2] = b0; source[3] = b1; - - c0 = source[4]; c1 = source[5]; - b0 = translation[c0]; b1 = translation[c1]; - source[4] = b0; source[5] = b1; - - c0 = source[6]; c1 = source[7]; - b0 = translation[c0]; b1 = translation[c1]; - source[6] = b0; source[7] = b1; - - source += 8; - } - // Do the final row if count was odd. - if (count & 1) - { - c0 = source[0]; c1 = source[1]; - b0 = translation[c0]; b1 = translation[c1]; - source[0] = b0; source[1] = b1; - - c0 = source[2]; c1 = source[3]; - b0 = translation[c0]; b1 = translation[c1]; - source[2] = b0; source[3] = b1; - } - } - - void DrawColumnRt1AddPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t fg = colormap[*source]; - uint32_t bg = *dest; - - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg+bg) | 0x1f07c1f; - *dest = RGB32k.All[fg & (fg>>15)]; - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt4AddPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t fg = colormap[source[0]]; - uint32_t bg = dest[0]; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg+bg) | 0x1f07c1f; - dest[0] = RGB32k.All[fg & (fg>>15)]; - - fg = colormap[source[1]]; - bg = dest[1]; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg+bg) | 0x1f07c1f; - dest[1] = RGB32k.All[fg & (fg>>15)]; - - - fg = colormap[source[2]]; - bg = dest[2]; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg+bg) | 0x1f07c1f; - dest[2] = RGB32k.All[fg & (fg>>15)]; - - fg = colormap[source[3]]; - bg = dest[3]; - fg = fg2rgb[fg]; - bg = bg2rgb[bg]; - fg = (fg+bg) | 0x1f07c1f; - dest[3] = RGB32k.All[fg & (fg>>15)]; - - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt1ShadedPalCommand::Execute(DrawerThread *thread) - { - uint32_t *fgstart; - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - fgstart = &Col2RGB8[0][_color]; - colormap = _colormap; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - - do { - uint32_t val = colormap[*source]; - uint32_t fg = fgstart[val<<8]; - val = (Col2RGB8[64-val][*dest] + fg) | 0x1f07c1f; - *dest = RGB32k.All[val & (val>>15)]; - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt4ShadedPalCommand::Execute(DrawerThread *thread) - { - uint32_t *fgstart; - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - fgstart = &Col2RGB8[0][_color]; - colormap = _colormap; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch * thread->num_cores; - - do { - uint32_t val; - - val = colormap[source[0]]; - val = (Col2RGB8[64-val][dest[0]] + fgstart[val<<8]) | 0x1f07c1f; - dest[0] = RGB32k.All[val & (val>>15)]; - - val = colormap[source[1]]; - val = (Col2RGB8[64-val][dest[1]] + fgstart[val<<8]) | 0x1f07c1f; - dest[1] = RGB32k.All[val & (val>>15)]; - - val = colormap[source[2]]; - val = (Col2RGB8[64-val][dest[2]] + fgstart[val<<8]) | 0x1f07c1f; - dest[2] = RGB32k.All[val & (val>>15)]; - - val = colormap[source[3]]; - val = (Col2RGB8[64-val][dest[3]] + fgstart[val<<8]) | 0x1f07c1f; - dest[3] = RGB32k.All[val & (val>>15)]; - - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt1AddClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t a = fg2rgb[colormap[*source]] + bg2rgb[*dest]; - uint32_t b = a; - - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - *dest = RGB32k.All[(a>>15) & a]; - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt4AddClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - - do { - uint32_t a = fg2rgb[colormap[source[0]]] + bg2rgb[dest[0]]; - uint32_t b = a; - - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - dest[0] = RGB32k.All[(a>>15) & a]; - - a = fg2rgb[colormap[source[1]]] + bg2rgb[dest[1]]; - b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - dest[1] = RGB32k.All[(a>>15) & a]; - - a = fg2rgb[colormap[source[2]]] + bg2rgb[dest[2]]; - b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - dest[2] = RGB32k.All[(a>>15) & a]; - - a = fg2rgb[colormap[source[3]]] + bg2rgb[dest[3]]; - b = a; - a |= 0x01f07c1f; - b &= 0x40100400; - a &= 0x3fffffff; - b = b - (b >> 5); - a |= b; - dest[3] = RGB32k.All[(a>>15) & a]; - - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt1SubClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t a = (fg2rgb[colormap[*source]] | 0x40100400) - bg2rgb[*dest]; - uint32_t b = a; - - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[(a>>15) & a]; - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt4SubClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t a = (fg2rgb[colormap[source[0]]] | 0x40100400) - bg2rgb[dest[0]]; - uint32_t b = a; - - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[0] = RGB32k.All[(a>>15) & a]; - - a = (fg2rgb[colormap[source[1]]] | 0x40100400) - bg2rgb[dest[1]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[1] = RGB32k.All[(a>>15) & a]; - - a = (fg2rgb[colormap[source[2]]] | 0x40100400) - bg2rgb[dest[2]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[2] = RGB32k.All[(a>>15) & a]; - - a = (fg2rgb[colormap[source[3]]] | 0x40100400) - bg2rgb[dest[3]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[3] = RGB32k.All[(a>>15) & a]; - - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt1RevSubClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4 + hx]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t a = (bg2rgb[*dest] | 0x40100400) - fg2rgb[colormap[*source]]; - uint32_t b = a; - - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - *dest = RGB32k.All[(a>>15) & a]; - source += 4; - dest += pitch; - } while (--count); - } - - void DrawColumnRt4RevSubClampPalCommand::Execute(DrawerThread *thread) - { - const uint8_t *colormap; - uint8_t *source; - uint8_t *dest; - int pitch; - - int count = yh - yl + 1; - count = thread->count_for_thread(yl, count); - if (count <= 0) - return; - - const uint32_t *fg2rgb = _srcblend; - const uint32_t *bg2rgb = _destblend; - dest = ylookup[yl + thread->skipped_by_thread(yl)] + sx + _destorg; - source = &thread->dc_temp[thread->temp_line_for_thread(yl)*4]; - pitch = _pitch * thread->num_cores; - colormap = _colormap; - - do { - uint32_t a = (bg2rgb[dest[0]] | 0x40100400) - fg2rgb[colormap[source[0]]]; - uint32_t b = a; - - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[0] = RGB32k.All[(a>>15) & a]; - - a = (bg2rgb[dest[1]] | 0x40100400) - fg2rgb[colormap[source[1]]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[1] = RGB32k.All[(a>>15) & a]; - - a = (bg2rgb[dest[2]] | 0x40100400) - fg2rgb[colormap[source[2]]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[2] = RGB32k.All[(a>>15) & a]; - - a = (bg2rgb[dest[3]] | 0x40100400) - fg2rgb[colormap[source[3]]]; - b = a; - b &= 0x40100400; - b = b - (b >> 5); - a &= b; - a |= 0x01f07c1f; - dest[3] = RGB32k.All[(a>>15) & a]; - - source += 4; - dest += pitch; - } while (--count); - } -} diff --git a/src/r_main.cpp b/src/r_main.cpp index 7030339c7..a83b2f190 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -40,6 +40,7 @@ #include "r_segs.h" #include "r_3dfloors.h" #include "r_sky.h" +#include "r_draw_rgba.h" #include "st_stuff.h" #include "c_cvars.h" #include "c_dispatch.h" @@ -58,23 +59,12 @@ #include "v_font.h" #include "r_data/colormaps.h" #include "p_maputl.h" -#include "r_thread.h" +#include "p_setup.h" +#include "version.h" CVAR (String, r_viewsize, "", CVAR_NOSET) CVAR (Bool, r_shadercolormaps, true, CVAR_ARCHIVE) -CUSTOM_CVAR (Int, r_columnmethod, 1, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) -{ - if (self != 0 && self != 1) - { - self = 1; - } - else - { // Trigger the change - setsizeneeded = true; - } -} - CVAR(Int, r_portal_recursions, 4, CVAR_ARCHIVE) CVAR(Bool, r_highlight_portals, false, CVAR_ARCHIVE) @@ -85,11 +75,8 @@ extern cycle_t FrameCycles; extern bool r_showviewer; -cycle_t WallCycles, PlaneCycles, MaskedCycles, WallScanCycles; - namespace swrenderer { - using namespace drawerargs; // MACROS ------------------------------------------------------------------ @@ -131,6 +118,8 @@ bool r_dontmaplines; // PUBLIC DATA DEFINITIONS ------------------------------------------------- +bool r_swtruecolor; + double r_BaseVisibility; double r_WallVisibility; double r_FloorVisibility; @@ -144,7 +133,7 @@ double FocalLengthX; double FocalLengthY; FDynamicColormap*basecolormap; // [RH] colormap currently drawing with int fixedlightlev; -lighttable_t *fixedcolormap; +FSWColormap *fixedcolormap; FSpecialColormap *realfixedcolormap; double WallTMapScale2; @@ -180,10 +169,7 @@ void (*fuzzcolfunc) (void); void (*transcolfunc) (void); void (*spanfunc) (void); -void (*hcolfunc_pre) (void); -void (*hcolfunc_post1) (int hx, int sx, int yl, int yh); -void (*hcolfunc_post2) (int hx, int sx, int yl, int yh); -void (*hcolfunc_post4) (int sx, int yl, int yh); +cycle_t WallCycles, PlaneCycles, MaskedCycles, WallScanCycles; // PRIVATE DATA DEFINITIONS ------------------------------------------------ @@ -402,16 +388,6 @@ void R_InitRenderer() R_InitPlanes (); R_InitShadeMaps(); R_InitColumnDrawers (); - - colfunc = basecolfunc = R_DrawColumn; - fuzzcolfunc = R_DrawFuzzColumn; - transcolfunc = R_DrawTranslatedColumn; - spanfunc = R_DrawSpan; - - // [RH] Horizontal column drawers - hcolfunc_pre = R_DrawColumnHoriz; - hcolfunc_post1 = rt_map1col; - hcolfunc_post4 = rt_map4cols; } //========================================================================== @@ -472,16 +448,16 @@ void R_SetupColormap(player_t *player) if (player->fixedcolormap >= 0 && player->fixedcolormap < (int)SpecialColormaps.Size()) { realfixedcolormap = &SpecialColormaps[player->fixedcolormap]; - if (RenderTarget == screen && (DFrameBuffer *)screen->Accel2D && r_shadercolormaps) + if (RenderTarget == screen && (r_swtruecolor || ((DFrameBuffer *)screen->Accel2D && r_shadercolormaps))) { // Render everything fullbright. The copy to video memory will // apply the special colormap, so it won't be restricted to the // palette. - fixedcolormap = realcolormaps; + fixedcolormap = &realcolormaps; } else { - fixedcolormap = SpecialColormaps[player->fixedcolormap].Colormap; + fixedcolormap = &SpecialColormaps[player->fixedcolormap]; } } else if (player->fixedlightlevel >= 0 && player->fixedlightlevel < NUMCOLORMAPS) @@ -490,14 +466,14 @@ void R_SetupColormap(player_t *player) // [SP] Emulate GZDoom's light-amp goggles. if (r_fullbrightignoresectorcolor && fixedlightlev >= 0) { - fixedcolormap = FullNormalLight.Maps; + fixedcolormap = &FullNormalLight; } } } // [RH] Inverse light for shooting the Sigil if (fixedcolormap == NULL && extralight == INT_MIN) { - fixedcolormap = SpecialColormaps[INVERSECOLORMAP].Colormap; + fixedcolormap = &SpecialColormaps[INVERSECOLORMAP]; extralight = 0; } } @@ -583,6 +559,9 @@ void R_HighlightPortal (PortalDrawseg* pds) // [ZZ] NO OVERFLOW CHECKS HERE // I believe it won't break. if it does, blame me. :( + if (r_swtruecolor) // Assuming this is just a debug function + return; + BYTE color = (BYTE)BestColor((DWORD *)GPalette.BaseColors, 255, 0, 0, 0, 255); BYTE* pixels = RenderTarget->GetBuffer(); @@ -630,12 +609,26 @@ void R_EnterPortal (PortalDrawseg* pds, int depth) int Ytop = pds->ceilingclip[x-pds->x1]; int Ybottom = pds->floorclip[x-pds->x1]; - BYTE *dest = RenderTarget->GetBuffer() + x + Ytop * spacing; - - for (int y = Ytop; y <= Ybottom; y++) + if (r_swtruecolor) { - *dest = color; - dest += spacing; + uint32_t *dest = (uint32_t*)RenderTarget->GetBuffer() + x + Ytop * spacing; + + uint32_t c = GPalette.BaseColors[color].d; + for (int y = Ytop; y <= Ybottom; y++) + { + *dest = c; + dest += spacing; + } + } + else + { + BYTE *dest = RenderTarget->GetBuffer() + x + Ytop * spacing; + + for (int y = Ytop; y <= Ybottom; y++) + { + *dest = color; + dest += spacing; + } } } @@ -801,10 +794,13 @@ void R_EnterPortal (PortalDrawseg* pds, int depth) void R_SetupBuffer () { + using namespace drawerargs; + static BYTE *lastbuff = NULL; int pitch = RenderTarget->GetPitch(); - BYTE *lineptr = RenderTarget->GetBuffer() + viewwindowy*pitch + viewwindowx; + int pixelsize = r_swtruecolor ? 4 : 1; + BYTE *lineptr = RenderTarget->GetBuffer() + (viewwindowy*pitch + viewwindowx) * pixelsize; if (dc_pitch != pitch || lineptr != lastbuff) { @@ -814,6 +810,7 @@ void R_SetupBuffer () R_InitFuzzTable (pitch); } dc_destorg = lineptr; + dc_destheight = RenderTarget->GetHeight() - viewwindowy; for (int i = 0; i < RenderTarget->GetHeight(); i++) { ylookup[i] = i * pitch; @@ -851,17 +848,11 @@ void R_RenderActorView (AActor *actor, bool dontmaplines) // [RH] Show off segs if r_drawflat is 1 if (r_drawflat) { - hcolfunc_pre = R_FillColumnHoriz; - hcolfunc_post1 = rt_copy1col; - hcolfunc_post4 = rt_copy4cols; colfunc = R_FillColumn; spanfunc = R_FillSpan; } else { - hcolfunc_pre = R_DrawColumnHoriz; - hcolfunc_post1 = rt_map1col; - hcolfunc_post4 = rt_map4cols; colfunc = basecolfunc; spanfunc = R_DrawSpan; } @@ -890,7 +881,7 @@ void R_RenderActorView (AActor *actor, bool dontmaplines) // Link the polyobjects right before drawing the scene to reduce the amounts of calls to this function PO_LinkToSubsectors(); InSubsector = NULL; - R_RenderBSPNode (nodes + numnodes - 1); // The head node is the last node output. + R_RenderBSPNode(nodes + numnodes - 1); // The head node is the last node output. R_3D_ResetClip(); // reset clips (floor/ceiling) camera->renderflags = savedflags; WallCycles.Unclock(); @@ -900,8 +891,8 @@ void R_RenderActorView (AActor *actor, bool dontmaplines) if (viewactive) { PlaneCycles.Clock(); - R_DrawPlanes (); - R_DrawPortals (); + R_DrawPlanes(); + R_DrawPortals(); PlaneCycles.Unclock(); // [RH] Walk through mirrors @@ -929,7 +920,7 @@ void R_RenderActorView (AActor *actor, bool dontmaplines) // If we don't want shadered colormaps, NULL it now so that the // copy to the screen does not use a special colormap shader. - if (!r_shadercolormaps) + if (!r_shadercolormaps && !r_swtruecolor) { realfixedcolormap = NULL; } @@ -947,7 +938,14 @@ void R_RenderViewToCanvas (AActor *actor, DCanvas *canvas, int x, int y, int width, int height, bool dontmaplines) { const bool savedviewactive = viewactive; + const bool savedoutputformat = r_swtruecolor; + if (r_swtruecolor != canvas->IsBgra()) + { + r_swtruecolor = canvas->IsBgra(); + R_InitColumnDrawers(); + } + R_BeginDrawerCommands(); viewwidth = width; @@ -969,7 +967,14 @@ void R_RenderViewToCanvas (AActor *actor, DCanvas *canvas, screen->Lock (true); R_SetupBuffer (); screen->Unlock (); + viewactive = savedviewactive; + r_swtruecolor = savedoutputformat; + + if (r_swtruecolor != canvas->IsBgra()) + { + R_InitColumnDrawers(); + } } //========================================================================== @@ -1073,4 +1078,4 @@ CCMD (clearscancycles) } #endif -} \ No newline at end of file +} diff --git a/src/r_main.h b/src/r_main.h index be1c36306..daf60c16d 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -85,9 +85,16 @@ extern bool r_dontmaplines; // Change R_CalcTiltedLighting() when this changes. #define GETPALOOKUP(vis,shade) (clamp (((shade)-FLOAT2FIXED(MIN(MAXLIGHTVIS,double(vis))))>>FRACBITS, 0, NUMCOLORMAPS-1)) +// Calculate the light multiplier for dc_light/ds_light +// This is used instead of GETPALOOKUP when ds_colormap/dc_colormap is set to the base colormap +// Returns a value between 0 and 1 in fixed point +#define LIGHTSCALE(vis,shade) FLOAT2FIXED(clamp((FIXED2DBL(shade) - (MIN(MAXLIGHTVIS,double(vis)))) / NUMCOLORMAPS, 0.0, (NUMCOLORMAPS-1)/(double)NUMCOLORMAPS)) + // Converts fixedlightlev into a shade value #define FIXEDLIGHT2SHADE(lightlev) (((lightlev) >> COLORMAPSHIFT) << FRACBITS) +extern bool r_swtruecolor; + extern double GlobVis; void R_SetVisibility(double visibility); @@ -102,7 +109,7 @@ extern double r_SpriteVisibility; extern int r_actualextralight; extern bool foggy; extern int fixedlightlev; -extern lighttable_t* fixedcolormap; +extern FSWColormap* fixedcolormap; extern FSpecialColormap*realfixedcolormap; @@ -117,13 +124,6 @@ extern void (*transcolfunc) (void); // No shadow effects on floors. extern void (*spanfunc) (void); -// [RH] Function pointers for the horizontal column drawers. -extern void (*hcolfunc_pre) (void); -extern void (*hcolfunc_post1) (int hx, int sx, int yl, int yh); -extern void (*hcolfunc_post2) (int hx, int sx, int yl, int yh); -extern void (*hcolfunc_post4) (int sx, int yl, int yh); - - void R_InitTextureMapping (); diff --git a/src/r_plane.cpp b/src/r_plane.cpp index 64433b6d4..fce565922 100644 --- a/src/r_plane.cpp +++ b/src/r_plane.cpp @@ -58,11 +58,14 @@ #include "r_3dfloors.h" #include "v_palette.h" #include "r_data/colormaps.h" +#include "r_draw_rgba.h" +#include "gl/dynlights/gl_dynlight.h" #ifdef _MSC_VER #pragma warning(disable:4244) #endif +CVAR(Bool, r_linearsky, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); CVAR(Bool, tilt, false, 0); CVAR(Bool, r_skyboxes, true, 0) @@ -237,12 +240,78 @@ void R_MapPlane (int y, int x1) ds_yfrac = 0; } + if (r_swtruecolor) + { + double distance2 = planeheight * yslope[(y + 1 < viewheight) ? y + 1 : y - 1]; + double xmagnitude = fabs(ystepscale * (distance2 - distance) * FocalLengthX); + double ymagnitude = fabs(xstepscale * (distance2 - distance) * FocalLengthX); + double magnitude = MAX(ymagnitude, xmagnitude); + double min_lod = -1000.0; + ds_lod = MAX(log2(magnitude) + r_lod_bias, min_lod); + } + if (plane_shade) { // Determine lighting based on the span's distance from the viewer. R_SetDSColorMapLight(basecolormap, GlobVis * fabs(CenterY - y), planeshade); } + if (r_dynlights) + { + // Find row position in view space + float zspan = planeheight / (fabs(y + 0.5 - CenterY) / InvZtoScale); + dc_viewpos.X = (float)((x1 + 0.5 - CenterX) / CenterX * zspan); + dc_viewpos.Y = zspan; + dc_viewpos.Z = (float)((CenterY - y - 0.5) / InvZtoScale * zspan); + dc_viewpos_step.X = (float)(zspan / CenterX); + + static TriLight lightbuffer[64 * 1024]; + static int nextlightindex = 0; + + // Setup lights for column + dc_num_lights = 0; + dc_lights = lightbuffer + nextlightindex; + visplane_light *cur_node = ds_light_list; + while (cur_node && nextlightindex < 64 * 1024) + { + double lightX = cur_node->lightsource->X() - ViewPos.X; + double lightY = cur_node->lightsource->Y() - ViewPos.Y; + double lightZ = cur_node->lightsource->Z() - ViewPos.Z; + + float lx = (float)(lightX * ViewSin - lightY * ViewCos); + float ly = (float)(lightX * ViewTanCos + lightY * ViewTanSin) - dc_viewpos.Y; + float lz = (float)lightZ - dc_viewpos.Z; + + // Precalculate the constant part of the dot here so the drawer doesn't have to. + float lconstant = ly * ly + lz * lz; + + // Include light only if it touches this row + float radius = cur_node->lightsource->GetRadius(); + if (radius * radius >= lconstant) + { + uint32_t red = cur_node->lightsource->GetRed(); + uint32_t green = cur_node->lightsource->GetGreen(); + uint32_t blue = cur_node->lightsource->GetBlue(); + + nextlightindex++; + auto &light = dc_lights[dc_num_lights++]; + light.x = lx; + light.y = lconstant; + light.radius = 256.0f / radius; + light.color = (red << 16) | (green << 8) | blue; + } + + cur_node = cur_node->next; + } + + if (nextlightindex == 64 * 1024) + nextlightindex = 0; + } + else + { + dc_num_lights = 0; + } + ds_y = y; ds_x1 = x1; ds_x2 = x2; @@ -272,6 +341,50 @@ void R_MapColoredPlane(int y, int x1) R_DrawColoredSpan(y, x1, spanend[y]); } +//========================================================================== + +namespace +{ + enum { max_plane_lights = 32 * 1024 }; + visplane_light plane_lights[max_plane_lights]; + int next_plane_light = 0; +} + +void R_AddPlaneLights(visplane_t *plane, FLightNode *node) +{ + if (!r_dynlights) + return; + + while (node) + { + if (!(node->lightsource->flags2&MF2_DORMANT)) + { + bool found = false; + visplane_light *light_node = plane->lights; + while (light_node) + { + if (light_node->lightsource == node->lightsource) + { + found = true; + break; + } + light_node = light_node->next; + } + if (!found) + { + if (next_plane_light == max_plane_lights) + return; + + visplane_light *newlight = &plane_lights[next_plane_light++]; + newlight->next = plane->lights; + newlight->lightsource = node->lightsource; + plane->lights = newlight; + } + } + node = node->nextLight; + } +} + //========================================================================== // // R_ClearPlanes @@ -324,6 +437,8 @@ void R_ClearPlanes (bool fullclear) ? (ConBottom - viewwindowy) : 0); lastopening = 0; + + next_plane_light = 0; } } @@ -351,6 +466,8 @@ static visplane_t *new_visplane (unsigned hash) freehead = &freetail; } + check->lights = nullptr; + check->next = visplanes[hash]; visplanes[hash] = check; return check; @@ -574,6 +691,7 @@ visplane_t *R_CheckPlane (visplane_t *pl, int start, int stop) new_pl->CurrentPortalUniq = pl->CurrentPortalUniq; new_pl->MirrorFlags = pl->MirrorFlags; new_pl->CurrentSkybox = pl->CurrentSkybox; + new_pl->lights = pl->lights; pl = new_pl; pl->left = start; pl->right = stop; @@ -625,61 +743,137 @@ extern FTexture *rw_pic; // Allow for layer skies up to 512 pixels tall. This is overkill, // since the most anyone can ever see of the sky is 500 pixels. // We need 4 skybufs because R_DrawSkySegment can draw up to 4 columns at a time. +// Need two versions - one for true color and one for palette +#define MAXSKYBUF 3072 static BYTE skybuf[4][512]; +static uint32_t skybuf_bgra[MAXSKYBUF][512]; static DWORD lastskycol[4]; +static DWORD lastskycol_bgra[MAXSKYBUF]; static int skycolplace; +static int skycolplace_bgra; + // Get a column of sky when there is only one sky texture. static const BYTE *R_GetOneSkyColumn (FTexture *fronttex, int x) { - angle_t column = (skyangle + xtoviewangle[x]) ^ skyflip; - return fronttex->GetColumn((UMulScale16(column, frontcyl) + frontpos) >> FRACBITS, NULL); + int tx; + if (r_linearsky) + { + angle_t xangle = (angle_t)((0.5 - x / (double)viewwidth) * FocalTangent * ANGLE_90); + angle_t column = (skyangle + xangle) ^ skyflip; + tx = (UMulScale16(column, frontcyl) + frontpos) >> FRACBITS; + } + else + { + angle_t column = (skyangle + xtoviewangle[x]) ^ skyflip; + tx = (UMulScale16(column, frontcyl) + frontpos) >> FRACBITS; + } + + if (!r_swtruecolor) + return fronttex->GetColumn(tx, NULL); + else + { + return (const BYTE *)fronttex->GetColumnBgra(tx, NULL); + } } // Get a column of sky when there are two overlapping sky textures static const BYTE *R_GetTwoSkyColumns (FTexture *fronttex, int x) { - DWORD ang = (skyangle + xtoviewangle[x]) ^ skyflip; - DWORD angle1 = (DWORD)((UMulScale16(ang, frontcyl) + frontpos) >> FRACBITS); - DWORD angle2 = (DWORD)((UMulScale16(ang, backcyl) + backpos) >> FRACBITS); + DWORD ang, angle1, angle2; + + if (r_linearsky) + { + angle_t xangle = (angle_t)((0.5 - x / (double)viewwidth) * FocalTangent * ANGLE_90); + ang = (skyangle + xangle) ^ skyflip; + } + else + { + ang = (skyangle + xtoviewangle[x]) ^ skyflip; + } + angle1 = (DWORD)((UMulScale16(ang, frontcyl) + frontpos) >> FRACBITS); + angle2 = (DWORD)((UMulScale16(ang, backcyl) + backpos) >> FRACBITS); // Check if this column has already been built. If so, there's // no reason to waste time building it again. DWORD skycol = (angle1 << 16) | angle2; int i; - for (i = 0; i < 4; ++i) + if (!r_swtruecolor) { - if (lastskycol[i] == skycol) + for (i = 0; i < 4; ++i) { - return skybuf[i]; + if (lastskycol[i] == skycol) + { + return skybuf[i]; + } } + + lastskycol[skycolplace] = skycol; + BYTE *composite = skybuf[skycolplace]; + skycolplace = (skycolplace + 1) & 3; + + // The ordering of the following code has been tuned to allow VC++ to optimize + // it well. In particular, this arrangement lets it keep count in a register + // instead of on the stack. + const BYTE *front = fronttex->GetColumn(angle1, NULL); + const BYTE *back = backskytex->GetColumn(angle2, NULL); + + int count = MIN(512, MIN(backskytex->GetHeight(), fronttex->GetHeight())); + i = 0; + do + { + if (front[i]) + { + composite[i] = front[i]; + } + else + { + composite[i] = back[i]; + } + } while (++i, --count); + return composite; } - - lastskycol[skycolplace] = skycol; - BYTE *composite = skybuf[skycolplace]; - skycolplace = (skycolplace + 1) & 3; - - // The ordering of the following code has been tuned to allow VC++ to optimize - // it well. In particular, this arrangement lets it keep count in a register - // instead of on the stack. - const BYTE *front = fronttex->GetColumn (angle1, NULL); - const BYTE *back = backskytex->GetColumn (angle2, NULL); - - int count = MIN (512, MIN (backskytex->GetHeight(), fronttex->GetHeight())); - i = 0; - do + else { - if (front[i]) + //return R_GetOneSkyColumn(fronttex, x); + for (i = skycolplace_bgra - 4; i < skycolplace_bgra; ++i) { - composite[i] = front[i]; + int ic = (i % MAXSKYBUF); // i "checker" - can wrap around the ends of the array + if (lastskycol_bgra[ic] == skycol) + { + return (BYTE*)(skybuf_bgra[ic]); + } } - else + + lastskycol_bgra[skycolplace_bgra] = skycol; + uint32_t *composite = skybuf_bgra[skycolplace_bgra]; + skycolplace_bgra = (skycolplace_bgra + 1) % MAXSKYBUF; + + // The ordering of the following code has been tuned to allow VC++ to optimize + // it well. In particular, this arrangement lets it keep count in a register + // instead of on the stack. + const uint32_t *front = (const uint32_t *)fronttex->GetColumnBgra(angle1, NULL); + const uint32_t *back = (const uint32_t *)backskytex->GetColumnBgra(angle2, NULL); + + //[SP] Paletted version is used for comparison only + const BYTE *frontcompare = fronttex->GetColumn(angle1, NULL); + + int count = MIN(512, MIN(backskytex->GetHeight(), fronttex->GetHeight())); + i = 0; + do { - composite[i] = back[i]; - } - } while (++i, --count); - return composite; + if (frontcompare[i]) + { + composite[i] = front[i]; + } + else + { + composite[i] = back[i]; + } + } while (++i, --count); + return (BYTE*)composite; + } } static void R_DrawSkyColumnStripe(int start_x, int y1, int y2, int columns, double scale, double texturemid, double yrepeat) @@ -701,12 +895,28 @@ static void R_DrawSkyColumnStripe(int start_x, int y1, int y2, int columns, doub DWORD ang, angle1, angle2; - ang = (skyangle + xtoviewangle[x]) ^ skyflip; + if (r_linearsky) + { + angle_t xangle = (angle_t)((0.5 - x / (double)viewwidth) * FocalTangent * ANGLE_90); + ang = (skyangle + xangle) ^ skyflip; + } + else + { + ang = (skyangle + xtoviewangle[x]) ^ skyflip; + } angle1 = (DWORD)((UMulScale16(ang, frontcyl) + frontpos) >> FRACBITS); angle2 = (DWORD)((UMulScale16(ang, backcyl) + backpos) >> FRACBITS); - dc_wall_source[i] = (const BYTE *)frontskytex->GetColumn(angle1, nullptr); - dc_wall_source2[i] = backskytex ? (const BYTE *)backskytex->GetColumn(angle2, nullptr) : nullptr; + if (r_swtruecolor) + { + dc_wall_source[i] = (const BYTE *)frontskytex->GetColumnBgra(angle1, nullptr); + dc_wall_source2[i] = backskytex ? (const BYTE *)backskytex->GetColumnBgra(angle2, nullptr) : nullptr; + } + else + { + dc_wall_source[i] = (const BYTE *)frontskytex->GetColumn(angle1, nullptr); + dc_wall_source2[i] = backskytex ? (const BYTE *)backskytex->GetColumn(angle2, nullptr) : nullptr; + } dc_wall_iscale[i] = uv_step; dc_wall_texturefrac[i] = uv_pos; @@ -714,7 +924,8 @@ static void R_DrawSkyColumnStripe(int start_x, int y1, int y2, int columns, doub dc_wall_sourceheight[0] = height; dc_wall_sourceheight[1] = backskytex ? backskytex->GetHeight() : height; - dc_dest = (ylookup[y1] + start_x) + dc_destorg; + int pixelsize = r_swtruecolor ? 4 : 1; + dc_dest = (ylookup[y1] + start_x) * pixelsize + dc_destorg; dc_count = y2 - y1; uint32_t solid_top = frontskytex->GetSkyCapColor(false); @@ -877,6 +1088,7 @@ static void R_DrawSky (visplane_t *pl) for (x = 0; x < 4; ++x) { lastskycol[x] = 0xffffffff; + lastskycol_bgra[x] = 0xffffffff; } rw_pic = frontskytex; @@ -890,6 +1102,7 @@ static void R_DrawSky (visplane_t *pl) for (x = 0; x < 4; ++x) { lastskycol[x] = 0xffffffff; + lastskycol_bgra[x] = 0xffffffff; } R_DrawSkySegment (pl, (short *)pl->top, (short *)pl->bottom, swall, lwall, frontyScale, backskytex == NULL ? R_GetOneSkyColumn : R_GetTwoSkyColumns); @@ -927,6 +1140,7 @@ static void R_DrawSkyStriped (visplane_t *pl) for (x = 0; x < 4; ++x) { lastskycol[x] = 0xffffffff; + lastskycol_bgra[x] = 0xffffffff; } R_DrawSkySegment (pl, top, bot, swall, lwall, rw_pic->Scale.Y, backskytex == NULL ? R_GetOneSkyColumn : R_GetTwoSkyColumns); @@ -944,6 +1158,7 @@ static void R_DrawSkyStriped (visplane_t *pl) // //========================================================================== + int R_DrawPlanes () { visplane_t *pl; @@ -1409,7 +1624,7 @@ void R_DrawSkyPlane (visplane_t *pl) else { fakefixed = true; - fixedcolormap = NormalLight.Maps; + fixedcolormap = &NormalLight; R_SetColorMapLight(fixedcolormap, 0, 0); } @@ -1511,12 +1726,16 @@ void R_DrawNormalPlane (visplane_t *pl, double _xscale, double _yscale, fixed_t spanfunc = R_DrawSpanMaskedTranslucent; dc_srcblend = Col2RGB8[alpha>>10]; dc_destblend = Col2RGB8[(OPAQUE-alpha)>>10]; + dc_srcalpha = alpha; + dc_destalpha = OPAQUE - alpha; } else { spanfunc = R_DrawSpanMaskedAddClamp; dc_srcblend = Col2RGB8_LessPrecision[alpha>>10]; dc_destblend = Col2RGB8_LessPrecision[FRACUNIT>>10]; + dc_srcalpha = alpha; + dc_destalpha = FRACUNIT; } } else @@ -1533,12 +1752,16 @@ void R_DrawNormalPlane (visplane_t *pl, double _xscale, double _yscale, fixed_t spanfunc = R_DrawSpanTranslucent; dc_srcblend = Col2RGB8[alpha>>10]; dc_destblend = Col2RGB8[(OPAQUE-alpha)>>10]; + dc_srcalpha = alpha; + dc_destalpha = OPAQUE - alpha; } else { spanfunc = R_DrawSpanAddClamp; dc_srcblend = Col2RGB8_LessPrecision[alpha>>10]; dc_destblend = Col2RGB8_LessPrecision[FRACUNIT>>10]; + dc_srcalpha = alpha; + dc_destalpha = FRACUNIT; } } else @@ -1698,6 +1921,8 @@ void R_MapVisPlane (visplane_t *pl, void (*mapfunc)(int y, int x1)) int t2 = pl->top[x]; int b2 = pl->bottom[x]; + ds_light_list = pl->lights; + if (b2 > t2) { fillshort (spanend+t2, b2-t2, x); @@ -1744,6 +1969,8 @@ void R_MapVisPlane (visplane_t *pl, void (*mapfunc)(int y, int x1)) { mapfunc (--b2, pl->left); } + + ds_light_list = nullptr; } //========================================================================== diff --git a/src/r_plane.h b/src/r_plane.h index 0e133a7cd..740020209 100644 --- a/src/r_plane.h +++ b/src/r_plane.h @@ -26,10 +26,18 @@ #include class ASkyViewpoint; +class ADynamicLight; +struct FLightNode; namespace swrenderer { +struct visplane_light +{ + ADynamicLight *lightsource; + visplane_light *next; +}; + // // The infamous visplane // @@ -39,6 +47,7 @@ struct visplane_s FDynamicColormap *colormap; // [RH] Support multiple colormaps FSectorPortal *portal; // [RH] Support sky boxes + visplane_light *lights; FTransform xform; secplane_t height; @@ -89,6 +98,8 @@ void R_InitPlanes (); void R_DeinitPlanes (); void R_ClearPlanes (bool fullclear); +void R_AddPlaneLights(visplane_t *plane, FLightNode *light_head); + int R_DrawPlanes (); void R_DrawPortals (); void R_DrawSkyPlane (visplane_t *pl); diff --git a/src/r_poly.cpp b/src/r_poly.cpp new file mode 100644 index 000000000..f7fa33979 --- /dev/null +++ b/src/r_poly.cpp @@ -0,0 +1,184 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_data/r_interpolate.h" +#include "r_poly.h" +#include "gl/data/gl_data.h" +#include "d_net.h" +#include "po_man.h" + +EXTERN_CVAR(Int, screenblocks) +void InitGLRMapinfoData(); +extern bool r_showviewer; + +///////////////////////////////////////////////////////////////////////////// + +PolyRenderer *PolyRenderer::Instance() +{ + static PolyRenderer scene; + return &scene; +} + +void PolyRenderer::RenderViewToCanvas(AActor *actor, DCanvas *canvas, int x, int y, int width, int height, bool dontmaplines) +{ + const bool savedviewactive = viewactive; + const bool savedoutputformat = swrenderer::r_swtruecolor; + + viewwidth = width; + RenderTarget = canvas; + swrenderer::bRenderingToCanvas = true; + R_SetWindow(12, width, height, height, true); + viewwindowx = x; + viewwindowy = y; + viewactive = true; + swrenderer::r_swtruecolor = canvas->IsBgra(); + + canvas->Lock(true); + + RenderActorView(actor, dontmaplines); + + canvas->Unlock(); + + RenderTarget = screen; + swrenderer::bRenderingToCanvas = false; + R_ExecuteSetViewSize(); + viewactive = savedviewactive; + swrenderer::r_swtruecolor = savedoutputformat; +} + +void PolyRenderer::RenderActorView(AActor *actor, bool dontmaplines) +{ + NetUpdate(); + + DontMapLines = dontmaplines; + + P_FindParticleSubsectors(); + PO_LinkToSubsectors(); + R_SetupFrame(actor); + + ActorRenderFlags savedflags = camera->renderflags; + // Never draw the player unless in chasecam mode + if (!r_showviewer) + camera->renderflags |= RF_INVISIBLE; + + R_BeginDrawerCommands(); + + ClearBuffers(); + SetSceneViewport(); + SetupPerspectiveMatrix(); + MainPortal.SetViewpoint(WorldToClip, Vec4f(0.0f, 0.0f, 0.0f, 1.0f), GetNextStencilValue()); + MainPortal.Render(0); + Skydome.Render(WorldToClip); + MainPortal.RenderTranslucent(0); + PlayerSprites.Render(); + + camera->renderflags = savedflags; + interpolator.RestoreInterpolations (); + + NetUpdate(); + + R_EndDrawerCommands(); + + NetUpdate(); +} + +void PolyRenderer::RenderRemainingPlayerSprites() +{ + PlayerSprites.RenderRemainingSprites(); +} + +void PolyRenderer::ClearBuffers() +{ + PolyVertexBuffer::Clear(); + PolyStencilBuffer::Instance()->Clear(RenderTarget->GetWidth(), RenderTarget->GetHeight(), 0); + PolySubsectorGBuffer::Instance()->Resize(RenderTarget->GetPitch(), RenderTarget->GetHeight()); + NextStencilValue = 0; + SeenLinePortals.clear(); + SeenMirrors.clear(); +} + +void PolyRenderer::SetSceneViewport() +{ + if (RenderTarget == screen) // Rendering to screen + { + int height; + if (screenblocks >= 10) + height = SCREENHEIGHT; + else + height = (screenblocks*SCREENHEIGHT / 10) & ~7; + + int bottom = SCREENHEIGHT - (height + viewwindowy - ((height - viewheight) / 2)); + PolyTriangleDrawer::set_viewport(viewwindowx, SCREENHEIGHT - bottom - height, viewwidth, height, RenderTarget); + } + else // Rendering to camera texture + { + PolyTriangleDrawer::set_viewport(0, 0, RenderTarget->GetWidth(), RenderTarget->GetHeight(), RenderTarget); + } +} + +void PolyRenderer::SetupPerspectiveMatrix() +{ + static bool bDidSetup = false; + + if (!bDidSetup) + { + InitGLRMapinfoData(); + bDidSetup = true; + } + + // Code provided courtesy of Graf Zahl. Now we just have to plug it into the viewmatrix code... + // We have to scale the pitch to account for the pixel stretching, because the playsim doesn't know about this and treats it as 1:1. + double radPitch = ViewPitch.Normalized180().Radians(); + double angx = cos(radPitch); + double angy = sin(radPitch) * glset.pixelstretch; + double alen = sqrt(angx*angx + angy*angy); + float adjustedPitch = (float)asin(angy / alen); + float adjustedViewAngle = (float)(ViewAngle - 90).Radians(); + + float ratio = WidescreenRatio; + float fovratio = (WidescreenRatio >= 1.3f) ? 1.333333f : ratio; + float fovy = (float)(2 * DAngle::ToDegrees(atan(tan(FieldOfView.Radians() / 2) / fovratio)).Degrees); + + TriMatrix worldToView = + TriMatrix::rotate(adjustedPitch, 1.0f, 0.0f, 0.0f) * + TriMatrix::rotate(adjustedViewAngle, 0.0f, -1.0f, 0.0f) * + TriMatrix::scale(1.0f, glset.pixelstretch, 1.0f) * + TriMatrix::swapYZ() * + TriMatrix::translate((float)-ViewPos.X, (float)-ViewPos.Y, (float)-ViewPos.Z); + + WorldToClip = TriMatrix::perspective(fovy, ratio, 5.0f, 65535.0f) * worldToView; +} + +bool PolyRenderer::InsertSeenLinePortal(FLinePortal *portal) +{ + return SeenLinePortals.insert(portal).second; +} + +bool PolyRenderer::InsertSeenMirror(line_t *mirrorLine) +{ + return SeenMirrors.insert(mirrorLine).second; +} diff --git a/src/r_poly.h b/src/r_poly.h new file mode 100644 index 000000000..10d2e92aa --- /dev/null +++ b/src/r_poly.h @@ -0,0 +1,68 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include +#include +#include +#include +#include "doomdata.h" +#include "r_utility.h" +#include "r_main.h" +#include "r_poly_portal.h" +#include "r_poly_playersprite.h" +#include "r_poly_sky.h" + +class AActor; +class DCanvas; + +class PolyRenderer +{ +public: + void RenderViewToCanvas(AActor *actor, DCanvas *canvas, int x, int y, int width, int height, bool dontmaplines); + void RenderActorView(AActor *actor, bool dontmaplines); + void RenderRemainingPlayerSprites(); + + static PolyRenderer *Instance(); + + uint32_t GetNextStencilValue() { uint32_t value = NextStencilValue; NextStencilValue += 2; return value; } + + bool InsertSeenLinePortal(FLinePortal *portal); + bool InsertSeenMirror(line_t *mirrorLine); + + bool DontMapLines = false; + +private: + void ClearBuffers(); + void SetSceneViewport(); + void SetupPerspectiveMatrix(); + + TriMatrix WorldToClip; + RenderPolyScene MainPortal; + PolySkyDome Skydome; + RenderPolyPlayerSprites PlayerSprites; + uint32_t NextStencilValue = 0; + + std::set SeenLinePortals; + std::set SeenMirrors; +}; diff --git a/src/r_poly_cull.cpp b/src/r_poly_cull.cpp new file mode 100644 index 000000000..02a0f2fc5 --- /dev/null +++ b/src/r_poly_cull.cpp @@ -0,0 +1,311 @@ +/* +** Potential visible set (PVS) handling +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_cull.h" +#include "r_poly.h" + +void PolyCull::CullScene(const TriMatrix &worldToClip, const Vec4f &portalClipPlane) +{ + PvsSectors.clear(); + frustumPlanes = FrustumPlanes(worldToClip); + PortalClipPlane = portalClipPlane; + + // Cull front to back + MaxCeilingHeight = 0.0; + MinFloorHeight = 0.0; + if (numnodes == 0) + CullSubsector(subsectors); + else + CullNode(nodes + numnodes - 1); // The head node is the last node output. +} + +void PolyCull::CullNode(void *node) +{ + while (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + + // Decide which side the view point is on. + int side = PointOnSide(ViewPos, bsp); + + // Recursively divide front space (toward the viewer). + CullNode(bsp->children[side]); + + // Possibly divide back space (away from the viewer). + side ^= 1; + + if (!CheckBBox(bsp->bbox[side])) + return; + + node = bsp->children[side]; + } + + subsector_t *sub = (subsector_t *)((BYTE *)node - 1); + CullSubsector(sub); +} + +void PolyCull::CullSubsector(subsector_t *sub) +{ + // Update sky heights for the scene + MaxCeilingHeight = MAX(MaxCeilingHeight, sub->sector->ceilingplane.Zat0()); + MinFloorHeight = MIN(MinFloorHeight, sub->sector->floorplane.Zat0()); + + // Mark that we need to render this + PvsSectors.push_back(sub); + + // Update culling info for further bsp clipping + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + if ((line->sidedef == nullptr || !(line->sidedef->Flags & WALLF_POLYOBJ)) && line->backsector == nullptr) + { + // Skip lines not facing viewer + DVector2 pt1 = line->v1->fPos() - ViewPos; + DVector2 pt2 = line->v2->fPos() - ViewPos; + if (pt1.Y * (pt1.X - pt2.X) + pt1.X * (pt2.Y - pt1.Y) >= 0) + continue; + + int sx1, sx2; + if (GetSegmentRangeForLine(line->v1->fX(), line->v1->fY(), line->v2->fX(), line->v2->fY(), sx1, sx2) == LineSegmentRange::HasSegment) + { + MarkSegmentCulled(sx1, sx2); + } + } + } +} + +void PolyCull::ClearSolidSegments() +{ + SolidSegments.clear(); + SolidSegments.reserve(SolidCullScale + 2); + SolidSegments.push_back({ -0x7fff, -SolidCullScale }); + SolidSegments.push_back({ SolidCullScale , 0x7fff }); +} + +void PolyCull::InvertSegments() +{ + TempInvertSolidSegments.swap(SolidSegments); + ClearSolidSegments(); + int x = -0x7fff; + for (const auto &segment : TempInvertSolidSegments) + { + MarkSegmentCulled(x, segment.X1 - 1); + x = segment.X2 + 1; + } +} + +bool PolyCull::IsSegmentCulled(int x1, int x2) const +{ + x1 = clamp(x1, -0x7ffe, 0x7ffd); + x2 = clamp(x2, -0x7ffd, 0x7ffe); + + int next = 0; + while (SolidSegments[next].X2 <= x2) + next++; + return (x1 >= SolidSegments[next].X1 && x2 <= SolidSegments[next].X2); +} + +void PolyCull::MarkSegmentCulled(int x1, int x2) +{ + if (x1 >= x2) + return; + + x1 = clamp(x1, -0x7ffe, 0x7ffd); + x2 = clamp(x2, -0x7ffd, 0x7ffe); + + int cur = 0; + while (true) + { + if (SolidSegments[cur].X1 <= x1 && SolidSegments[cur].X2 >= x2) // Already fully marked + { + break; + } + else if (SolidSegments[cur].X2 >= x1 && SolidSegments[cur].X1 <= x2) // Merge segments + { + // Find last segment + int merge = cur; + while (merge + 1 != (int)SolidSegments.size() && SolidSegments[merge + 1].X1 <= x2) + merge++; + + // Apply new merged range + SolidSegments[cur].X1 = MIN(SolidSegments[cur].X1, x1); + SolidSegments[cur].X2 = MAX(SolidSegments[merge].X2, x2); + + // Remove additional segments we merged with + if (merge > cur) + SolidSegments.erase(SolidSegments.begin() + (cur + 1), SolidSegments.begin() + (merge + 1)); + + break; + } + else if (SolidSegments[cur].X1 > x1) // Insert new segment + { + SolidSegments.insert(SolidSegments.begin() + cur, { x1, x2 }); + break; + } + cur++; + } +} + +int PolyCull::PointOnSide(const DVector2 &pos, const node_t *node) +{ + return DMulScale32(FLOAT2FIXED(pos.Y) - node->y, node->dx, node->x - FLOAT2FIXED(pos.X), node->dy) > 0; +} + +bool PolyCull::CheckBBox(float *bspcoord) +{ + // Start using a quick frustum AABB test: + + AxisAlignedBoundingBox aabb(Vec3f(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM], (float)ViewPos.Z - 1000.0f), Vec3f(bspcoord[BOXRIGHT], bspcoord[BOXTOP], (float)ViewPos.Z + 1000.0f)); + auto result = IntersectionTest::frustum_aabb(frustumPlanes, aabb); + if (result == IntersectionTest::outside) + return false; + + // Skip if its in front of the portal: + + if (IntersectionTest::plane_aabb(PortalClipPlane, aabb) == IntersectionTest::outside) + return false; + + // Occlusion test using solid segments: + + static const int lines[4][4] = + { + { BOXLEFT, BOXBOTTOM, BOXRIGHT, BOXBOTTOM }, + { BOXRIGHT, BOXBOTTOM, BOXRIGHT, BOXTOP }, + { BOXRIGHT, BOXTOP, BOXLEFT, BOXTOP }, + { BOXLEFT, BOXTOP, BOXLEFT, BOXBOTTOM } + }; + + bool foundline = false; + int minsx1, maxsx2; + for (int i = 0; i < 4; i++) + { + int j = i < 3 ? i + 1 : 0; + float x1 = bspcoord[lines[i][0]]; + float y1 = bspcoord[lines[i][1]]; + float x2 = bspcoord[lines[i][2]]; + float y2 = bspcoord[lines[i][3]]; + int sx1, sx2; + LineSegmentRange result = GetSegmentRangeForLine(x1, y1, x2, y2, sx1, sx2); + if (result == LineSegmentRange::HasSegment) + { + if (foundline) + { + minsx1 = MIN(minsx1, sx1); + maxsx2 = MAX(maxsx2, sx2); + } + else + { + minsx1 = sx1; + maxsx2 = sx2; + foundline = true; + } + } + else if (result == LineSegmentRange::AlwaysVisible) + { + return true; + } + } + if (!foundline) + return false; + + return !IsSegmentCulled(minsx1, maxsx2); +} + +LineSegmentRange PolyCull::GetSegmentRangeForLine(double x1, double y1, double x2, double y2, int &sx1, int &sx2) const +{ + double znear = 5.0; + double updownnear = -400.0; + double sidenear = 400.0; + + // Clip line to the portal clip plane + float distance1 = Vec4f::dot(PortalClipPlane, Vec4f((float)x1, (float)y1, 0.0f, 1.0f)); + float distance2 = Vec4f::dot(PortalClipPlane, Vec4f((float)x2, (float)y2, 0.0f, 1.0f)); + if (distance1 < 0.0f && distance2 < 0.0f) + { + return LineSegmentRange::NotVisible; + } + else if (distance1 < 0.0f || distance2 < 0.0f) + { + double t1 = 0.0f, t2 = 1.0f; + if (distance1 < 0.0f) + t1 = clamp(distance1 / (distance1 - distance2), 0.0f, 1.0f); + else + t2 = clamp(distance2 / (distance1 - distance2), 0.0f, 1.0f); + double nx1 = x1 * (1.0 - t1) + x2 * t1; + double ny1 = y1 * (1.0 - t1) + y2 * t1; + double nx2 = x1 * (1.0 - t2) + x2 * t2; + double ny2 = y1 * (1.0 - t2) + y2 * t2; + x1 = nx1; + x2 = nx2; + y1 = ny1; + y2 = ny2; + } + + // Transform to 2D view space: + x1 = x1 - ViewPos.X; + y1 = y1 - ViewPos.Y; + x2 = x2 - ViewPos.X; + y2 = y2 - ViewPos.Y; + double rx1 = x1 * ViewSin - y1 * ViewCos; + double rx2 = x2 * ViewSin - y2 * ViewCos; + double ry1 = x1 * ViewCos + y1 * ViewSin; + double ry2 = x2 * ViewCos + y2 * ViewSin; + + // Is it potentially visible when looking straight up or down? + if (!(ry1 < updownnear && ry2 < updownnear) && !(ry1 > znear && ry2 > znear) && + !(rx1 < -sidenear && rx2 < -sidenear) && !(rx1 > sidenear && rx2 > sidenear)) + return LineSegmentRange::AlwaysVisible; + + // Cull if line is entirely behind view + if (ry1 < znear && ry2 < znear) + return LineSegmentRange::NotVisible; + + // Clip line, if needed + double t1 = 0.0f, t2 = 1.0f; + if (ry1 < znear) + t1 = clamp((znear - ry1) / (ry2 - ry1), 0.0, 1.0); + if (ry2 < znear) + t2 = clamp((znear - ry2) / (ry2 - ry1), 0.0, 1.0); + if (t1 != 0.0 || t2 != 1.0) + { + double nx1 = rx1 * (1.0 - t1) + rx2 * t1; + double ny1 = ry1 * (1.0 - t1) + ry2 * t1; + double nx2 = rx1 * (1.0 - t2) + rx2 * t2; + double ny2 = ry1 * (1.0 - t2) + ry2 * t2; + rx1 = nx1; + rx2 = nx2; + ry1 = ny1; + ry2 = ny2; + } + + sx1 = (int)floor(clamp(rx1 / ry1 * (SolidCullScale / 3), (double)-SolidCullScale, (double)SolidCullScale)); + sx2 = (int)floor(clamp(rx2 / ry2 * (SolidCullScale / 3), (double)-SolidCullScale, (double)SolidCullScale)); + + if (sx1 > sx2) + std::swap(sx1, sx2); + return (sx1 != sx2) ? LineSegmentRange::HasSegment : LineSegmentRange::AlwaysVisible; +} diff --git a/src/r_poly_cull.h b/src/r_poly_cull.h new file mode 100644 index 000000000..4c0cfe314 --- /dev/null +++ b/src/r_poly_cull.h @@ -0,0 +1,71 @@ +/* +** Potential visible set (PVS) handling +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" +#include "r_poly_intersection.h" + +enum class LineSegmentRange +{ + NotVisible, + HasSegment, + AlwaysVisible +}; + +class PolyCull +{ +public: + void ClearSolidSegments(); + void CullScene(const TriMatrix &worldToClip, const Vec4f &portalClipPlane); + + LineSegmentRange GetSegmentRangeForLine(double x1, double y1, double x2, double y2, int &sx1, int &sx2) const; + void MarkSegmentCulled(int x1, int x2); + bool IsSegmentCulled(int x1, int x2) const; + void InvertSegments(); + + std::vector PvsSectors; + double MaxCeilingHeight = 0.0; + double MinFloorHeight = 0.0; + +private: + struct SolidSegment + { + SolidSegment(int x1, int x2) : X1(x1), X2(x2) { } + int X1, X2; + }; + + void CullNode(void *node); + void CullSubsector(subsector_t *sub); + int PointOnSide(const DVector2 &pos, const node_t *node); + + // Checks BSP node/subtree bounding box. + // Returns true if some part of the bbox might be visible. + bool CheckBBox(float *bspcoord); + + std::vector SolidSegments; + std::vector TempInvertSolidSegments; + const int SolidCullScale = 3000; + + FrustumPlanes frustumPlanes; + Vec4f PortalClipPlane; +}; diff --git a/src/r_poly_decal.cpp b/src/r_poly_decal.cpp new file mode 100644 index 000000000..7718d422e --- /dev/null +++ b/src/r_poly_decal.cpp @@ -0,0 +1,175 @@ +/* +** Handling drawing a decal +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_decal.h" +#include "r_poly.h" +#include "a_sharedglobal.h" + +void RenderPolyDecal::RenderWallDecals(const TriMatrix &worldToClip, const Vec4f &clipPlane, const seg_t *line, uint32_t subsectorDepth, uint32_t stencilValue) +{ + if (line->linedef == nullptr && line->sidedef == nullptr) + return; + + for (DBaseDecal *decal = line->sidedef->AttachedDecals; decal != nullptr; decal = decal->WallNext) + { + RenderPolyDecal render; + render.Render(worldToClip, clipPlane, decal, line, subsectorDepth, stencilValue); + } +} + +void RenderPolyDecal::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, DBaseDecal *decal, const seg_t *line, uint32_t subsectorDepth, uint32_t stencilValue) +{ + if (decal->RenderFlags & RF_INVISIBLE || !viewactive || !decal->PicNum.isValid()) + return; + + FTexture *tex = TexMan(decal->PicNum, true); + if (tex == nullptr || tex->UseType == FTexture::TEX_Null) + return; + + double edge_right = tex->GetWidth(); + double edge_left = tex->LeftOffset; + edge_right = (edge_right - edge_left) * decal->ScaleX; + edge_left *= decal->ScaleX; + + double dcx, dcy; + decal->GetXY(line->sidedef, dcx, dcy); + DVector2 decal_pos = { dcx, dcy }; + + DVector2 angvec = (line->v2->fPos() - line->v1->fPos()).Unit(); + DVector2 decal_left = decal_pos - edge_left * angvec; + DVector2 decal_right = decal_pos + edge_right * angvec; + + // Determine actor z + double zpos = decal->Z; + sector_t *front = line->frontsector; + sector_t *back = (line->backsector != nullptr) ? line->backsector : line->frontsector; + switch (decal->RenderFlags & RF_RELMASK) + { + default: + zpos = decal->Z; + break; + case RF_RELUPPER: + if (line->linedef->flags & ML_DONTPEGTOP) + zpos = decal->Z + front->GetPlaneTexZ(sector_t::ceiling); + else + zpos = decal->Z + back->GetPlaneTexZ(sector_t::ceiling); + break; + case RF_RELLOWER: + if (line->linedef->flags & ML_DONTPEGBOTTOM) + zpos = decal->Z + front->GetPlaneTexZ(sector_t::ceiling); + else + zpos = decal->Z + back->GetPlaneTexZ(sector_t::floor); + break; + case RF_RELMID: + if (line->linedef->flags & ML_DONTPEGBOTTOM) + zpos = decal->Z + front->GetPlaneTexZ(sector_t::floor); + else + zpos = decal->Z + front->GetPlaneTexZ(sector_t::ceiling); + } + + DVector2 spriteScale = { decal->ScaleX, decal->ScaleY }; + double thingxscalemul = spriteScale.X / tex->Scale.X; + double thingyscalemul = spriteScale.Y / tex->Scale.Y; + double spriteHeight = thingyscalemul * tex->GetHeight(); + + bool flipTextureX = (decal->RenderFlags & RF_XFLIP) == RF_XFLIP; + + DVector2 points[2] = { decal_left, decal_right }; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(4); + if (!vertices) + return; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + + std::pair offsets[4] = + { + { 0.0f, 1.0f }, + { 1.0f, 1.0f }, + { 1.0f, 0.0f }, + { 0.0f, 0.0f }, + }; + + for (int i = 0; i < 4; i++) + { + auto &p = (i == 0 || i == 3) ? points[0] : points[1]; + + vertices[i].x = (float)p.X; + vertices[i].y = (float)p.Y; + vertices[i].z = (float)(zpos + spriteHeight * offsets[i].second - spriteHeight * 0.5); + vertices[i].w = 1.0f; + vertices[i].varying[0] = (float)(offsets[i].first * tex->Scale.X); + vertices[i].varying[1] = (float)((1.0f - offsets[i].second) * tex->Scale.Y); + if (flipTextureX) + vertices[i].varying[0] = 1.0f - vertices[i].varying[0]; + } + + bool fullbrightSprite = (decal->RenderFlags & RF_FULLBRIGHT) == RF_FULLBRIGHT; + + PolyDrawArgs args; + args.uniforms.flags = 0; + args.SetColormap(front->ColorMap); + args.SetTexture(tex, decal->Translation, true); + if (fullbrightSprite || swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + { + args.uniforms.light = 256; + args.uniforms.flags |= TriUniforms::fixed_light; + } + else + { + args.uniforms.light = (uint32_t)((front->lightlevel + actualextralight) / 255.0f * 256.0f); + } + args.uniforms.subsectorDepth = subsectorDepth; + + if (swrenderer::r_swtruecolor) + { + args.uniforms.color = 0xff000000 | decal->AlphaColor; + } + else + { + args.uniforms.color = ((uint32_t)decal->AlphaColor) >> 24; + } + + args.uniforms.srcalpha = (uint32_t)(decal->Alpha * 256.0 + 0.5); + args.uniforms.destalpha = 256 - args.uniforms.srcalpha; + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = 4; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue; + //mode = R_SetPatchStyle (decal->RenderStyle, (float)decal->Alpha, decal->Translation, decal->AlphaColor); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + args.blendmode = TriBlendMode::Shaded; + args.subsectorTest = true; + args.writeStencil = false; + args.writeSubsector = false; + PolyTriangleDrawer::draw(args); +} diff --git a/src/r_poly_decal.h b/src/r_poly_decal.h new file mode 100644 index 000000000..068887d90 --- /dev/null +++ b/src/r_poly_decal.h @@ -0,0 +1,36 @@ +/* +** Handling drawing a decal +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class Vec4f; + +class RenderPolyDecal +{ +public: + static void RenderWallDecals(const TriMatrix &worldToClip, const Vec4f &clipPlane, const seg_t *line, uint32_t subsectorDepth, uint32_t stencilValue); + +private: + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, DBaseDecal *decal, const seg_t *line, uint32_t subsectorDepth, uint32_t stencilValue); +}; diff --git a/src/r_poly_intersection.cpp b/src/r_poly_intersection.cpp new file mode 100644 index 000000000..5e7ad374b --- /dev/null +++ b/src/r_poly_intersection.cpp @@ -0,0 +1,235 @@ +/* +** Various 3D intersection tests +** Copyright (c) 1997-2015 The UICore Team +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "r_poly_intersection.h" + +IntersectionTest::Result IntersectionTest::plane_aabb(const Vec4f &plane, const AxisAlignedBoundingBox &aabb) +{ + Vec3f center = aabb.center(); + Vec3f extents = aabb.extents(); + float e = extents.x * std::abs(plane.x) + extents.y * std::abs(plane.y) + extents.z * std::abs(plane.z); + float s = center.x * plane.x + center.y * plane.y + center.z * plane.z + plane.w; + if (s - e > 0) + return inside; + else if (s + e < 0) + return outside; + else + return intersecting; +} + +IntersectionTest::Result IntersectionTest::plane_obb(const Vec4f &plane, const OrientedBoundingBox &obb) +{ + Vec3f n(plane); + float d = plane.w; + float e = obb.extents.x * std::abs(Vec3f::dot(obb.axis_x, n)) + obb.extents.y * std::abs(Vec3f::dot(obb.axis_y, n)) + obb.extents.z * std::abs(Vec3f::dot(obb.axis_z, n)); + float s = Vec3f::dot(obb.center, n) + d; + if (s - e > 0) + return inside; + else if (s + e < 0) + return outside; + else + return intersecting; +} + +IntersectionTest::OverlapResult IntersectionTest::sphere(const Vec3f ¢er1, float radius1, const Vec3f ¢er2, float radius2) +{ + Vec3f h = center1 - center2; + float square_distance = Vec3f::dot(h, h); + float radius_sum = radius1 + radius2; + if (square_distance > radius_sum * radius_sum) + return disjoint; + else + return overlap; +} + +IntersectionTest::OverlapResult IntersectionTest::sphere_aabb(const Vec3f ¢er, float radius, const AxisAlignedBoundingBox &aabb) +{ + Vec3f a = aabb.aabb_min - center; + Vec3f b = center - aabb.aabb_max; + a.x = std::max(a.x, 0.0f); + a.y = std::max(a.y, 0.0f); + a.z = std::max(a.z, 0.0f); + b.x = std::max(b.x, 0.0f); + b.y = std::max(b.y, 0.0f); + b.z = std::max(b.z, 0.0f); + Vec3f e = a + b; + float d = Vec3f::dot(e, e); + if (d > radius * radius) + return disjoint; + else + return overlap; +} + +IntersectionTest::OverlapResult IntersectionTest::aabb(const AxisAlignedBoundingBox &a, const AxisAlignedBoundingBox &b) +{ + if (a.aabb_min.x > b.aabb_max.x || b.aabb_min.x > a.aabb_max.x || + a.aabb_min.y > b.aabb_max.y || b.aabb_min.y > a.aabb_max.y || + a.aabb_min.z > b.aabb_max.z || b.aabb_min.z > a.aabb_max.z) + { + return disjoint; + } + else + { + return overlap; + } +} + +IntersectionTest::Result IntersectionTest::frustum_aabb(const FrustumPlanes &frustum, const AxisAlignedBoundingBox &box) +{ + bool is_intersecting = false; + for (int i = 0; i < 6; i++) + { + Result result = plane_aabb(frustum.planes[i], box); + if (result == outside) + return outside; + else if (result == intersecting) + is_intersecting = true; + break; + } + if (is_intersecting) + return intersecting; + else + return inside; +} + +IntersectionTest::Result IntersectionTest::frustum_obb(const FrustumPlanes &frustum, const OrientedBoundingBox &box) +{ + bool is_intersecting = false; + for (int i = 0; i < 6; i++) + { + Result result = plane_obb(frustum.planes[i], box); + if (result == outside) + return outside; + else if (result == intersecting) + is_intersecting = true; + } + if (is_intersecting) + return intersecting; + else + return inside; +} + +IntersectionTest::OverlapResult IntersectionTest::ray_aabb(const Vec3f &ray_start, const Vec3f &ray_end, const AxisAlignedBoundingBox &aabb) +{ + Vec3f c = (ray_start + ray_end) * 0.5f; + Vec3f w = ray_end - c; + Vec3f h = aabb.extents(); + + c -= aabb.center(); + + Vec3f v(std::abs(w.x), std::abs(w.y), std::abs(w.z)); + + if (std::abs(c.x) > v.x + h.x || std::abs(c.y) > v.y + h.y || std::abs(c.z) > v.z + h.z) + return disjoint; + + if (std::abs(c.y * w.z - c.z * w.y) > h.y * v.z + h.z * v.y || + std::abs(c.x * w.z - c.z * w.x) > h.x * v.z + h.z * v.x || + std::abs(c.x * w.y - c.y * w.x) > h.x * v.y + h.y * v.x) + return disjoint; + + return overlap; +} + +///////////////////////////////////////////////////////////////////////////// + +FrustumPlanes::FrustumPlanes() +{ +} + +FrustumPlanes::FrustumPlanes(const Mat4f &world_to_projection) +{ + planes[0] = near_frustum_plane(world_to_projection); + planes[1] = far_frustum_plane(world_to_projection); + planes[2] = left_frustum_plane(world_to_projection); + planes[3] = right_frustum_plane(world_to_projection); + planes[4] = top_frustum_plane(world_to_projection); + planes[5] = bottom_frustum_plane(world_to_projection); +} + +Vec4f FrustumPlanes::left_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] + m.matrix[0 + 0 * 4], + m.matrix[3 + 1 * 4] + m.matrix[0 + 1 * 4], + m.matrix[3 + 2 * 4] + m.matrix[0 + 2 * 4], + m.matrix[3 + 3 * 4] + m.matrix[0 + 3 * 4]); + plane /= plane.length3(); + return plane; +} + +Vec4f FrustumPlanes::right_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] - m.matrix[0 + 0 * 4], + m.matrix[3 + 1 * 4] - m.matrix[0 + 1 * 4], + m.matrix[3 + 2 * 4] - m.matrix[0 + 2 * 4], + m.matrix[3 + 3 * 4] - m.matrix[0 + 3 * 4]); + plane /= plane.length3(); + return plane; +} + +Vec4f FrustumPlanes::top_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] - m.matrix[1 + 0 * 4], + m.matrix[3 + 1 * 4] - m.matrix[1 + 1 * 4], + m.matrix[3 + 2 * 4] - m.matrix[1 + 2 * 4], + m.matrix[3 + 3 * 4] - m.matrix[1 + 3 * 4]); + plane /= plane.length3(); + return plane; +} + +Vec4f FrustumPlanes::bottom_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] + m.matrix[1 + 0 * 4], + m.matrix[3 + 1 * 4] + m.matrix[1 + 1 * 4], + m.matrix[3 + 2 * 4] + m.matrix[1 + 2 * 4], + m.matrix[3 + 3 * 4] + m.matrix[1 + 3 * 4]); + plane /= plane.length3(); + return plane; +} + +Vec4f FrustumPlanes::near_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] + m.matrix[2 + 0 * 4], + m.matrix[3 + 1 * 4] + m.matrix[2 + 1 * 4], + m.matrix[3 + 2 * 4] + m.matrix[2 + 2 * 4], + m.matrix[3 + 3 * 4] + m.matrix[2 + 3 * 4]); + plane /= plane.length3(); + return plane; +} + +Vec4f FrustumPlanes::far_frustum_plane(const Mat4f &m) +{ + Vec4f plane( + m.matrix[3 + 0 * 4] - m.matrix[2 + 0 * 4], + m.matrix[3 + 1 * 4] - m.matrix[2 + 1 * 4], + m.matrix[3 + 2 * 4] - m.matrix[2 + 2 * 4], + m.matrix[3 + 3 * 4] - m.matrix[2 + 3 * 4]); + plane /= plane.length3(); + return plane; +} diff --git a/src/r_poly_intersection.h b/src/r_poly_intersection.h new file mode 100644 index 000000000..2ce164e5e --- /dev/null +++ b/src/r_poly_intersection.h @@ -0,0 +1,179 @@ +/* +** Various 3D intersection tests +** Copyright (c) 1997-2015 The UICore Team +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" +#include +#include + +class Vec3f; + +class Vec4f +{ +public: + Vec4f() = default; + Vec4f(const Vec4f &) = default; + Vec4f(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } + Vec4f(float v) : x(v), y(v), z(v), w(v) { } + Vec4f(const Vec3f &xyz, float w); + + static float dot(const Vec4f &a, const Vec4f &b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } + static float dot3(const Vec4f &a, const Vec4f &b) { return a.x * b.x + a.y * b.y + a.z * b.z; } + float length3() const { return std::sqrt(dot3(*this, *this)); } + float magnitude() const { return std::sqrt(dot(*this, *this)); } + + Vec4f &operator+=(const Vec4f &b) { *this = Vec4f(x + b.x, y + b.y, z + b.z, w + b.w); return *this; } + Vec4f &operator-=(const Vec4f &b) { *this = Vec4f(x - b.x, y - b.y, z - b.z, w - b.w); return *this; } + Vec4f &operator*=(const Vec4f &b) { *this = Vec4f(x * b.x, y * b.y, z * b.z, w * b.w); return *this; } + Vec4f &operator/=(const Vec4f &b) { *this = Vec4f(x / b.x, y / b.y, z / b.z, w / b.w); return *this; } + Vec4f &operator+=(float b) { *this = Vec4f(x + b, y + b, z + b, w + b); return *this; } + Vec4f &operator-=(float b) { *this = Vec4f(x - b, y - b, z - b, w - b); return *this; } + Vec4f &operator*=(float b) { *this = Vec4f(x * b, y * b, z * b, w * b); return *this; } + Vec4f &operator/=(float b) { *this = Vec4f(x / b, y / b, z / b, w / b); return *this; } + + float x, y, z, w; +}; + +inline bool operator==(const Vec4f &a, const Vec4f &b) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } +inline bool operator!=(const Vec4f &a, const Vec4f &b) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w == b.w; } + +class Vec3f +{ +public: + Vec3f() = default; + Vec3f(const Vec3f &) = default; + Vec3f(const Vec4f &v) : x(v.x), y(v.y), z(v.z) { } + Vec3f(float x, float y, float z) : x(x), y(y), z(z) { } + Vec3f(float v) : x(v), y(v), z(v) { } + + static float dot(const Vec3f &a, const Vec3f &b) { return a.x * b.x + a.y * b.y + a.z * b.z; } + float length() const { return std::sqrt(dot(*this, *this)); } + + Vec3f &operator+=(const Vec3f &b) { *this = Vec3f(x + b.x, y + b.y, z + b.z); return *this; } + Vec3f &operator-=(const Vec3f &b) { *this = Vec3f(x - b.x, y - b.y, z - b.z); return *this; } + Vec3f &operator*=(const Vec3f &b) { *this = Vec3f(x * b.x, y * b.y, z * b.z); return *this; } + Vec3f &operator/=(const Vec3f &b) { *this = Vec3f(x / b.x, y / b.y, z / b.z); return *this; } + Vec3f &operator+=(float b) { *this = Vec3f(x + b, y + b, z + b); return *this; } + Vec3f &operator-=(float b) { *this = Vec3f(x - b, y - b, z - b); return *this; } + Vec3f &operator*=(float b) { *this = Vec3f(x * b, y * b, z * b); return *this; } + Vec3f &operator/=(float b) { *this = Vec3f(x / b, y / b, z / b); return *this; } + + float x, y, z; +}; + +inline bool operator==(const Vec3f &a, const Vec3f &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } +inline bool operator!=(const Vec3f &a, const Vec3f &b) { return a.x != b.x || a.y != b.y || a.z != b.z; } + +inline Vec3f operator+(const Vec3f &a, const Vec3f &b) { return Vec3f(a.x + b.x, a.y + b.y, a.z + b.z); } +inline Vec3f operator-(const Vec3f &a, const Vec3f &b) { return Vec3f(a.x - b.x, a.y - b.y, a.z - b.z); } +inline Vec3f operator*(const Vec3f &a, const Vec3f &b) { return Vec3f(a.x * b.x, a.y * b.y, a.z * b.z); } +inline Vec3f operator/(const Vec3f &a, const Vec3f &b) { return Vec3f(a.x / b.x, a.y / b.y, a.z / b.z); } + +inline Vec3f operator+(const Vec3f &a, float b) { return Vec3f(a.x + b, a.y + b, a.z + b); } +inline Vec3f operator-(const Vec3f &a, float b) { return Vec3f(a.x - b, a.y - b, a.z - b); } +inline Vec3f operator*(const Vec3f &a, float b) { return Vec3f(a.x * b, a.y * b, a.z * b); } +inline Vec3f operator/(const Vec3f &a, float b) { return Vec3f(a.x / b, a.y / b, a.z / b); } + +inline Vec3f operator+(float a, const Vec3f &b) { return Vec3f(a + b.x, a + b.y, a + b.z); } +inline Vec3f operator-(float a, const Vec3f &b) { return Vec3f(a - b.x, a - b.y, a - b.z); } +inline Vec3f operator*(float a, const Vec3f &b) { return Vec3f(a * b.x, a * b.y, a * b.z); } +inline Vec3f operator/(float a, const Vec3f &b) { return Vec3f(a / b.x, a / b.y, a / b.z); } + +inline Vec4f::Vec4f(const Vec3f &xyz, float w) : x(xyz.x), y(xyz.y), z(xyz.z), w(w) { } + +typedef TriMatrix Mat4f; + +class AxisAlignedBoundingBox +{ +public: + AxisAlignedBoundingBox() : aabb_min(), aabb_max() {} + AxisAlignedBoundingBox(const Vec3f &aabb_min, const Vec3f &aabb_max) : aabb_min(aabb_min), aabb_max(aabb_max) { } + AxisAlignedBoundingBox(const AxisAlignedBoundingBox &aabb, const Vec3f &barycentric_min, const Vec3f &barycentric_max) + : aabb_min(mix(aabb.aabb_min, aabb.aabb_max, barycentric_min)), aabb_max(mix(aabb.aabb_min, aabb.aabb_max, barycentric_max)) { } + + Vec3f center() const { return (aabb_max + aabb_min) * 0.5f; } + Vec3f extents() const { return (aabb_max - aabb_min) * 0.5f; } + + Vec3f aabb_min; + Vec3f aabb_max; + +private: + template + inline A mix(A a, B b, C mix) + { + return a * (C(1) - mix) + b * mix; + } +}; + +class OrientedBoundingBox +{ +public: + Vec3f center; + Vec3f extents; + Vec3f axis_x; + Vec3f axis_y; + Vec3f axis_z; +}; + +class FrustumPlanes +{ +public: + FrustumPlanes(); + explicit FrustumPlanes(const Mat4f &world_to_projection); + + Vec4f planes[6]; + +private: + static Vec4f left_frustum_plane(const Mat4f &matrix); + static Vec4f right_frustum_plane(const Mat4f &matrix); + static Vec4f top_frustum_plane(const Mat4f &matrix); + static Vec4f bottom_frustum_plane(const Mat4f &matrix); + static Vec4f near_frustum_plane(const Mat4f &matrix); + static Vec4f far_frustum_plane(const Mat4f &matrix); +}; + +class IntersectionTest +{ +public: + enum Result + { + outside, + inside, + intersecting, + }; + + enum OverlapResult + { + disjoint, + overlap + }; + + static Result plane_aabb(const Vec4f &plane, const AxisAlignedBoundingBox &aabb); + static Result plane_obb(const Vec4f &plane, const OrientedBoundingBox &obb); + static OverlapResult sphere(const Vec3f ¢er1, float radius1, const Vec3f ¢er2, float radius2); + static OverlapResult sphere_aabb(const Vec3f ¢er, float radius, const AxisAlignedBoundingBox &aabb); + static OverlapResult aabb(const AxisAlignedBoundingBox &a, const AxisAlignedBoundingBox &b); + static Result frustum_aabb(const FrustumPlanes &frustum, const AxisAlignedBoundingBox &box); + static Result frustum_obb(const FrustumPlanes &frustum, const OrientedBoundingBox &box); + static OverlapResult ray_aabb(const Vec3f &ray_start, const Vec3f &ray_end, const AxisAlignedBoundingBox &box); +}; diff --git a/src/r_poly_particle.cpp b/src/r_poly_particle.cpp new file mode 100644 index 000000000..27888e77b --- /dev/null +++ b/src/r_poly_particle.cpp @@ -0,0 +1,113 @@ +/* +** Particle drawing +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_particle.h" +#include "r_poly.h" + +void RenderPolyParticle::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, particle_t *particle, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue) +{ + DVector3 pos = particle->Pos; + double psize = particle->size / 8.0; + double zpos = pos.Z; + + DVector2 points[2] = + { + { pos.X - ViewSin * psize, pos.Y + ViewCos * psize }, + { pos.X + ViewSin * psize, pos.Y - ViewCos * psize } + }; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(4); + if (!vertices) + return; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + + std::pair offsets[4] = + { + { 0.0f, 1.0f }, + { 1.0f, 1.0f }, + { 1.0f, 0.0f }, + { 0.0f, 0.0f }, + }; + + for (int i = 0; i < 4; i++) + { + auto &p = (i == 0 || i == 3) ? points[0] : points[1]; + + vertices[i].x = (float)p.X; + vertices[i].y = (float)p.Y; + vertices[i].z = (float)(zpos + psize * (2.0 * offsets[i].second - 1.0)); + vertices[i].w = 1.0f; + vertices[i].varying[0] = (float)(offsets[i].first); + vertices[i].varying[1] = (float)(1.0f - offsets[i].second); + } + + // int color = (particle->color >> 24) & 0xff; // pal index, I think + bool fullbrightSprite = particle->bright != 0; + + PolyDrawArgs args; + + if (fullbrightSprite || swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + { + args.uniforms.light = 256; + args.uniforms.flags = TriUniforms::fixed_light; + } + else + { + args.uniforms.light = (uint32_t)((sub->sector->lightlevel + actualextralight) / 255.0f * 256.0f); + args.uniforms.flags = 0; + } + args.uniforms.subsectorDepth = subsectorDepth; + + if (swrenderer::r_swtruecolor) + { + uint32_t alpha = particle->trans; + args.uniforms.color = (alpha << 24) | (particle->color & 0xffffff); + } + else + { + args.uniforms.color = ((uint32_t)particle->color) >> 24; + args.uniforms.srcalpha = particle->trans; + args.uniforms.destalpha = 255 - particle->trans; + } + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = 4; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue; + args.SetColormap(sub->sector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + args.subsectorTest = true; + args.writeStencil = false; + args.writeSubsector = false; + args.blendmode = TriBlendMode::AlphaBlend; + PolyTriangleDrawer::draw(args); +} diff --git a/src/r_poly_particle.h b/src/r_poly_particle.h new file mode 100644 index 000000000..fd581fa83 --- /dev/null +++ b/src/r_poly_particle.h @@ -0,0 +1,34 @@ +/* +** Handling drawing a particle +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" +#include "p_effect.h" + +class Vec4f; + +class RenderPolyParticle +{ +public: + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, particle_t *particle, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue); +}; diff --git a/src/r_poly_plane.cpp b/src/r_poly_plane.cpp new file mode 100644 index 000000000..e21868dc2 --- /dev/null +++ b/src/r_poly_plane.cpp @@ -0,0 +1,496 @@ +/* +** Handling drawing a plane (ceiling, floor) +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_plane.h" +#include "r_poly_portal.h" +#include "r_poly.h" +#include "r_sky.h" + +EXTERN_CVAR(Int, r_3dfloors) + +void RenderPolyPlane::RenderPlanes(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, double skyCeilingHeight, double skyFloorHeight, std::vector> §orPortals) +{ + RenderPolyPlane plane; + + if (r_3dfloors) + { + auto frontsector = sub->sector; + auto &ffloors = frontsector->e->XFloor.ffloors; + + // 3D floor floors + for (int i = 0; i < (int)ffloors.Size(); i++) + { + F3DFloor *fakeFloor = ffloors[i]; + if (!(fakeFloor->flags & FF_EXISTS)) continue; + if (!fakeFloor->model) continue; + if (fakeFloor->bottom.plane->isSlope()) continue; + //if (!(fakeFloor->flags & FF_NOSHADE) || (fakeFloor->flags & (FF_RENDERPLANES | FF_RENDERSIDES))) + // R_3D_AddHeight(fakeFloor->top.plane, frontsector); + if (!(fakeFloor->flags & FF_RENDERPLANES)) continue; + if (fakeFloor->alpha == 0) continue; + if (fakeFloor->flags & FF_THISINSIDE && fakeFloor->flags & FF_INVERTSECTOR) continue; + //fakeFloor->alpha + + double fakeHeight = fakeFloor->top.plane->ZatPoint(frontsector->centerspot); + if (fakeHeight < ViewPos.Z && fakeHeight > frontsector->floorplane.ZatPoint(frontsector->centerspot)) + { + plane.Render3DFloor(worldToClip, clipPlane, sub, subsectorDepth, stencilValue, false, fakeFloor); + } + } + + // 3D floor ceilings + for (int i = 0; i < (int)ffloors.Size(); i++) + { + F3DFloor *fakeFloor = ffloors[i]; + if (!(fakeFloor->flags & FF_EXISTS)) continue; + if (!fakeFloor->model) continue; + if (fakeFloor->top.plane->isSlope()) continue; + //if (!(fakeFloor->flags & FF_NOSHADE) || (fakeFloor->flags & (FF_RENDERPLANES | FF_RENDERSIDES))) + // R_3D_AddHeight(fakeFloor->bottom.plane, frontsector); + if (!(fakeFloor->flags & FF_RENDERPLANES)) continue; + if (fakeFloor->alpha == 0) continue; + if (!(fakeFloor->flags & FF_THISINSIDE) && (fakeFloor->flags & (FF_SWIMMABLE | FF_INVERTSECTOR)) == (FF_SWIMMABLE | FF_INVERTSECTOR)) continue; + //fakeFloor->alpha + + double fakeHeight = fakeFloor->bottom.plane->ZatPoint(frontsector->centerspot); + if (fakeHeight > ViewPos.Z && fakeHeight < frontsector->ceilingplane.ZatPoint(frontsector->centerspot)) + { + plane.Render3DFloor(worldToClip, clipPlane, sub, subsectorDepth, stencilValue, true, fakeFloor); + } + } + } + + plane.Render(worldToClip, clipPlane, cull, sub, subsectorDepth, stencilValue, true, skyCeilingHeight, sectorPortals); + plane.Render(worldToClip, clipPlane, cull, sub, subsectorDepth, stencilValue, false, skyFloorHeight, sectorPortals); +} + +void RenderPolyPlane::Render3DFloor(const TriMatrix &worldToClip, const Vec4f &clipPlane, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, bool ceiling, F3DFloor *fakeFloor) +{ + FTextureID picnum = ceiling ? *fakeFloor->bottom.texture : *fakeFloor->top.texture; + FTexture *tex = TexMan(picnum); + if (tex->UseType == FTexture::TEX_Null) + return; + + int lightlevel = 255; + if (swrenderer::fixedlightlev < 0 && sub->sector->e->XFloor.lightlist.Size()) + { + lightlist_t *light = P_GetPlaneLight(sub->sector, &sub->sector->ceilingplane, false); + swrenderer::basecolormap = light->extra_colormap; + lightlevel = *light->p_lightlevel; + } + + UVTransform xform(ceiling ? fakeFloor->top.model->planes[sector_t::ceiling].xform : fakeFloor->top.model->planes[sector_t::floor].xform, tex); + + PolyDrawArgs args; + args.uniforms.light = (uint32_t)(lightlevel / 255.0f * 256.0f); + if (swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + args.uniforms.light = 256; + args.uniforms.flags = 0; + args.uniforms.subsectorDepth = subsectorDepth; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(sub->numlines); + if (!vertices) + return; + + if (ceiling) + { + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + vertices[sub->numlines - 1 - i] = PlaneVertex(line->v1, fakeFloor->bottom.plane->ZatPoint(line->v1), xform); + } + } + else + { + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + vertices[i] = PlaneVertex(line->v1, fakeFloor->top.plane->ZatPoint(line->v1), xform); + } + } + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = sub->numlines; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue + 1; + args.SetTexture(tex); + args.SetColormap(sub->sector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + args.blendmode = TriBlendMode::Copy; + PolyTriangleDrawer::draw(args); +} + +void RenderPolyPlane::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, bool ceiling, double skyHeight, std::vector> §orPortals) +{ + std::vector portalSegments; + FSectorPortal *portal = nullptr;// sub->sector->ValidatePortal(ceiling ? sector_t::ceiling : sector_t::floor); + PolyDrawSectorPortal *polyportal = nullptr; + if (portal && (portal->mFlags & PORTSF_INSKYBOX) == PORTSF_INSKYBOX) // Do not recurse into portals we already recursed into + portal = nullptr; + if (portal) + { + for (auto &p : sectorPortals) + { + if (p->Portal == portal) // To do: what other criteria do we need to check for? + { + polyportal = p.get(); + break; + } + } + if (!polyportal) + { + sectorPortals.push_back(std::make_unique(portal, ceiling)); + polyportal = sectorPortals.back().get(); + } + + // Calculate portal clipping + + DVector2 v; + bool inside = true; + double vdist = 1.0e10; + + portalSegments.reserve(sub->numlines); + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + + DVector2 pt1 = line->v1->fPos() - ViewPos; + DVector2 pt2 = line->v2->fPos() - ViewPos; + if (pt1.Y * (pt1.X - pt2.X) + pt1.X * (pt2.Y - pt1.Y) >= 0) + inside = false; + + double dist = pt1.LengthSquared(); + if (dist < vdist) + { + v = line->v1->fPos(); + vdist = dist; + } + dist = pt2.LengthSquared(); + if (dist < vdist) + { + v = line->v2->fPos(); + vdist = dist; + } + + int sx1, sx2; + LineSegmentRange range = cull.GetSegmentRangeForLine(line->v1->fX(), line->v1->fY(), line->v2->fX(), line->v2->fY(), sx1, sx2); + if (range == LineSegmentRange::HasSegment) + portalSegments.push_back({ sx1, sx2 }); + } + + if (inside) + { + polyportal->PortalPlane = Vec4f(0.0f, 0.0f, 0.0f, 1.0f); + } + else if(polyportal->PortalPlane == Vec4f(0.0f) || Vec4f::dot(polyportal->PortalPlane, Vec4f((float)v.X, (float)v.Y, 0.0f, 1.0f)) > 0.0f) + { + DVector2 planePos = v; + DVector2 planeNormal = v - ViewPos; + planeNormal.MakeUnit(); + double planeD = -(planeNormal | (planePos + planeNormal * 0.001)); + polyportal->PortalPlane = Vec4f((float)planeNormal.X, (float)planeNormal.Y, 0.0f, (float)planeD); + } + } + + sector_t *fakesector = sub->sector->heightsec; + if (fakesector && (fakesector == sub->sector || (fakesector->MoreFlags & SECF_IGNOREHEIGHTSEC) == SECF_IGNOREHEIGHTSEC)) + fakesector = nullptr; + + bool fakeflooronly = fakesector && (fakesector->MoreFlags & SECF_FAKEFLOORONLY) == SECF_FAKEFLOORONLY; + + FTextureID picnum; + bool ccw; + sector_t *frontsector; + if (fakesector) + { + // Floor and ceiling texture needs to be swapped sometimes? Why?? :( + + if (ViewPos.Z < fakesector->floorplane.Zat0()) // In water + { + if (ceiling) + { + picnum = fakesector->GetTexture(sector_t::ceiling); + ceiling = false; + frontsector = fakesector; + ccw = false; + } + else + { + picnum = fakesector->GetTexture(sector_t::floor); + frontsector = sub->sector; + ccw = true; + } + } + else if (ViewPos.Z >= fakesector->ceilingplane.Zat0() && !fakeflooronly) // In ceiling water + { + if (ceiling) + { + picnum = fakesector->GetTexture(sector_t::ceiling); + frontsector = sub->sector; + ccw = true; + } + else + { + picnum = fakesector->GetTexture(sector_t::floor); + frontsector = fakesector; + ccw = false; + ceiling = true; + } + } + else if (!ceiling) // Water surface + { + picnum = fakesector->GetTexture(sector_t::ceiling); + frontsector = fakesector; + ccw = true; + } + else if (!fakeflooronly) // Ceiling water surface + { + picnum = fakesector->GetTexture(sector_t::floor); + frontsector = fakesector; + ccw = true; + } + else // Upper ceiling + { + picnum = sub->sector->GetTexture(sector_t::ceiling); + ccw = true; + frontsector = sub->sector; + } + } + else + { + picnum = sub->sector->GetTexture(ceiling ? sector_t::ceiling : sector_t::floor); + ccw = true; + frontsector = sub->sector; + } + + FTexture *tex = TexMan(picnum); + if (tex->UseType == FTexture::TEX_Null) + return; + + bool isSky = picnum == skyflatnum; + + UVTransform transform(ceiling ? frontsector->planes[sector_t::ceiling].xform : frontsector->planes[sector_t::floor].xform, tex); + + PolyDrawArgs args; + args.uniforms.light = (uint32_t)(frontsector->lightlevel / 255.0f * 256.0f); + if (swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + args.uniforms.light = 256; + args.uniforms.flags = 0; + args.uniforms.subsectorDepth = isSky ? RenderPolyScene::SkySubsectorDepth : subsectorDepth; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(sub->numlines); + if (!vertices) + return; + + if (ceiling) + { + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + vertices[sub->numlines - 1 - i] = PlaneVertex(line->v1, isSky ? skyHeight : frontsector->ceilingplane.ZatPoint(line->v1), transform); + } + } + else + { + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + vertices[i] = PlaneVertex(line->v1, isSky ? skyHeight : frontsector->floorplane.ZatPoint(line->v1), transform); + } + } + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = sub->numlines; + args.mode = TriangleDrawMode::Fan; + args.ccw = ccw; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue + 1; + args.SetColormap(frontsector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + + if (!isSky) + { + if (!portal) + { + args.SetTexture(tex); + args.blendmode = TriBlendMode::Copy; + PolyTriangleDrawer::draw(args); + } + else + { + args.stencilwritevalue = polyportal->StencilValue; + args.writeColor = false; + args.writeSubsector = false; + PolyTriangleDrawer::draw(args); + polyportal->Shape.push_back({ args.vinput, args.vcount, args.ccw, subsectorDepth }); + polyportal->Segments.insert(polyportal->Segments.end(), portalSegments.begin(), portalSegments.end()); + } + } + else + { + if (portal) + { + args.stencilwritevalue = polyportal->StencilValue; + polyportal->Shape.push_back({ args.vinput, args.vcount, args.ccw, subsectorDepth }); + polyportal->Segments.insert(polyportal->Segments.end(), portalSegments.begin(), portalSegments.end()); + } + else + { + args.stencilwritevalue = 255; + } + + args.writeColor = false; + args.writeSubsector = false; + PolyTriangleDrawer::draw(args); + + for (uint32_t i = 0; i < sub->numlines; i++) + { + TriVertex *wallvert = PolyVertexBuffer::GetVertices(4); + if (!wallvert) + return; + + seg_t *line = &sub->firstline[i]; + + double skyBottomz1 = frontsector->ceilingplane.ZatPoint(line->v1); + double skyBottomz2 = frontsector->ceilingplane.ZatPoint(line->v2); + if (line->backsector) + { + sector_t *backsector = (line->backsector != line->frontsector) ? line->backsector : line->frontsector; + + double frontceilz1 = frontsector->ceilingplane.ZatPoint(line->v1); + double frontfloorz1 = frontsector->floorplane.ZatPoint(line->v1); + double frontceilz2 = frontsector->ceilingplane.ZatPoint(line->v2); + double frontfloorz2 = frontsector->floorplane.ZatPoint(line->v2); + + double backceilz1 = backsector->ceilingplane.ZatPoint(line->v1); + double backfloorz1 = backsector->floorplane.ZatPoint(line->v1); + double backceilz2 = backsector->ceilingplane.ZatPoint(line->v2); + double backfloorz2 = backsector->floorplane.ZatPoint(line->v2); + + double topceilz1 = frontceilz1; + double topceilz2 = frontceilz2; + double topfloorz1 = MIN(backceilz1, frontceilz1); + double topfloorz2 = MIN(backceilz2, frontceilz2); + double bottomceilz1 = MAX(frontfloorz1, backfloorz1); + double bottomceilz2 = MAX(frontfloorz2, backfloorz2); + double middleceilz1 = topfloorz1; + double middleceilz2 = topfloorz2; + double middlefloorz1 = MIN(bottomceilz1, middleceilz1); + double middlefloorz2 = MIN(bottomceilz2, middleceilz2); + + bool bothSkyCeiling = frontsector->GetTexture(sector_t::ceiling) == skyflatnum && backsector->GetTexture(sector_t::ceiling) == skyflatnum; + + bool closedSector = backceilz1 == backfloorz1 && backceilz2 == backfloorz2; + if (ceiling && bothSkyCeiling && closedSector) + { + skyBottomz1 = middlefloorz1; + skyBottomz2 = middlefloorz2; + } + else if (bothSkyCeiling) + { + continue; + } + } + + if (ceiling) + { + wallvert[0] = PlaneVertex(line->v1, skyHeight, transform); + wallvert[1] = PlaneVertex(line->v2, skyHeight, transform); + wallvert[2] = PlaneVertex(line->v2, skyBottomz2, transform); + wallvert[3] = PlaneVertex(line->v1, skyBottomz1, transform); + } + else + { + wallvert[0] = PlaneVertex(line->v1, frontsector->floorplane.ZatPoint(line->v1), transform); + wallvert[1] = PlaneVertex(line->v2, frontsector->floorplane.ZatPoint(line->v2), transform); + wallvert[2] = PlaneVertex(line->v2, skyHeight, transform); + wallvert[3] = PlaneVertex(line->v1, skyHeight, transform); + } + + args.vinput = wallvert; + args.vcount = 4; + PolyTriangleDrawer::draw(args); + + if (portal) + { + polyportal->Shape.push_back({ args.vinput, args.vcount, args.ccw, subsectorDepth }); + polyportal->Segments.insert(polyportal->Segments.end(), portalSegments.begin(), portalSegments.end()); + } + } + } +} + +TriVertex RenderPolyPlane::PlaneVertex(vertex_t *v1, double height, const UVTransform &transform) +{ + TriVertex v; + v.x = (float)v1->fPos().X; + v.y = (float)v1->fPos().Y; + v.z = (float)height; + v.w = 1.0f; + v.varying[0] = transform.GetU(v.x, v.y); + v.varying[1] = transform.GetV(v.x, v.y); + return v; +} + +RenderPolyPlane::UVTransform::UVTransform(const FTransform &transform, FTexture *tex) +{ + if (tex) + { + xscale = (float)(transform.xScale * tex->Scale.X / tex->GetWidth()); + yscale = (float)(transform.yScale * tex->Scale.Y / tex->GetHeight()); + + double planeang = (transform.Angle + transform.baseAngle).Radians(); + cosine = (float)cos(planeang); + sine = (float)sin(planeang); + + xOffs = (float)transform.xOffs; + yOffs = (float)transform.yOffs; + } + else + { + xscale = 1.0f / 64.0f; + yscale = 1.0f / 64.0f; + cosine = 1.0f; + sine = 0.0f; + xOffs = 0.0f; + yOffs = 0.0f; + } +} + +float RenderPolyPlane::UVTransform::GetU(float x, float y) const +{ + return (xOffs + x * cosine - y * sine) * xscale; +} + +float RenderPolyPlane::UVTransform::GetV(float x, float y) const +{ + return (yOffs - x * sine - y * cosine) * yscale; +} diff --git a/src/r_poly_plane.h b/src/r_poly_plane.h new file mode 100644 index 000000000..be307b4e2 --- /dev/null +++ b/src/r_poly_plane.h @@ -0,0 +1,54 @@ +/* +** Handling drawing a plane (ceiling, floor) +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class PolyDrawSectorPortal; +class PolyCull; +class Vec4f; + +class RenderPolyPlane +{ +public: + static void RenderPlanes(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, double skyCeilingHeight, double skyFloorHeight, std::vector> §orPortals); + +private: + struct UVTransform + { + UVTransform(const FTransform &transform, FTexture *tex); + + float GetU(float x, float y) const; + float GetV(float x, float y) const; + + float xscale; + float yscale; + float cosine; + float sine; + float xOffs, yOffs; + }; + + void Render3DFloor(const TriMatrix &worldToClip, const Vec4f &clipPlane, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, bool ceiling, F3DFloor *fakefloor); + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, bool ceiling, double skyHeight, std::vector> §orPortals); + TriVertex PlaneVertex(vertex_t *v1, double height, const UVTransform &transform); +}; diff --git a/src/r_poly_playersprite.cpp b/src/r_poly_playersprite.cpp new file mode 100644 index 000000000..cd9584b68 --- /dev/null +++ b/src/r_poly_playersprite.cpp @@ -0,0 +1,425 @@ +/* +** Handling drawing a player sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_playersprite.h" +#include "r_poly.h" +#include "r_things.h" // for pspritexscale + +EXTERN_CVAR(Bool, r_drawplayersprites) +EXTERN_CVAR(Bool, r_deathcamera) +EXTERN_CVAR(Bool, st_scale) +EXTERN_CVAR(Bool, r_fullbrightignoresectorcolor) +EXTERN_CVAR(Bool, r_shadercolormaps) + +void RenderPolyPlayerSprites::Render() +{ + // This code cannot be moved directly to RenderRemainingSprites because the engine + // draws the canvas textures between this call and the final call to RenderRemainingSprites.. + + if (!r_drawplayersprites || + !camera || + !camera->player || + (players[consoleplayer].cheats & CF_CHASECAM) || + (r_deathcamera && camera->health <= 0)) + return; + + float bobx, boby; + P_BobWeapon(camera->player, &bobx, &boby, r_TicFracF); + + // Interpolate the main weapon layer once so as to be able to add it to other layers. + double wx, wy; + DPSprite *weapon = camera->player->FindPSprite(PSP_WEAPON); + if (weapon) + { + if (weapon->firstTic) + { + wx = weapon->x; + wy = weapon->y; + } + else + { + wx = weapon->oldx + (weapon->x - weapon->oldx) * r_TicFracF; + wy = weapon->oldy + (weapon->y - weapon->oldy) * r_TicFracF; + } + } + else + { + wx = 0; + wy = 0; + } + + for (DPSprite *sprite = camera->player->psprites; sprite != nullptr; sprite = sprite->GetNext()) + { + // [RH] Don't draw the targeter's crosshair if the player already has a crosshair set. + // It's possible this psprite's caller is now null but the layer itself hasn't been destroyed + // because it didn't tick yet (if we typed 'take all' while in the console for example). + // In this case let's simply not draw it to avoid crashing. + if ((sprite->GetID() != PSP_TARGETCENTER || CrosshairImage == nullptr) && sprite->GetCaller() != nullptr) + { + RenderSprite(sprite, camera, bobx, boby, wx, wy, r_TicFracF); + } + } +} + +void RenderPolyPlayerSprites::RenderRemainingSprites() +{ + for (auto &sprite : ScreenSprites) + sprite.Render(); + ScreenSprites.clear(); +} + +void RenderPolyPlayerSprites::RenderSprite(DPSprite *sprite, AActor *owner, float bobx, float boby, double wx, double wy, double ticfrac) +{ + // decide which patch to use + if ((unsigned)sprite->GetSprite() >= (unsigned)sprites.Size()) + { + DPrintf(DMSG_ERROR, "RenderPlayerSprite: invalid sprite number %i\n", sprite->GetSprite()); + return; + } + + spritedef_t *def = &sprites[sprite->GetSprite()]; + if (sprite->GetFrame() >= def->numframes) + { + DPrintf(DMSG_ERROR, "RenderPlayerSprite: invalid sprite frame %i : %i\n", sprite->GetSprite(), sprite->GetFrame()); + return; + } + + spriteframe_t *frame = &SpriteFrames[def->spriteframes + sprite->GetFrame()]; + FTextureID picnum = frame->Texture[0]; + bool flip = (frame->Flip & 1) != 0; + + FTexture *tex = TexMan(picnum); + if (tex->UseType == FTexture::TEX_Null) + return; + + // Can't interpolate the first tic. + if (sprite->firstTic) + { + sprite->firstTic = false; + sprite->oldx = sprite->x; + sprite->oldy = sprite->y; + } + + double sx = sprite->oldx + (sprite->x - sprite->oldx) * ticfrac; + double sy = sprite->oldy + (sprite->y - sprite->oldy) * ticfrac; + + if (sprite->Flags & PSPF_ADDBOB) + { + sx += bobx; + sy += boby; + } + + if (sprite->Flags & PSPF_ADDWEAPON && sprite->GetID() != PSP_WEAPON) + { + sx += wx; + sy += wy; + } + + // calculate edges of the shape + double tx = sx - BaseXCenter; + + tx -= tex->GetScaledLeftOffset(); + int x1 = xs_RoundToInt(swrenderer::CenterX + tx * swrenderer::pspritexscale); + + // off the right side + if (x1 > viewwidth) + return; + + tx += tex->GetScaledWidth(); + int x2 = xs_RoundToInt(swrenderer::CenterX + tx * swrenderer::pspritexscale); + + // off the left side + if (x2 <= 0) + return; + + double texturemid = (BaseYCenter - sy) * tex->Scale.Y + tex->TopOffset; + + // Adjust PSprite for fullscreen views + if (camera->player && (RenderTarget != screen || viewheight == RenderTarget->GetHeight() || (RenderTarget->GetWidth() > (BaseXCenter * 2) && !st_scale))) + { + AWeapon *weapon = dyn_cast(sprite->GetCaller()); + if (weapon != nullptr && weapon->YAdjust != 0) + { + if (RenderTarget != screen || viewheight == RenderTarget->GetHeight()) + { + texturemid -= weapon->YAdjust; + } + else + { + texturemid -= StatusBar->GetDisplacement() * weapon->YAdjust; + } + } + } + + // Move the weapon down for 1280x1024. + if (sprite->GetID() < PSP_TARGETCENTER) + { + texturemid -= AspectPspriteOffset(WidescreenRatio); + } + + int clipped_x1 = MAX(x1, 0); + int clipped_x2 = MIN(x2, viewwidth); + double xscale = swrenderer::pspritexscale / tex->Scale.X; + double yscale = swrenderer::pspriteyscale / tex->Scale.Y; + uint32_t translation = 0; // [RH] Use default colors + + double xiscale, startfrac; + if (flip) + { + xiscale = -swrenderer::pspritexiscale * tex->Scale.X; + startfrac = 1; + } + else + { + xiscale = swrenderer::pspritexiscale * tex->Scale.X; + startfrac = 0; + } + + if (clipped_x1 > x1) + startfrac += xiscale * (clipped_x1 - x1); + + bool noaccel = false; + + FDynamicColormap *basecolormap = viewsector->ColorMap; + FDynamicColormap *colormap_to_use = basecolormap; + + visstyle_t visstyle; + visstyle.ColormapNum = 0; + visstyle.BaseColormap = basecolormap; + visstyle.Alpha = 0; + visstyle.RenderStyle = STYLE_Normal; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + int spriteshade = LIGHT2SHADE(owner->Sector->lightlevel + actualextralight); + double minz = double((2048 * 4) / double(1 << 20)); + visstyle.ColormapNum = GETPALOOKUP(swrenderer::r_SpriteVisibility / minz, spriteshade); + + if (sprite->GetID() < PSP_TARGETCENTER) + { + visstyle.Alpha = float(owner->Alpha); + visstyle.RenderStyle = owner->RenderStyle; + + // The software renderer cannot invert the source without inverting the overlay + // too. That means if the source is inverted, we need to do the reverse of what + // the invert overlay flag says to do. + INTBOOL invertcolormap = (visstyle.RenderStyle.Flags & STYLEF_InvertOverlay); + + if (visstyle.RenderStyle.Flags & STYLEF_InvertSource) + { + invertcolormap = !invertcolormap; + } + + FDynamicColormap *mybasecolormap = basecolormap; + + if (visstyle.RenderStyle.Flags & STYLEF_FadeToBlack) + { + if (invertcolormap) + { // Fade to white + mybasecolormap = GetSpecialLights(mybasecolormap->Color, MAKERGB(255, 255, 255), mybasecolormap->Desaturate); + invertcolormap = false; + } + else + { // Fade to black + mybasecolormap = GetSpecialLights(mybasecolormap->Color, MAKERGB(0, 0, 0), mybasecolormap->Desaturate); + } + } + + /* + if (swrenderer::realfixedcolormap != nullptr && (!swrenderer::r_swtruecolor || (r_shadercolormaps && screen->Accel2D))) + { // fixed color + visstyle.BaseColormap = swrenderer::realfixedcolormap; + visstyle.ColormapNum = 0; + } + else + { + if (invertcolormap) + { + mybasecolormap = GetSpecialLights(mybasecolormap->Color, mybasecolormap->Fade.InverseColor(), mybasecolormap->Desaturate); + } + if (swrenderer::fixedlightlev >= 0) + { + visstyle.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; + visstyle.ColormapNum = swrenderer::fixedlightlev >> COLORMAPSHIFT; + } + else if (!foggy && sprite->GetState()->GetFullbright()) + { // full bright + visstyle.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; // [RH] use basecolormap + visstyle.ColormapNum = 0; + } + else + { // local light + visstyle.BaseColormap = mybasecolormap; + visstyle.ColormapNum = GETPALOOKUP(0, spriteshade); + } + } + */ + + if (camera->Inventory != nullptr) + { + BYTE oldcolormapnum = visstyle.ColormapNum; + FSWColormap *oldcolormap = visstyle.BaseColormap; + camera->Inventory->AlterWeaponSprite(&visstyle); + if (visstyle.BaseColormap != oldcolormap || visstyle.ColormapNum != oldcolormapnum) + { + // The colormap has changed. Is it one we can easily identify? + // If not, then don't bother trying to identify it for + // hardware accelerated drawing. + if (visstyle.BaseColormap < &SpecialColormaps[0] || + visstyle.BaseColormap > &SpecialColormaps.Last()) + { + noaccel = true; + } + // Has the basecolormap changed? If so, we can't hardware accelerate it, + // since we don't know what it is anymore. + else if (visstyle.BaseColormap != mybasecolormap) + { + noaccel = true; + } + } + } + // If we're drawing with a special colormap, but shaders for them are disabled, do + // not accelerate. + if (!r_shadercolormaps && (visstyle.BaseColormap >= &SpecialColormaps[0] && + visstyle.BaseColormap <= &SpecialColormaps.Last())) + { + noaccel = true; + } + // If drawing with a BOOM colormap, disable acceleration. + if (mybasecolormap == &NormalLight && NormalLight.Maps != realcolormaps.Maps) + { + noaccel = true; + } + // If the main colormap has fixed lights, and this sprite is being drawn with that + // colormap, disable acceleration so that the lights can remain fixed. + if (!noaccel && swrenderer::realfixedcolormap == nullptr && + NormalLightHasFixedLights && mybasecolormap == &NormalLight && + tex->UseBasePalette()) + { + noaccel = true; + } + // [SP] If emulating GZDoom fullbright, disable acceleration + if (r_fullbrightignoresectorcolor && swrenderer::fixedlightlev >= 0) + mybasecolormap = &FullNormalLight; + if (r_fullbrightignoresectorcolor && !foggy && sprite->GetState()->GetFullbright()) + mybasecolormap = &FullNormalLight; + colormap_to_use = mybasecolormap; + } + + // Check for hardware-assisted 2D. If it's available, and this sprite is not + // fuzzy, don't draw it until after the switch to 2D mode. + if (!noaccel && RenderTarget == screen && (DFrameBuffer *)screen->Accel2D) + { + FRenderStyle style = visstyle.RenderStyle; + style.CheckFuzz(); + if (style.BlendOp != STYLEOP_Fuzz) + { + PolyScreenSprite screenSprite; + screenSprite.Pic = tex; + screenSprite.X1 = viewwindowx + x1; + screenSprite.Y1 = viewwindowy + viewheight / 2 - texturemid * yscale - 0.5; + screenSprite.Width = tex->GetWidth() * xscale; + screenSprite.Height = tex->GetHeight() * yscale; + screenSprite.Translation = TranslationToTable(translation); + screenSprite.Flip = xiscale < 0; + screenSprite.visstyle = visstyle; + screenSprite.Colormap = colormap_to_use; + ScreenSprites.push_back(screenSprite); + return; + } + } + + // To do: draw sprite same way as R_DrawVisSprite(vis) here + + // Draw the fuzzy weapon: + FRenderStyle style = visstyle.RenderStyle; + style.CheckFuzz(); + if (style.BlendOp == STYLEOP_Fuzz) + { + visstyle.RenderStyle = LegacyRenderStyles[STYLE_Shadow]; + + PolyScreenSprite screenSprite; + screenSprite.Pic = tex; + screenSprite.X1 = viewwindowx + x1; + screenSprite.Y1 = viewwindowy + viewheight / 2 - texturemid * yscale - 0.5; + screenSprite.Width = tex->GetWidth() * xscale; + screenSprite.Height = tex->GetHeight() * yscale; + screenSprite.Translation = TranslationToTable(translation); + screenSprite.Flip = xiscale < 0; + screenSprite.visstyle = visstyle; + screenSprite.Colormap = colormap_to_use; + ScreenSprites.push_back(screenSprite); + } +} + +void PolyScreenSprite::Render() +{ + FSpecialColormap *special = nullptr; + FColormapStyle colormapstyle; + PalEntry overlay = 0; + bool usecolormapstyle = false; + if (visstyle.BaseColormap >= &SpecialColormaps[0] && + visstyle.BaseColormap < &SpecialColormaps[SpecialColormaps.Size()]) + { + special = static_cast(visstyle.BaseColormap); + } + else if (Colormap->Color == PalEntry(255, 255, 255) && + Colormap->Desaturate == 0) + { + overlay = Colormap->Fade; + overlay.a = BYTE(visstyle.ColormapNum * 255 / NUMCOLORMAPS); + } + else + { + usecolormapstyle = true; + colormapstyle.Color = Colormap->Color; + colormapstyle.Fade = Colormap->Fade; + colormapstyle.Desaturate = Colormap->Desaturate; + colormapstyle.FadeLevel = visstyle.ColormapNum / float(NUMCOLORMAPS); + } + + screen->DrawTexture(Pic, + X1, + Y1, + DTA_DestWidthF, Width, + DTA_DestHeightF, Height, + DTA_Translation, Translation, + DTA_FlipX, Flip, + DTA_TopOffset, 0, + DTA_LeftOffset, 0, + DTA_ClipLeft, viewwindowx, + DTA_ClipTop, viewwindowy, + DTA_ClipRight, viewwindowx + viewwidth, + DTA_ClipBottom, viewwindowy + viewheight, + DTA_AlphaF, visstyle.Alpha, + DTA_RenderStyle, visstyle.RenderStyle, + DTA_FillColor, FillColor, + DTA_SpecialColormap, special, + DTA_ColorOverlay, overlay.d, + DTA_ColormapStyle, usecolormapstyle ? &colormapstyle : nullptr, + TAG_DONE); +} diff --git a/src/r_poly_playersprite.h b/src/r_poly_playersprite.h new file mode 100644 index 000000000..e7384e200 --- /dev/null +++ b/src/r_poly_playersprite.h @@ -0,0 +1,59 @@ +/* +** Handling drawing a player sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +class PolyScreenSprite; +class DPSprite; + +class RenderPolyPlayerSprites +{ +public: + void Render(); + void RenderRemainingSprites(); + +private: + void RenderSprite(DPSprite *sprite, AActor *owner, float bobx, float boby, double wx, double wy, double ticfrac); + + const int BaseXCenter = 160; + const int BaseYCenter = 100; + + std::vector ScreenSprites; +}; + +// DScreen accelerated sprite to be rendered +class PolyScreenSprite +{ +public: + void Render(); + + FTexture *Pic = nullptr; + double X1 = 0.0; + double Y1 = 0.0; + double Width = 0.0; + double Height = 0.0; + FRemapTable *Translation = nullptr; + bool Flip = false; + visstyle_t visstyle; + uint32_t FillColor = 0; + FDynamicColormap *Colormap = nullptr; +}; diff --git a/src/r_poly_portal.cpp b/src/r_poly_portal.cpp new file mode 100644 index 000000000..580622c1f --- /dev/null +++ b/src/r_poly_portal.cpp @@ -0,0 +1,296 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "p_maputl.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_portal.h" +#include "r_poly.h" +#include "gl/data/gl_data.h" + +extern bool r_showviewer; + +///////////////////////////////////////////////////////////////////////////// + +PolyDrawSectorPortal::PolyDrawSectorPortal(FSectorPortal *portal, bool ceiling) : Portal(portal), Ceiling(ceiling) +{ + StencilValue = PolyRenderer::Instance()->GetNextStencilValue(); +} + +void PolyDrawSectorPortal::Render(int portalDepth) +{ + if (Portal->mType == PORTS_HORIZON || Portal->mType == PORTS_PLANE) + return; + + SaveGlobals(); + + // To do: get this information from PolyRenderer instead of duplicating the code.. + double radPitch = ViewPitch.Normalized180().Radians(); + double angx = cos(radPitch); + double angy = sin(radPitch) * glset.pixelstretch; + double alen = sqrt(angx*angx + angy*angy); + float adjustedPitch = (float)asin(angy / alen); + float adjustedViewAngle = (float)(ViewAngle - 90).Radians(); + float ratio = WidescreenRatio; + float fovratio = (WidescreenRatio >= 1.3f) ? 1.333333f : ratio; + float fovy = (float)(2 * DAngle::ToDegrees(atan(tan(FieldOfView.Radians() / 2) / fovratio)).Degrees); + TriMatrix worldToView = + TriMatrix::rotate(adjustedPitch, 1.0f, 0.0f, 0.0f) * + TriMatrix::rotate(adjustedViewAngle, 0.0f, -1.0f, 0.0f) * + TriMatrix::scale(1.0f, glset.pixelstretch, 1.0f) * + TriMatrix::swapYZ() * + TriMatrix::translate((float)-ViewPos.X, (float)-ViewPos.Y, (float)-ViewPos.Z); + TriMatrix worldToClip = TriMatrix::perspective(fovy, ratio, 5.0f, 65535.0f) * worldToView; + + RenderPortal.SetViewpoint(worldToClip, PortalPlane, StencilValue); + RenderPortal.SetPortalSegments(Segments); + RenderPortal.Render(portalDepth); + + RestoreGlobals(); +} + +void PolyDrawSectorPortal::RenderTranslucent(int portalDepth) +{ + if (Portal->mType == PORTS_HORIZON || Portal->mType == PORTS_PLANE) + return; + + SaveGlobals(); + + RenderPortal.RenderTranslucent(portalDepth); + + RestoreGlobals(); +} + +void PolyDrawSectorPortal::SaveGlobals() +{ + savedextralight = extralight; + savedpos = ViewPos; + savedangle = ViewAngle; + savedvisibility = swrenderer::R_GetVisibility(); + savedcamera = camera; + savedsector = viewsector; + + if (Portal->mType == PORTS_SKYVIEWPOINT) + { + // Don't let gun flashes brighten the sky box + ASkyViewpoint *sky = barrier_cast(Portal->mSkybox); + extralight = 0; + swrenderer::R_SetVisibility(sky->args[0] * 0.25f); + ViewPos = sky->InterpolatedPosition(r_TicFracF); + ViewAngle = savedangle + (sky->PrevAngles.Yaw + deltaangle(sky->PrevAngles.Yaw, sky->Angles.Yaw) * r_TicFracF); + } + else //if (Portal->mType == PORTS_STACKEDSECTORTHING || Portal->mType == PORTS_PORTAL || Portal->mType == PORTS_LINKEDPORTAL) + { + //extralight = pl->extralight; + //swrenderer::R_SetVisibility(pl->visibility); + ViewPos.X += Portal->mDisplacement.X; + ViewPos.Y += Portal->mDisplacement.Y; + } + + camera = nullptr; + viewsector = Portal->mDestination; + R_SetViewAngle(); + + Portal->mFlags |= PORTSF_INSKYBOX; + if (Portal->mPartner > 0) sectorPortals[Portal->mPartner].mFlags |= PORTSF_INSKYBOX; +} + +void PolyDrawSectorPortal::RestoreGlobals() +{ + Portal->mFlags &= ~PORTSF_INSKYBOX; + if (Portal->mPartner > 0) sectorPortals[Portal->mPartner].mFlags &= ~PORTSF_INSKYBOX; + + camera = savedcamera; + viewsector = savedsector; + ViewPos = savedpos; + swrenderer::R_SetVisibility(savedvisibility); + extralight = savedextralight; + ViewAngle = savedangle; + R_SetViewAngle(); +} + +///////////////////////////////////////////////////////////////////////////// + +PolyDrawLinePortal::PolyDrawLinePortal(FLinePortal *portal) : Portal(portal) +{ + StencilValue = PolyRenderer::Instance()->GetNextStencilValue(); +} + +PolyDrawLinePortal::PolyDrawLinePortal(line_t *mirror) : Mirror(mirror) +{ + StencilValue = PolyRenderer::Instance()->GetNextStencilValue(); +} + +void PolyDrawLinePortal::Render(int portalDepth) +{ + SaveGlobals(); + + // To do: get this information from PolyRenderer instead of duplicating the code.. + double radPitch = ViewPitch.Normalized180().Radians(); + double angx = cos(radPitch); + double angy = sin(radPitch) * glset.pixelstretch; + double alen = sqrt(angx*angx + angy*angy); + float adjustedPitch = (float)asin(angy / alen); + float adjustedViewAngle = (float)(ViewAngle - 90).Radians(); + float ratio = WidescreenRatio; + float fovratio = (WidescreenRatio >= 1.3f) ? 1.333333f : ratio; + float fovy = (float)(2 * DAngle::ToDegrees(atan(tan(FieldOfView.Radians() / 2) / fovratio)).Degrees); + TriMatrix worldToView = + TriMatrix::rotate(adjustedPitch, 1.0f, 0.0f, 0.0f) * + TriMatrix::rotate(adjustedViewAngle, 0.0f, -1.0f, 0.0f) * + TriMatrix::scale(1.0f, glset.pixelstretch, 1.0f) * + TriMatrix::swapYZ() * + TriMatrix::translate((float)-ViewPos.X, (float)-ViewPos.Y, (float)-ViewPos.Z); + if (Mirror) + worldToView = TriMatrix::scale(-1.0f, 1.0f, 1.0f) * worldToView; + TriMatrix worldToClip = TriMatrix::perspective(fovy, ratio, 5.0f, 65535.0f) * worldToView; + + // Calculate plane clipping + line_t *clipLine = Portal ? Portal->mDestination : Mirror; + DVector2 planePos = clipLine->v1->fPos(); + DVector2 planeNormal = (clipLine->v2->fPos() - clipLine->v1->fPos()).Rotated90CW(); + planeNormal.MakeUnit(); + double planeD = -(planeNormal | (planePos + planeNormal * 0.001)); + Vec4f portalPlane((float)planeNormal.X, (float)planeNormal.Y, 0.0f, (float)planeD); + + RenderPortal.SetViewpoint(worldToClip, portalPlane, StencilValue); + RenderPortal.SetPortalSegments(Segments); + RenderPortal.Render(portalDepth); + + RestoreGlobals(); +} + +void PolyDrawLinePortal::RenderTranslucent(int portalDepth) +{ + SaveGlobals(); + RenderPortal.RenderTranslucent(portalDepth); + RestoreGlobals(); +} + +void PolyDrawLinePortal::SaveGlobals() +{ + savedextralight = extralight; + savedpos = ViewPos; + savedangle = ViewAngle; + savedcamera = camera; + savedsector = viewsector; + savedinvisibility = camera ? (camera->renderflags & RF_INVISIBLE) == RF_INVISIBLE : false; + savedViewPath[0] = ViewPath[0]; + savedViewPath[1] = ViewPath[1]; + + if (Mirror) + { + DAngle startang = ViewAngle; + DVector3 startpos = ViewPos; + + vertex_t *v1 = Mirror->v1; + + // Reflect the current view behind the mirror. + if (Mirror->Delta().X == 0) + { // vertical mirror + ViewPos.X = v1->fX() - startpos.X + v1->fX(); + } + else if (Mirror->Delta().Y == 0) + { // horizontal mirror + ViewPos.Y = v1->fY() - startpos.Y + v1->fY(); + } + else + { // any mirror + vertex_t *v2 = Mirror->v2; + + double dx = v2->fX() - v1->fX(); + double dy = v2->fY() - v1->fY(); + double x1 = v1->fX(); + double y1 = v1->fY(); + double x = startpos.X; + double y = startpos.Y; + + // the above two cases catch len == 0 + double r = ((x - x1)*dx + (y - y1)*dy) / (dx*dx + dy*dy); + + ViewPos.X = (x1 + r * dx) * 2 - x; + ViewPos.Y = (y1 + r * dy) * 2 - y; + } + ViewAngle = Mirror->Delta().Angle() * 2 - startang; + + if (camera) + camera->renderflags &= ~RF_INVISIBLE; + } + else + { + auto src = Portal->mOrigin; + auto dst = Portal->mDestination; + + P_TranslatePortalXY(src, ViewPos.X, ViewPos.Y); + P_TranslatePortalZ(src, ViewPos.Z); + P_TranslatePortalAngle(src, ViewAngle); + P_TranslatePortalXY(src, ViewPath[0].X, ViewPath[0].Y); + P_TranslatePortalXY(src, ViewPath[1].X, ViewPath[1].Y); + + if (!r_showviewer && camera && P_PointOnLineSidePrecise(ViewPath[0], dst) != P_PointOnLineSidePrecise(ViewPath[1], dst)) + { + double distp = (ViewPath[0] - ViewPath[1]).Length(); + if (distp > EQUAL_EPSILON) + { + double dist1 = (ViewPos - ViewPath[0]).Length(); + double dist2 = (ViewPos - ViewPath[1]).Length(); + + if (dist1 + dist2 < distp + 1) + { + camera->renderflags |= RF_INVISIBLE; + } + } + } + } + + //camera = nullptr; + //viewsector = R_PointInSubsector(ViewPos)->sector; + R_SetViewAngle(); + + if (Mirror) + PolyTriangleDrawer::toggle_mirror(); +} + +void PolyDrawLinePortal::RestoreGlobals() +{ + if (camera) + { + if (savedinvisibility) + camera->renderflags |= RF_INVISIBLE; + else + camera->renderflags &= ~RF_INVISIBLE; + } + camera = savedcamera; + viewsector = savedsector; + ViewPos = savedpos; + extralight = savedextralight; + ViewAngle = savedangle; + ViewPath[0] = savedViewPath[0]; + ViewPath[1] = savedViewPath[1]; + R_SetViewAngle(); + + if (Mirror) + PolyTriangleDrawer::toggle_mirror(); +} diff --git a/src/r_poly_portal.h b/src/r_poly_portal.h new file mode 100644 index 000000000..4f2356761 --- /dev/null +++ b/src/r_poly_portal.h @@ -0,0 +1,100 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_scene.h" + +struct PolyPortalVertexRange +{ + PolyPortalVertexRange(const TriVertex *vertices, int count, bool ccw, uint32_t subsectorDepth) : Vertices(vertices), Count(count), Ccw(ccw), SubsectorDepth(subsectorDepth) { } + const TriVertex *Vertices; + int Count; + bool Ccw; + uint32_t SubsectorDepth; +}; + +class PolyPortalSegment +{ +public: + PolyPortalSegment(int x1, int x2) : X1(x1), X2(x2) { } + int X1, X2; +}; + +class PolyDrawSectorPortal +{ +public: + PolyDrawSectorPortal(FSectorPortal *portal, bool ceiling); + + void Render(int portalDepth); + void RenderTranslucent(int portalDepth); + + FSectorPortal *Portal = nullptr; + uint32_t StencilValue = 0; + std::vector Shape; + std::vector Segments; + Vec4f PortalPlane = Vec4f(0.0f); + +private: + void SaveGlobals(); + void RestoreGlobals(); + + bool Ceiling; + RenderPolyScene RenderPortal; + + int savedextralight; + DVector3 savedpos; + DAngle savedangle; + double savedvisibility; + AActor *savedcamera; + sector_t *savedsector; +}; + +class PolyDrawLinePortal +{ +public: + PolyDrawLinePortal(FLinePortal *portal); + PolyDrawLinePortal(line_t *mirror); + + void Render(int portalDepth); + void RenderTranslucent(int portalDepth); + + FLinePortal *Portal = nullptr; + line_t *Mirror = nullptr; + uint32_t StencilValue = 0; + std::vector Shape; + std::vector Segments; + +private: + void SaveGlobals(); + void RestoreGlobals(); + + RenderPolyScene RenderPortal; + + int savedextralight; + DVector3 savedpos; + DAngle savedangle; + AActor *savedcamera; + sector_t *savedsector; + bool savedinvisibility; + DVector3 savedViewPath[2]; +}; diff --git a/src/r_poly_scene.cpp b/src/r_poly_scene.cpp new file mode 100644 index 000000000..8bf6d1ce9 --- /dev/null +++ b/src/r_poly_scene.cpp @@ -0,0 +1,365 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "p_maputl.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_scene.h" +#include "r_poly.h" +#include "gl/data/gl_data.h" + +CVAR(Bool, r_debug_cull, 0, 0) +EXTERN_CVAR(Int, r_portal_recursions) + +///////////////////////////////////////////////////////////////////////////// + +RenderPolyScene::RenderPolyScene() +{ +} + +RenderPolyScene::~RenderPolyScene() +{ +} + +void RenderPolyScene::SetViewpoint(const TriMatrix &worldToClip, const Vec4f &portalPlane, uint32_t stencilValue) +{ + WorldToClip = worldToClip; + StencilValue = stencilValue; + PortalPlane = portalPlane; +} + +void RenderPolyScene::SetPortalSegments(const std::vector &segments) +{ + Cull.ClearSolidSegments(); + for (const auto &segment : segments) + { + Cull.MarkSegmentCulled(segment.X1, segment.X2); + } + Cull.InvertSegments(); + PortalSegmentsAdded = true; +} + +void RenderPolyScene::Render(int portalDepth) +{ + ClearBuffers(); + if (!PortalSegmentsAdded) + Cull.ClearSolidSegments(); + Cull.CullScene(WorldToClip, PortalPlane); + Cull.ClearSolidSegments(); + RenderSectors(); + RenderPortals(portalDepth); +} + +void RenderPolyScene::ClearBuffers() +{ + SeenSectors.clear(); + SubsectorDepths.clear(); + TranslucentObjects.clear(); + SectorPortals.clear(); + LinePortals.clear(); + NextSubsectorDepth = 0; +} + +void RenderPolyScene::RenderSectors() +{ + if (r_debug_cull) + { + for (auto it = Cull.PvsSectors.rbegin(); it != Cull.PvsSectors.rend(); ++it) + RenderSubsector(*it); + } + else + { + for (auto it = Cull.PvsSectors.begin(); it != Cull.PvsSectors.end(); ++it) + RenderSubsector(*it); + } +} + +void RenderPolyScene::RenderSubsector(subsector_t *sub) +{ + sector_t *frontsector = sub->sector; + frontsector->MoreFlags |= SECF_DRAWN; + + uint32_t subsectorDepth = NextSubsectorDepth++; + + if (sub->sector->CenterFloor() != sub->sector->CenterCeiling()) + { + RenderPolyPlane::RenderPlanes(WorldToClip, PortalPlane, Cull, sub, subsectorDepth, StencilValue, Cull.MaxCeilingHeight, Cull.MinFloorHeight, SectorPortals); + } + + for (uint32_t i = 0; i < sub->numlines; i++) + { + seg_t *line = &sub->firstline[i]; + if (line->sidedef == nullptr || !(line->sidedef->Flags & WALLF_POLYOBJ)) + { + RenderLine(sub, line, frontsector, subsectorDepth); + } + } + + bool mainBSP = ((unsigned int)(sub - subsectors) < (unsigned int)numsubsectors); + if (mainBSP) + { + int subsectorIndex = (int)(sub - subsectors); + for (int i = ParticlesInSubsec[subsectorIndex]; i != NO_PARTICLE; i = Particles[i].snext) + { + particle_t *particle = Particles + i; + TranslucentObjects.push_back({ particle, sub, subsectorDepth }); + } + } + + SeenSectors.insert(sub->sector); + SubsectorDepths[sub] = subsectorDepth; +} + +void RenderPolyScene::RenderSprite(AActor *thing, double sortDistance, const DVector2 &left, const DVector2 &right) +{ + if (numnodes == 0) + { + subsector_t *sub = subsectors; + auto it = SubsectorDepths.find(sub); + if (it != SubsectorDepths.end()) + TranslucentObjects.push_back({ thing, sub, it->second, sortDistance, 0.0f, 1.0f }); + } + else + { + RenderSprite(thing, sortDistance, left, right, 0.0, 1.0, nodes + numnodes - 1); // The head node is the last node output. + } +} + +void RenderPolyScene::RenderSprite(AActor *thing, double sortDistance, DVector2 left, DVector2 right, double t1, double t2, void *node) +{ + while (!((size_t)node & 1)) // Keep going until found a subsector + { + node_t *bsp = (node_t *)node; + + DVector2 planePos(FIXED2DBL(bsp->x), FIXED2DBL(bsp->y)); + DVector2 planeNormal = DVector2(FIXED2DBL(-bsp->dy), FIXED2DBL(bsp->dx)); + double planeD = planeNormal | planePos; + + int sideLeft = (left | planeNormal) > planeD; + int sideRight = (right | planeNormal) > planeD; + + if (sideLeft != sideRight) + { + double dotLeft = planeNormal | left; + double dotRight = planeNormal | right; + double t = (planeD - dotLeft) / (dotRight - dotLeft); + + DVector2 mid = left * (1.0 - t) + right * t; + double tmid = t1 * (1.0 - t) + t2 * t; + + RenderSprite(thing, sortDistance, mid, right, tmid, t2, bsp->children[sideRight]); + right = mid; + t2 = tmid; + } + node = bsp->children[sideLeft]; + } + + subsector_t *sub = (subsector_t *)((BYTE *)node - 1); + + auto it = SubsectorDepths.find(sub); + if (it != SubsectorDepths.end()) + TranslucentObjects.push_back({ thing, sub, it->second, sortDistance, (float)t1, (float)t2 }); +} + +void RenderPolyScene::RenderLine(subsector_t *sub, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth) +{ + // Reject lines not facing viewer + DVector2 pt1 = line->v1->fPos() - ViewPos; + DVector2 pt2 = line->v2->fPos() - ViewPos; + if (pt1.Y * (pt1.X - pt2.X) + pt1.X * (pt2.Y - pt1.Y) >= 0) + return; + + // Cull wall if not visible + int sx1, sx2; + LineSegmentRange segmentRange = Cull.GetSegmentRangeForLine(line->v1->fX(), line->v1->fY(), line->v2->fX(), line->v2->fY(), sx1, sx2); + if (segmentRange == LineSegmentRange::NotVisible || (segmentRange == LineSegmentRange::HasSegment && Cull.IsSegmentCulled(sx1, sx2))) + return; + + // Tell automap we saw this + if (!PolyRenderer::Instance()->DontMapLines && line->linedef && segmentRange != LineSegmentRange::AlwaysVisible) + { + line->linedef->flags |= ML_MAPPED; + sub->flags |= SSECF_DRAWN; + } + + // Render 3D floor sides + if (line->backsector && frontsector->e && line->backsector->e->XFloor.ffloors.Size()) + { + for (unsigned int i = 0; i < line->backsector->e->XFloor.ffloors.Size(); i++) + { + F3DFloor *fakeFloor = line->backsector->e->XFloor.ffloors[i]; + if (!(fakeFloor->flags & FF_EXISTS)) continue; + if (!(fakeFloor->flags & FF_RENDERPLANES)) continue; + if (!fakeFloor->model) continue; + RenderPolyWall::Render3DFloorLine(WorldToClip, PortalPlane, Cull, line, frontsector, subsectorDepth, StencilValue, fakeFloor, TranslucentObjects); + } + } + + // Render wall, and update culling info if its an occlusion blocker + if (RenderPolyWall::RenderLine(WorldToClip, PortalPlane, Cull, line, frontsector, subsectorDepth, StencilValue, TranslucentObjects, LinePortals)) + { + if (segmentRange == LineSegmentRange::HasSegment) + Cull.MarkSegmentCulled(sx1, sx2); + } +} + +void RenderPolyScene::RenderPortals(int portalDepth) +{ + if (portalDepth < r_portal_recursions) + { + for (auto &portal : SectorPortals) + portal->Render(portalDepth + 1); + + for (auto &portal : LinePortals) + portal->Render(portalDepth + 1); + } + else // Fill with black + { + PolyDrawArgs args; + args.objectToClip = &WorldToClip; + args.mode = TriangleDrawMode::Fan; + args.uniforms.color = 0; + args.uniforms.light = 256; + args.uniforms.flags = TriUniforms::fixed_light; + args.SetClipPlane(PortalPlane.x, PortalPlane.y, PortalPlane.z, PortalPlane.w); + + for (auto &portal : SectorPortals) + { + args.stenciltestvalue = portal->StencilValue; + args.stencilwritevalue = portal->StencilValue + 1; + for (const auto &verts : portal->Shape) + { + args.vinput = verts.Vertices; + args.vcount = verts.Count; + args.ccw = verts.Ccw; + args.uniforms.subsectorDepth = verts.SubsectorDepth; + args.blendmode = TriBlendMode::Copy; + PolyTriangleDrawer::draw(args); + } + } + + for (auto &portal : LinePortals) + { + args.stenciltestvalue = portal->StencilValue; + args.stencilwritevalue = portal->StencilValue + 1; + for (const auto &verts : portal->Shape) + { + args.vinput = verts.Vertices; + args.vcount = verts.Count; + args.ccw = verts.Ccw; + args.uniforms.subsectorDepth = verts.SubsectorDepth; + PolyTriangleDrawer::draw(args); + } + } + } +} + +void RenderPolyScene::RenderTranslucent(int portalDepth) +{ + if (portalDepth < r_portal_recursions) + { + for (auto it = SectorPortals.rbegin(); it != SectorPortals.rend(); ++it) + { + auto &portal = *it; + portal->RenderTranslucent(portalDepth + 1); + + PolyDrawArgs args; + args.objectToClip = &WorldToClip; + args.mode = TriangleDrawMode::Fan; + args.stenciltestvalue = portal->StencilValue + 1; + args.stencilwritevalue = StencilValue + 1; + args.SetClipPlane(PortalPlane.x, PortalPlane.y, PortalPlane.z, PortalPlane.w); + for (const auto &verts : portal->Shape) + { + args.vinput = verts.Vertices; + args.vcount = verts.Count; + args.ccw = verts.Ccw; + args.uniforms.subsectorDepth = verts.SubsectorDepth; + args.writeColor = false; + PolyTriangleDrawer::draw(args); + } + } + + for (auto it = LinePortals.rbegin(); it != LinePortals.rend(); ++it) + { + auto &portal = *it; + portal->RenderTranslucent(portalDepth + 1); + + PolyDrawArgs args; + args.objectToClip = &WorldToClip; + args.mode = TriangleDrawMode::Fan; + args.stenciltestvalue = portal->StencilValue + 1; + args.stencilwritevalue = StencilValue + 1; + args.SetClipPlane(PortalPlane.x, PortalPlane.y, PortalPlane.z, PortalPlane.w); + for (const auto &verts : portal->Shape) + { + args.vinput = verts.Vertices; + args.vcount = verts.Count; + args.ccw = verts.Ccw; + args.uniforms.subsectorDepth = verts.SubsectorDepth; + args.writeColor = false; + PolyTriangleDrawer::draw(args); + } + } + } + + for (sector_t *sector : SeenSectors) + { + for (AActor *thing = sector->thinglist; thing != nullptr; thing = thing->snext) + { + DVector2 left, right; + if (!RenderPolySprite::GetLine(thing, left, right)) + continue; + double distanceSquared = (thing->Pos() - ViewPos).LengthSquared(); + RenderSprite(thing, distanceSquared, left, right); + } + } + + std::stable_sort(TranslucentObjects.begin(), TranslucentObjects.end()); + + for (auto it = TranslucentObjects.rbegin(); it != TranslucentObjects.rend(); ++it) + { + auto &obj = *it; + if (obj.particle) + { + RenderPolyParticle spr; + spr.Render(WorldToClip, PortalPlane, obj.particle, obj.sub, obj.subsectorDepth, StencilValue + 1); + } + else if (!obj.thing) + { + obj.wall.Render(WorldToClip, PortalPlane, Cull); + } + else if ((obj.thing->renderflags & RF_SPRITETYPEMASK) == RF_WALLSPRITE) + { + RenderPolyWallSprite wallspr; + wallspr.Render(WorldToClip, PortalPlane, obj.thing, obj.sub, obj.subsectorDepth, StencilValue + 1); + } + else + { + RenderPolySprite spr; + spr.Render(WorldToClip, PortalPlane, obj.thing, obj.sub, obj.subsectorDepth, StencilValue + 1, obj.SpriteLeft, obj.SpriteRight); + } + } +} diff --git a/src/r_poly_scene.h b/src/r_poly_scene.h new file mode 100644 index 000000000..00502e53e --- /dev/null +++ b/src/r_poly_scene.h @@ -0,0 +1,106 @@ +/* +** Polygon Doom software renderer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include +#include +#include +#include +#include "doomdata.h" +#include "r_utility.h" +#include "r_main.h" +#include "r_poly_triangle.h" +#include "r_poly_intersection.h" +#include "r_poly_wall.h" +#include "r_poly_sprite.h" +#include "r_poly_wallsprite.h" +#include "r_poly_playersprite.h" +#include "r_poly_particle.h" +#include "r_poly_plane.h" +#include "r_poly_cull.h" +#include +#include + +class PolyTranslucentObject +{ +public: + PolyTranslucentObject(particle_t *particle, subsector_t *sub, uint32_t subsectorDepth) : particle(particle), sub(sub), subsectorDepth(subsectorDepth) { } + PolyTranslucentObject(AActor *thing, subsector_t *sub, uint32_t subsectorDepth, double dist, float t1, float t2) : thing(thing), sub(sub), subsectorDepth(subsectorDepth), DistanceSquared(dist), SpriteLeft(t1), SpriteRight(t2) { } + PolyTranslucentObject(RenderPolyWall wall) : wall(wall), subsectorDepth(wall.SubsectorDepth), DistanceSquared(1.e6) { } + + bool operator<(const PolyTranslucentObject &other) const + { + return subsectorDepth != other.subsectorDepth ? subsectorDepth < other.subsectorDepth : DistanceSquared < other.DistanceSquared; + } + + particle_t *particle = nullptr; + AActor *thing = nullptr; + subsector_t *sub = nullptr; + + RenderPolyWall wall; + + uint32_t subsectorDepth = 0; + double DistanceSquared = 0.0; + + float SpriteLeft = 0.0f, SpriteRight = 1.0f; +}; + +class PolyDrawSectorPortal; +class PolyDrawLinePortal; +class PolyPortalSegment; + +// Renders everything from a specific viewpoint +class RenderPolyScene +{ +public: + RenderPolyScene(); + ~RenderPolyScene(); + void SetViewpoint(const TriMatrix &worldToClip, const Vec4f &portalPlane, uint32_t stencilValue); + void SetPortalSegments(const std::vector &segments); + void Render(int portalDepth); + void RenderTranslucent(int portalDepth); + + static const uint32_t SkySubsectorDepth = 0x7fffffff; + +private: + void ClearBuffers(); + void RenderPortals(int portalDepth); + void RenderSectors(); + void RenderSubsector(subsector_t *sub); + void RenderLine(subsector_t *sub, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth); + void RenderSprite(AActor *thing, double sortDistance, const DVector2 &left, const DVector2 &right); + void RenderSprite(AActor *thing, double sortDistance, DVector2 left, DVector2 right, double t1, double t2, void *node); + + TriMatrix WorldToClip; + Vec4f PortalPlane; + uint32_t StencilValue = 0; + PolyCull Cull; + uint32_t NextSubsectorDepth = 0; + std::set SeenSectors; + std::unordered_map SubsectorDepths; + std::vector TranslucentObjects; + + std::vector> SectorPortals; + std::vector> LinePortals; + bool PortalSegmentsAdded = false; +}; diff --git a/src/r_poly_sky.cpp b/src/r_poly_sky.cpp new file mode 100644 index 000000000..d2ea632b8 --- /dev/null +++ b/src/r_poly_sky.cpp @@ -0,0 +1,183 @@ +/* +** Sky dome rendering +** Copyright(C) 2003-2016 Christoph Oelckers +** All rights reserved. +** +** This program is free software: you can redistribute it and/or modify +** it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public License +** along with this program. If not, see http:**www.gnu.org/licenses/ +** +** Loosely based on the JDoom sky and the ZDoomGL 0.66.2 sky. +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_sky.h" +#include "r_poly_portal.h" +#include "r_sky.h" // for skyflatnum + +PolySkyDome::PolySkyDome() +{ + CreateDome(); +} + +void PolySkyDome::Render(const TriMatrix &worldToClip) +{ + FTextureID sky1tex, sky2tex; + if ((level.flags & LEVEL_SWAPSKIES) && !(level.flags & LEVEL_DOUBLESKY)) + sky1tex = sky2texture; + else + sky1tex = sky1texture; + sky2tex = sky2texture; + + FTexture *frontskytex = TexMan(sky1tex, true); + FTexture *backskytex = nullptr; + if (level.flags & LEVEL_DOUBLESKY) + backskytex = TexMan(sky2tex, true); + + TriMatrix objectToWorld = TriMatrix::translate((float)ViewPos.X, (float)ViewPos.Y, (float)ViewPos.Z); + objectToClip = worldToClip * objectToWorld; + + int rc = mRows + 1; + + PolyDrawArgs args; + args.uniforms.light = 256; + args.uniforms.flags = 0; + args.uniforms.subsectorDepth = RenderPolyScene::SkySubsectorDepth; + args.objectToClip = &objectToClip; + args.stenciltestvalue = 255; + args.stencilwritevalue = 1; + args.SetColormap(&NormalLight); + args.SetClipPlane(0.0f, 0.0f, 0.0f, 0.0f); + + RenderCapColorRow(args, frontskytex, 0, false); + RenderCapColorRow(args, frontskytex, rc, true); + + args.SetTexture(frontskytex); + + uint32_t topcapcolor = frontskytex->GetSkyCapColor(false); + uint32_t bottomcapcolor = frontskytex->GetSkyCapColor(true); + + for (int i = 1; i <= mRows; i++) + { + RenderRow(args, i, topcapcolor); + RenderRow(args, rc + i, bottomcapcolor); + } +} + +void PolySkyDome::RenderRow(PolyDrawArgs &args, int row, uint32_t capcolor) +{ + args.vinput = &mVertices[mPrimStart[row]]; + args.vcount = mPrimStart[row + 1] - mPrimStart[row]; + args.mode = TriangleDrawMode::Strip; + args.ccw = false; + args.uniforms.color = capcolor; + args.blendmode = TriBlendMode::Skycap; + PolyTriangleDrawer::draw(args); +} + +void PolySkyDome::RenderCapColorRow(PolyDrawArgs &args, FTexture *skytex, int row, bool bottomCap) +{ + uint32_t solid = skytex->GetSkyCapColor(bottomCap); + if (!swrenderer::r_swtruecolor) + solid = RGB32k.RGB[(RPART(solid) >> 3)][(GPART(solid) >> 3)][(BPART(solid) >> 3)]; + + args.vinput = &mVertices[mPrimStart[row]]; + args.vcount = mPrimStart[row + 1] - mPrimStart[row]; + args.mode = TriangleDrawMode::Fan; + args.ccw = bottomCap; + args.uniforms.color = solid; + args.blendmode = TriBlendMode::Copy; + PolyTriangleDrawer::draw(args); +} + +void PolySkyDome::CreateDome() +{ + mColumns = 16;// 128; + mRows = 4; + CreateSkyHemisphere(false); + CreateSkyHemisphere(true); + mPrimStart.Push(mVertices.Size()); +} + +void PolySkyDome::CreateSkyHemisphere(bool zflip) +{ + int r, c; + + mPrimStart.Push(mVertices.Size()); + + for (c = 0; c < mColumns; c++) + { + SkyVertex(1, c, zflip); + } + + // The total number of triangles per hemisphere can be calculated + // as follows: rows * columns * 2 + 2 (for the top cap). + for (r = 0; r < mRows; r++) + { + mPrimStart.Push(mVertices.Size()); + for (c = 0; c <= mColumns; c++) + { + SkyVertex(r + zflip, c, zflip); + SkyVertex(r + 1 - zflip, c, zflip); + } + } +} + +TriVertex PolySkyDome::SetVertexXYZ(float xx, float yy, float zz, float uu, float vv) +{ + TriVertex v; + v.x = xx; + v.y = zz; + v.z = yy; + v.w = 1.0f; + v.varying[0] = uu; + v.varying[1] = vv; + return v; +} + +void PolySkyDome::SkyVertex(int r, int c, bool zflip) +{ + static const FAngle maxSideAngle = 60.f; + static const float scale = 10000.; + + FAngle topAngle = (c / (float)mColumns * 360.f); + FAngle sideAngle = maxSideAngle * (float)(mRows - r) / (float)mRows; + float height = sideAngle.Sin(); + float realRadius = scale * sideAngle.Cos(); + FVector2 pos = topAngle.ToVector(realRadius); + float z = (!zflip) ? scale * height : -scale * height; + + float u, v; + + // And the texture coordinates. + if (!zflip) // Flipped Y is for the lower hemisphere. + { + u = (-c / (float)mColumns); + v = (r / (float)mRows); + } + else + { + u = (-c / (float)mColumns); + v = 1.0f + ((mRows - r) / (float)mRows); + } + + if (r != 4) z += 300; + + // And finally the vertex. + TriVertex vert; + vert = SetVertexXYZ(-pos.X, z - 1.f, pos.Y, u * 4.0f, v * 1.2f - 0.5f); + mVertices.Push(vert); +} diff --git a/src/r_poly_sky.h b/src/r_poly_sky.h new file mode 100644 index 000000000..1f5a655b9 --- /dev/null +++ b/src/r_poly_sky.h @@ -0,0 +1,45 @@ +/* +** Sky dome rendering +** Copyright(C) 2003-2016 Christoph Oelckers +** All rights reserved. +** +** This program is free software: you can redistribute it and/or modify +** it under the terms of the GNU Lesser 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 Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public License +** along with this program. If not, see http:**www.gnu.org/licenses/ +** +** Loosely based on the JDoom sky and the ZDoomGL 0.66.2 sky. +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class PolySkyDome +{ +public: + PolySkyDome(); + void Render(const TriMatrix &worldToClip); + +private: + TArray mVertices; + TArray mPrimStart; + int mRows, mColumns; + TriMatrix objectToClip; + + void SkyVertex(int r, int c, bool yflip); + void CreateSkyHemisphere(bool zflip); + void CreateDome(); + void RenderRow(PolyDrawArgs &args, int row, uint32_t capcolor); + void RenderCapColorRow(PolyDrawArgs &args, FTexture *skytex, int row, bool bottomCap); + + TriVertex SetVertexXYZ(float xx, float yy, float zz, float uu = 0, float vv = 0); +}; diff --git a/src/r_poly_sprite.cpp b/src/r_poly_sprite.cpp new file mode 100644 index 000000000..182135753 --- /dev/null +++ b/src/r_poly_sprite.cpp @@ -0,0 +1,433 @@ +/* +** Handling drawing a sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_sprite.h" +#include "r_poly.h" +#include "r_poly_intersection.h" + +EXTERN_CVAR(Float, transsouls) +EXTERN_CVAR(Int, r_drawfuzz) + +bool RenderPolySprite::GetLine(AActor *thing, DVector2 &left, DVector2 &right) +{ + if (IsThingCulled(thing)) + return false; + + DVector3 pos = thing->InterpolatedPosition(r_TicFracF); + + bool flipTextureX = false; + FTexture *tex = GetSpriteTexture(thing, flipTextureX); + if (tex == nullptr) + return false; + + DVector2 spriteScale = thing->Scale; + double thingxscalemul = spriteScale.X / tex->Scale.X; + double thingyscalemul = spriteScale.Y / tex->Scale.Y; + + if (flipTextureX) + pos.X -= (tex->GetWidth() - tex->LeftOffset) * thingxscalemul; + else + pos.X -= tex->LeftOffset * thingxscalemul; + + double spriteHalfWidth = thingxscalemul * tex->GetWidth() * 0.5; + double spriteHeight = thingyscalemul * tex->GetHeight(); + + pos.X += spriteHalfWidth; + + left = DVector2(pos.X - ViewSin * spriteHalfWidth, pos.Y + ViewCos * spriteHalfWidth); + right = DVector2(pos.X + ViewSin * spriteHalfWidth, pos.Y - ViewCos * spriteHalfWidth); + return true; +} + +void RenderPolySprite::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, AActor *thing, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, float t1, float t2) +{ + DVector2 line[2]; + if (!GetLine(thing, line[0], line[1])) + return; + + DVector3 pos = thing->InterpolatedPosition(r_TicFracF); + pos.Z += thing->GetBobOffset(r_TicFracF); + + bool flipTextureX = false; + FTexture *tex = GetSpriteTexture(thing, flipTextureX); + if (tex == nullptr || tex->UseType == FTexture::TEX_Null) + return; + + DVector2 spriteScale = thing->Scale; + double thingxscalemul = spriteScale.X / tex->Scale.X; + double thingyscalemul = spriteScale.Y / tex->Scale.Y; + + if (flipTextureX) + pos.X -= (tex->GetWidth() - tex->LeftOffset) * thingxscalemul; + else + pos.X -= tex->LeftOffset * thingxscalemul; + + //pos.Z -= tex->TopOffset * thingyscalemul; + pos.Z -= (tex->GetHeight() - tex->TopOffset) * thingyscalemul + thing->Floorclip; + + double spriteHalfWidth = thingxscalemul * tex->GetWidth() * 0.5; + double spriteHeight = thingyscalemul * tex->GetHeight(); + + pos.X += spriteHalfWidth; + + //double depth = 1.0; + //visstyle_t visstyle = GetSpriteVisStyle(thing, depth); + // Rumor has it that AlterWeaponSprite needs to be called with visstyle passed in somewhere around here.. + //R_SetColorMapLight(visstyle.BaseColormap, 0, visstyle.ColormapNum << FRACBITS); + + TriVertex *vertices = PolyVertexBuffer::GetVertices(4); + if (!vertices) + return; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + + std::pair offsets[4] = + { + { t1, 1.0f }, + { t2, 1.0f }, + { t2, 0.0f }, + { t1, 0.0f }, + }; + + DVector2 points[2] = + { + line[0] * (1.0 - t1) + line[1] * t1, + line[0] * (1.0 - t2) + line[1] * t2 + }; + + for (int i = 0; i < 4; i++) + { + auto &p = (i == 0 || i == 3) ? points[0] : points[1]; + + vertices[i].x = (float)p.X; + vertices[i].y = (float)p.Y; + vertices[i].z = (float)(pos.Z + spriteHeight * offsets[i].second); + vertices[i].w = 1.0f; + vertices[i].varying[0] = (float)(offsets[i].first * tex->Scale.X); + vertices[i].varying[1] = (float)((1.0f - offsets[i].second) * tex->Scale.Y); + if (flipTextureX) + vertices[i].varying[0] = 1.0f - vertices[i].varying[0]; + } + + bool fullbrightSprite = ((thing->renderflags & RF_FULLBRIGHT) || (thing->flags5 & MF5_BRIGHT)); + + PolyDrawArgs args; + args.uniforms.flags = 0; + if (fullbrightSprite || swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + { + args.uniforms.light = 256; + args.uniforms.flags |= TriUniforms::fixed_light; + } + else + { + args.uniforms.light = (uint32_t)((thing->Sector->lightlevel + actualextralight) / 255.0f * 256.0f); + } + args.uniforms.subsectorDepth = subsectorDepth; + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = 4; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue; + args.SetTexture(tex, thing->Translation); + args.SetColormap(sub->sector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + + TriBlendMode blendmode; + + if (thing->RenderStyle == LegacyRenderStyles[STYLE_Normal] || + (r_drawfuzz == 0 && thing->RenderStyle == LegacyRenderStyles[STYLE_OptFuzzy])) + { + args.uniforms.destalpha = 0; + args.uniforms.srcalpha = 256; + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Add] && fullbrightSprite && thing->Alpha == 1.0 && args.translation == nullptr) + { + args.uniforms.destalpha = 256; + args.uniforms.srcalpha = 256; + blendmode = TriBlendMode::AddSrcColorOneMinusSrcColor; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Add]) + { + args.uniforms.destalpha = (uint32_t)(1.0 * 256); + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Subtract]) + { + args.uniforms.destalpha = (uint32_t)(1.0 * 256); + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + blendmode = args.translation ? TriBlendMode::TranslateRevSub : TriBlendMode::RevSub; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_SoulTrans]) + { + args.uniforms.destalpha = (uint32_t)(256 - transsouls * 256); + args.uniforms.srcalpha = (uint32_t)(transsouls * 256); + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Fuzzy] || + (r_drawfuzz == 2 && thing->RenderStyle == LegacyRenderStyles[STYLE_OptFuzzy])) + { // NYI - Fuzzy - for now, just a copy of "Shadow" + args.uniforms.destalpha = 160; + args.uniforms.srcalpha = 0; + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Shadow] || + (r_drawfuzz == 1 && thing->RenderStyle == LegacyRenderStyles[STYLE_OptFuzzy])) + { + args.uniforms.destalpha = 160; + args.uniforms.srcalpha = 0; + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_TranslucentStencil]) + { + args.uniforms.destalpha = (uint32_t)(256 - thing->Alpha * 256); + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + args.uniforms.color = 0xff000000 | thing->fillcolor; + blendmode = TriBlendMode::Stencil; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_AddStencil]) + { + args.uniforms.destalpha = 256; + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + args.uniforms.color = 0xff000000 | thing->fillcolor; + blendmode = TriBlendMode::Stencil; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_Shaded]) + { + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + args.uniforms.destalpha = 256 - args.uniforms.srcalpha; + args.uniforms.color = 0; + blendmode = TriBlendMode::Shaded; + } + else if (thing->RenderStyle == LegacyRenderStyles[STYLE_AddShaded]) + { + args.uniforms.destalpha = 256; + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + args.uniforms.color = 0; + blendmode = TriBlendMode::Shaded; + } + else + { + args.uniforms.destalpha = (uint32_t)(256 - thing->Alpha * 256); + args.uniforms.srcalpha = (uint32_t)(thing->Alpha * 256); + blendmode = args.translation ? TriBlendMode::TranslateAdd : TriBlendMode::Add; + } + + if (blendmode == TriBlendMode::Shaded) + { + args.SetTexture(tex, thing->Translation, true); + } + + if (!swrenderer::r_swtruecolor) + { + uint32_t r = (args.uniforms.color >> 16) & 0xff; + uint32_t g = (args.uniforms.color >> 8) & 0xff; + uint32_t b = args.uniforms.color & 0xff; + args.uniforms.color = RGB32k.RGB[r >> 3][g >> 3][b >> 3]; + + if (blendmode == TriBlendMode::Sub) // Sub crashes in pal mode for some weird reason. + blendmode = TriBlendMode::Add; + } + + args.subsectorTest = true; + args.writeSubsector = false; + args.writeStencil = false; + args.blendmode = blendmode; + PolyTriangleDrawer::draw(args); +} + +bool RenderPolySprite::IsThingCulled(AActor *thing) +{ + FIntCVar *cvar = thing->GetClass()->distancecheck; + if (cvar != nullptr && *cvar >= 0) + { + double dist = (thing->Pos() - ViewPos).LengthSquared(); + double check = (double)**cvar; + if (dist >= check * check) + return true; + } + + // Don't waste time projecting sprites that are definitely not visible. + if (thing == nullptr || + (thing->renderflags & RF_INVISIBLE) || + !thing->RenderStyle.IsVisible(thing->Alpha) || + !thing->IsVisibleToPlayer()) + { + return true; + } + + return false; +} + +visstyle_t RenderPolySprite::GetSpriteVisStyle(AActor *thing, double z) +{ + visstyle_t visstyle; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + int spriteshade = LIGHT2SHADE(thing->Sector->lightlevel + actualextralight); + + visstyle.RenderStyle = thing->RenderStyle; + visstyle.Alpha = float(thing->Alpha); + visstyle.ColormapNum = 0; + + // The software renderer cannot invert the source without inverting the overlay + // too. That means if the source is inverted, we need to do the reverse of what + // the invert overlay flag says to do. + bool invertcolormap = (visstyle.RenderStyle.Flags & STYLEF_InvertOverlay) != 0; + + if (visstyle.RenderStyle.Flags & STYLEF_InvertSource) + { + invertcolormap = !invertcolormap; + } + + FDynamicColormap *mybasecolormap = thing->Sector->ColorMap; + + // Sprites that are added to the scene must fade to black. + if (visstyle.RenderStyle == LegacyRenderStyles[STYLE_Add] && mybasecolormap->Fade != 0) + { + mybasecolormap = GetSpecialLights(mybasecolormap->Color, 0, mybasecolormap->Desaturate); + } + + if (visstyle.RenderStyle.Flags & STYLEF_FadeToBlack) + { + if (invertcolormap) + { // Fade to white + mybasecolormap = GetSpecialLights(mybasecolormap->Color, MAKERGB(255, 255, 255), mybasecolormap->Desaturate); + invertcolormap = false; + } + else + { // Fade to black + mybasecolormap = GetSpecialLights(mybasecolormap->Color, MAKERGB(0, 0, 0), mybasecolormap->Desaturate); + } + } + + // get light level + if (swrenderer::fixedcolormap != nullptr) + { // fixed map + visstyle.BaseColormap = swrenderer::fixedcolormap; + visstyle.ColormapNum = 0; + } + else + { + if (invertcolormap) + { + mybasecolormap = GetSpecialLights(mybasecolormap->Color, mybasecolormap->Fade.InverseColor(), mybasecolormap->Desaturate); + } + if (swrenderer::fixedlightlev >= 0) + { + visstyle.BaseColormap = mybasecolormap; + visstyle.ColormapNum = swrenderer::fixedlightlev >> COLORMAPSHIFT; + } + else if (!foggy && ((thing->renderflags & RF_FULLBRIGHT) || (thing->flags5 & MF5_BRIGHT))) + { // full bright + visstyle.BaseColormap = mybasecolormap; + visstyle.ColormapNum = 0; + } + else + { // diminished light + double minz = double((2048 * 4) / double(1 << 20)); + visstyle.ColormapNum = GETPALOOKUP(swrenderer::r_SpriteVisibility / MAX(z, minz), spriteshade); + visstyle.BaseColormap = mybasecolormap; + } + } + + return visstyle; +} + +FTexture *RenderPolySprite::GetSpriteTexture(AActor *thing, /*out*/ bool &flipX) +{ + flipX = false; + if (thing->picnum.isValid()) + { + FTexture *tex = TexMan(thing->picnum); + if (tex->UseType == FTexture::TEX_Null) + { + return nullptr; + } + + if (tex->Rotations != 0xFFFF) + { + // choose a different rotation based on player view + spriteframe_t *sprframe = &SpriteFrames[tex->Rotations]; + DVector3 pos = thing->InterpolatedPosition(r_TicFracF); + pos.Z += thing->GetBobOffset(r_TicFracF); + DAngle ang = (pos - ViewPos).Angle(); + angle_t rot; + if (sprframe->Texture[0] == sprframe->Texture[1]) + { + rot = (ang - thing->Angles.Yaw + 45.0 / 2 * 9).BAMs() >> 28; + } + else + { + rot = (ang - thing->Angles.Yaw + (45.0 / 2 * 9 - 180.0 / 16)).BAMs() >> 28; + } + flipX = (sprframe->Flip & (1 << rot)) != 0; + tex = TexMan[sprframe->Texture[rot]]; // Do not animate the rotation + } + return tex; + } + else + { + // decide which texture to use for the sprite + int spritenum = thing->sprite; + if (spritenum >= (signed)sprites.Size() || spritenum < 0) + return nullptr; + + spritedef_t *sprdef = &sprites[spritenum]; + if (thing->frame >= sprdef->numframes) + { + // If there are no frames at all for this sprite, don't draw it. + return nullptr; + } + else + { + //picnum = SpriteFrames[sprdef->spriteframes + thing->frame].Texture[0]; + // choose a different rotation based on player view + spriteframe_t *sprframe = &SpriteFrames[sprdef->spriteframes + thing->frame]; + DVector3 pos = thing->InterpolatedPosition(r_TicFracF); + pos.Z += thing->GetBobOffset(r_TicFracF); + DAngle ang = (pos - ViewPos).Angle(); + angle_t rot; + if (sprframe->Texture[0] == sprframe->Texture[1]) + { + rot = (ang - thing->Angles.Yaw + 45.0 / 2 * 9).BAMs() >> 28; + } + else + { + rot = (ang - thing->Angles.Yaw + (45.0 / 2 * 9 - 180.0 / 16)).BAMs() >> 28; + } + flipX = (sprframe->Flip & (1 << rot)) != 0; + return TexMan[sprframe->Texture[rot]]; // Do not animate the rotation + } + } +} diff --git a/src/r_poly_sprite.h b/src/r_poly_sprite.h new file mode 100644 index 000000000..085845e50 --- /dev/null +++ b/src/r_poly_sprite.h @@ -0,0 +1,40 @@ +/* +** Handling drawing a sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class Vec4f; + +class RenderPolySprite +{ +public: + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, AActor *thing, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue, float t1, float t2); + + static bool GetLine(AActor *thing, DVector2 &left, DVector2 &right); + static bool IsThingCulled(AActor *thing); + static FTexture *GetSpriteTexture(AActor *thing, /*out*/ bool &flipX); + +private: + visstyle_t GetSpriteVisStyle(AActor *thing, double z); +}; diff --git a/src/r_poly_triangle.cpp b/src/r_poly_triangle.cpp new file mode 100644 index 000000000..5da23297b --- /dev/null +++ b/src/r_poly_triangle.cpp @@ -0,0 +1,1516 @@ +/* +** Triangle drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "i_system.h" +#include "w_wad.h" +#include "r_local.h" +#include "v_video.h" +#include "doomstat.h" +#include "st_stuff.h" +#include "g_game.h" +#include "g_level.h" +#include "r_data/r_translate.h" +#include "v_palette.h" +#include "r_data/colormaps.h" +#include "r_poly_triangle.h" +#include "r_draw_rgba.h" + +CVAR(Bool, r_debug_trisetup, false, 0); + +int PolyTriangleDrawer::viewport_x; +int PolyTriangleDrawer::viewport_y; +int PolyTriangleDrawer::viewport_width; +int PolyTriangleDrawer::viewport_height; +int PolyTriangleDrawer::dest_pitch; +int PolyTriangleDrawer::dest_width; +int PolyTriangleDrawer::dest_height; +uint8_t *PolyTriangleDrawer::dest; +bool PolyTriangleDrawer::dest_bgra; +bool PolyTriangleDrawer::mirror; + +void PolyTriangleDrawer::set_viewport(int x, int y, int width, int height, DCanvas *canvas) +{ + dest = (uint8_t*)canvas->GetBuffer(); + dest_width = canvas->GetWidth(); + dest_height = canvas->GetHeight(); + dest_pitch = canvas->GetPitch(); + dest_bgra = canvas->IsBgra(); + + int offsetx = clamp(x, 0, dest_width); + int offsety = clamp(y, 0, dest_height); + int pixelsize = dest_bgra ? 4 : 1; + + viewport_x = x - offsetx; + viewport_y = y - offsety; + viewport_width = width; + viewport_height = height; + + dest += (offsetx + offsety * dest_pitch) * pixelsize; + dest_width = clamp(viewport_x + viewport_width, 0, dest_width - offsetx); + dest_height = clamp(viewport_y + viewport_height, 0, dest_height - offsety); + + mirror = false; +} + +void PolyTriangleDrawer::toggle_mirror() +{ + mirror = !mirror; +} + +void PolyTriangleDrawer::draw(const PolyDrawArgs &args) +{ + DrawerCommandQueue::QueueCommand(args, mirror); +} + +void PolyTriangleDrawer::draw_arrays(const PolyDrawArgs &drawargs, WorkerThreadData *thread) +{ + if (drawargs.vcount < 3) + return; + + auto llvm = Drawers::Instance(); + + PolyDrawFuncPtr drawfuncs[4]; + int num_drawfuncs = 0; + + drawfuncs[num_drawfuncs++] = drawargs.subsectorTest ? &ScreenTriangle::SetupSubsector : &ScreenTriangle::SetupNormal; + + if (!r_debug_trisetup) // For profiling how much time is spent in setup vs drawal + { + int bmode = (int)drawargs.blendmode; + if (drawargs.writeColor && drawargs.texturePixels) + drawfuncs[num_drawfuncs++] = dest_bgra ? llvm->TriDraw32[bmode] : llvm->TriDraw8[bmode]; + else if (drawargs.writeColor) + drawfuncs[num_drawfuncs++] = dest_bgra ? llvm->TriFill32[bmode] : llvm->TriFill8[bmode]; + } + + if (drawargs.writeStencil) + drawfuncs[num_drawfuncs++] = &ScreenTriangle::StencilWrite; + + if (drawargs.writeSubsector) + drawfuncs[num_drawfuncs++] = &ScreenTriangle::SubsectorWrite; + + TriDrawTriangleArgs args; + args.dest = dest; + args.pitch = dest_pitch; + args.clipleft = 0; + args.clipright = dest_width; + args.cliptop = 0; + args.clipbottom = dest_height; + args.texturePixels = drawargs.texturePixels; + args.textureWidth = drawargs.textureWidth; + args.textureHeight = drawargs.textureHeight; + args.translation = drawargs.translation; + args.uniforms = &drawargs.uniforms; + args.stencilTestValue = drawargs.stenciltestvalue; + args.stencilWriteValue = drawargs.stencilwritevalue; + args.stencilPitch = PolyStencilBuffer::Instance()->BlockWidth(); + args.stencilValues = PolyStencilBuffer::Instance()->Values(); + args.stencilMasks = PolyStencilBuffer::Instance()->Masks(); + args.subsectorGBuffer = PolySubsectorGBuffer::Instance()->Values(); + args.colormaps = drawargs.colormaps; + args.RGB256k = RGB256k.All; + args.BaseColors = (const uint8_t *)GPalette.BaseColors; + + bool ccw = drawargs.ccw; + const TriVertex *vinput = drawargs.vinput; + int vcount = drawargs.vcount; + + ShadedTriVertex vert[3]; + if (drawargs.mode == TriangleDrawMode::Normal) + { + for (int i = 0; i < vcount / 3; i++) + { + for (int j = 0; j < 3; j++) + vert[j] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + draw_shaded_triangle(vert, ccw, &args, thread, drawfuncs, num_drawfuncs); + } + } + else if (drawargs.mode == TriangleDrawMode::Fan) + { + vert[0] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + vert[1] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + for (int i = 2; i < vcount; i++) + { + vert[2] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + draw_shaded_triangle(vert, ccw, &args, thread, drawfuncs, num_drawfuncs); + vert[1] = vert[2]; + } + } + else // TriangleDrawMode::Strip + { + vert[0] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + vert[1] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + for (int i = 2; i < vcount; i++) + { + vert[2] = shade_vertex(*drawargs.objectToClip, drawargs.clipPlane, *(vinput++)); + draw_shaded_triangle(vert, ccw, &args, thread, drawfuncs, num_drawfuncs); + vert[0] = vert[1]; + vert[1] = vert[2]; + ccw = !ccw; + } + } +} + +ShadedTriVertex PolyTriangleDrawer::shade_vertex(const TriMatrix &objectToClip, const float *clipPlane, const TriVertex &v) +{ + // Apply transform to get clip coordinates: + ShadedTriVertex sv = objectToClip * v; + + // Calculate gl_ClipDistance[0] + sv.clipDistance0 = v.x * clipPlane[0] + v.y * clipPlane[1] + v.z * clipPlane[2] + v.w * clipPlane[3]; + + return sv; +} + +void PolyTriangleDrawer::draw_shaded_triangle(const ShadedTriVertex *vert, bool ccw, TriDrawTriangleArgs *args, WorkerThreadData *thread, PolyDrawFuncPtr *drawfuncs, int num_drawfuncs) +{ + // Cull, clip and generate additional vertices as needed + TriVertex clippedvert[max_additional_vertices]; + int numclipvert; + clipedge(vert, clippedvert, numclipvert); + + // Map to 2D viewport: + for (int j = 0; j < numclipvert; j++) + { + auto &v = clippedvert[j]; + + // Calculate normalized device coordinates: + v.w = 1.0f / v.w; + v.x *= v.w; + v.y *= v.w; + v.z *= v.w; + + // Apply viewport scale to get screen coordinates: + v.x = viewport_x + viewport_width * (1.0f + v.x) * 0.5f; + v.y = viewport_y + viewport_height * (1.0f - v.y) * 0.5f; + } + + // Keep varyings in -128 to 128 range if possible + if (numclipvert > 0) + { + for (int j = 0; j < TriVertex::NumVarying; j++) + { + float newOrigin = floorf(clippedvert[0].varying[j] * 0.1f) * 10.0f; + for (int i = 0; i < numclipvert; i++) + { + clippedvert[i].varying[j] -= newOrigin; + } + } + } + + // Draw screen triangles + if (ccw) + { + for (int i = numclipvert; i > 1; i--) + { + args->v1 = &clippedvert[numclipvert - 1]; + args->v2 = &clippedvert[i - 1]; + args->v3 = &clippedvert[i - 2]; + + for (int j = 0; j < num_drawfuncs; j++) + drawfuncs[j](args, thread); + } + } + else + { + for (int i = 2; i < numclipvert; i++) + { + args->v1 = &clippedvert[0]; + args->v2 = &clippedvert[i - 1]; + args->v3 = &clippedvert[i]; + + for (int j = 0; j < num_drawfuncs; j++) + drawfuncs[j](args, thread); + } + } +} + +bool PolyTriangleDrawer::cullhalfspace(float clipdistance1, float clipdistance2, float &t1, float &t2) +{ + if (clipdistance1 < 0.0f && clipdistance2 < 0.0f) + return true; + + if (clipdistance1 < 0.0f) + t1 = MAX(-clipdistance1 / (clipdistance2 - clipdistance1), 0.0f); + else + t1 = 0.0f; + + if (clipdistance2 < 0.0f) + t2 = MIN(1.0f + clipdistance2 / (clipdistance1 - clipdistance2), 1.0f); + else + t2 = 1.0f; + + return false; +} + +void PolyTriangleDrawer::clipedge(const ShadedTriVertex *verts, TriVertex *clippedvert, int &numclipvert) +{ + // Clip and cull so that the following is true for all vertices: + // -v.w <= v.x <= v.w + // -v.w <= v.y <= v.w + // -v.w <= v.z <= v.w + + // use barycentric weights while clipping vertices + float weights[max_additional_vertices * 3 * 2]; + for (int i = 0; i < 3; i++) + { + weights[i * 3 + 0] = 0.0f; + weights[i * 3 + 1] = 0.0f; + weights[i * 3 + 2] = 0.0f; + weights[i * 3 + i] = 1.0f; + } + + // halfspace clip distances + static const int numclipdistances = 7; + float clipdistance[numclipdistances * 3]; + for (int i = 0; i < 3; i++) + { + const auto &v = verts[i]; + clipdistance[i * numclipdistances + 0] = v.x + v.w; + clipdistance[i * numclipdistances + 1] = v.w - v.x; + clipdistance[i * numclipdistances + 2] = v.y + v.w; + clipdistance[i * numclipdistances + 3] = v.w - v.y; + clipdistance[i * numclipdistances + 4] = v.z + v.w; + clipdistance[i * numclipdistances + 5] = v.w - v.z; + clipdistance[i * numclipdistances + 6] = v.clipDistance0; + } + + // Clip against each halfspace + float *input = weights; + float *output = weights + max_additional_vertices * 3; + int inputverts = 3; + int outputverts = 0; + for (int p = 0; p < numclipdistances; p++) + { + // Clip each edge + outputverts = 0; + for (int i = 0; i < inputverts; i++) + { + int j = (i + 1) % inputverts; + float clipdistance1 = + clipdistance[0 * numclipdistances + p] * input[i * 3 + 0] + + clipdistance[1 * numclipdistances + p] * input[i * 3 + 1] + + clipdistance[2 * numclipdistances + p] * input[i * 3 + 2]; + + float clipdistance2 = + clipdistance[0 * numclipdistances + p] * input[j * 3 + 0] + + clipdistance[1 * numclipdistances + p] * input[j * 3 + 1] + + clipdistance[2 * numclipdistances + p] * input[j * 3 + 2]; + + float t1, t2; + if (!cullhalfspace(clipdistance1, clipdistance2, t1, t2) && outputverts + 1 < max_additional_vertices) + { + // add t1 vertex + for (int k = 0; k < 3; k++) + output[outputverts * 3 + k] = input[i * 3 + k] * (1.0f - t1) + input[j * 3 + k] * t1; + outputverts++; + + if (t2 != 1.0f && t2 > t1) + { + // add t2 vertex + for (int k = 0; k < 3; k++) + output[outputverts * 3 + k] = input[i * 3 + k] * (1.0f - t2) + input[j * 3 + k] * t2; + outputverts++; + } + } + } + std::swap(input, output); + std::swap(inputverts, outputverts); + if (inputverts == 0) + break; + } + + // Convert barycentric weights to actual vertices + numclipvert = inputverts; + for (int i = 0; i < numclipvert; i++) + { + auto &v = clippedvert[i]; + memset(&v, 0, sizeof(TriVertex)); + for (int w = 0; w < 3; w++) + { + float weight = input[i * 3 + w]; + v.x += verts[w].x * weight; + v.y += verts[w].y * weight; + v.z += verts[w].z * weight; + v.w += verts[w].w * weight; + for (int iv = 0; iv < TriVertex::NumVarying; iv++) + v.varying[iv] += verts[w].varying[iv] * weight; + } + } +} + +///////////////////////////////////////////////////////////////////////////// + +DrawPolyTrianglesCommand::DrawPolyTrianglesCommand(const PolyDrawArgs &args, bool mirror) + : args(args) +{ + if (mirror) + this->args.ccw = !this->args.ccw; +} + +void DrawPolyTrianglesCommand::Execute(DrawerThread *thread) +{ + WorkerThreadData thread_data; + thread_data.core = thread->core; + thread_data.num_cores = thread->num_cores; + thread_data.pass_start_y = thread->pass_start_y; + thread_data.pass_end_y = thread->pass_end_y; + thread_data.FullSpans = thread->FullSpansBuffer.data(); + thread_data.PartialBlocks = thread->PartialBlocksBuffer.data(); + + PolyTriangleDrawer::draw_arrays(args, &thread_data); +} + +FString DrawPolyTrianglesCommand::DebugInfo() +{ + FString blendmodestr; + switch (args.blendmode) + { + default: blendmodestr = "Unknown"; break; + case TriBlendMode::Copy: blendmodestr = "Copy"; break; + case TriBlendMode::AlphaBlend: blendmodestr = "AlphaBlend"; break; + case TriBlendMode::AddSolid: blendmodestr = "AddSolid"; break; + case TriBlendMode::Add: blendmodestr = "Add"; break; + case TriBlendMode::Sub: blendmodestr = "Sub"; break; + case TriBlendMode::RevSub: blendmodestr = "RevSub"; break; + case TriBlendMode::Stencil: blendmodestr = "Stencil"; break; + case TriBlendMode::Shaded: blendmodestr = "Shaded"; break; + case TriBlendMode::TranslateCopy: blendmodestr = "TranslateCopy"; break; + case TriBlendMode::TranslateAlphaBlend: blendmodestr = "TranslateAlphaBlend"; break; + case TriBlendMode::TranslateAdd: blendmodestr = "TranslateAdd"; break; + case TriBlendMode::TranslateSub: blendmodestr = "TranslateSub"; break; + case TriBlendMode::TranslateRevSub: blendmodestr = "TranslateRevSub"; break; + case TriBlendMode::AddSrcColorOneMinusSrcColor: blendmodestr = "AddSrcColorOneMinusSrcColor"; break; + } + + FString info; + info.Format("DrawPolyTriangles: blend mode = %s, color = %d, light = %d, textureWidth = %d, textureHeight = %d, texture = %s, translation = %s, colormaps = %s", + blendmodestr.GetChars(), args.uniforms.color, args.uniforms.light, args.textureWidth, args.textureHeight, + args.texturePixels ? "ptr" : "null", args.translation ? "ptr" : "null", args.colormaps ? "ptr" : "null"); + return info; +} + +///////////////////////////////////////////////////////////////////////////// + +TriMatrix TriMatrix::null() +{ + TriMatrix m; + memset(m.matrix, 0, sizeof(m.matrix)); + return m; +} + +TriMatrix TriMatrix::identity() +{ + TriMatrix m = null(); + m.matrix[0] = 1.0f; + m.matrix[5] = 1.0f; + m.matrix[10] = 1.0f; + m.matrix[15] = 1.0f; + return m; +} + +TriMatrix TriMatrix::translate(float x, float y, float z) +{ + TriMatrix m = identity(); + m.matrix[0 + 3 * 4] = x; + m.matrix[1 + 3 * 4] = y; + m.matrix[2 + 3 * 4] = z; + return m; +} + +TriMatrix TriMatrix::scale(float x, float y, float z) +{ + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = x; + m.matrix[1 + 1 * 4] = y; + m.matrix[2 + 2 * 4] = z; + m.matrix[3 + 3 * 4] = 1; + return m; +} + +TriMatrix TriMatrix::rotate(float angle, float x, float y, float z) +{ + float c = cosf(angle); + float s = sinf(angle); + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = (x*x*(1.0f - c) + c); + m.matrix[0 + 1 * 4] = (x*y*(1.0f - c) - z*s); + m.matrix[0 + 2 * 4] = (x*z*(1.0f - c) + y*s); + m.matrix[1 + 0 * 4] = (y*x*(1.0f - c) + z*s); + m.matrix[1 + 1 * 4] = (y*y*(1.0f - c) + c); + m.matrix[1 + 2 * 4] = (y*z*(1.0f - c) - x*s); + m.matrix[2 + 0 * 4] = (x*z*(1.0f - c) - y*s); + m.matrix[2 + 1 * 4] = (y*z*(1.0f - c) + x*s); + m.matrix[2 + 2 * 4] = (z*z*(1.0f - c) + c); + m.matrix[3 + 3 * 4] = 1.0f; + return m; +} + +TriMatrix TriMatrix::swapYZ() +{ + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = 1.0f; + m.matrix[1 + 2 * 4] = 1.0f; + m.matrix[2 + 1 * 4] = -1.0f; + m.matrix[3 + 3 * 4] = 1.0f; + return m; +} + +TriMatrix TriMatrix::perspective(float fovy, float aspect, float z_near, float z_far) +{ + float f = (float)(1.0 / tan(fovy * M_PI / 360.0)); + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = f / aspect; + m.matrix[1 + 1 * 4] = f; + m.matrix[2 + 2 * 4] = (z_far + z_near) / (z_near - z_far); + m.matrix[2 + 3 * 4] = (2.0f * z_far * z_near) / (z_near - z_far); + m.matrix[3 + 2 * 4] = -1.0f; + return m; +} + +TriMatrix TriMatrix::frustum(float left, float right, float bottom, float top, float near, float far) +{ + float a = (right + left) / (right - left); + float b = (top + bottom) / (top - bottom); + float c = -(far + near) / (far - near); + float d = -(2.0f * far) / (far - near); + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = 2.0f * near / (right - left); + m.matrix[1 + 1 * 4] = 2.0f * near / (top - bottom); + m.matrix[0 + 2 * 4] = a; + m.matrix[1 + 2 * 4] = b; + m.matrix[2 + 2 * 4] = c; + m.matrix[2 + 3 * 4] = d; + m.matrix[3 + 2 * 4] = -1; + return m; +} + +TriMatrix TriMatrix::worldToView() +{ + TriMatrix m = null(); + m.matrix[0 + 0 * 4] = (float)ViewSin; + m.matrix[0 + 1 * 4] = (float)-ViewCos; + m.matrix[1 + 2 * 4] = 1.0f; + m.matrix[2 + 0 * 4] = (float)-ViewCos; + m.matrix[2 + 1 * 4] = (float)-ViewSin; + m.matrix[3 + 3 * 4] = 1.0f; + return m * translate((float)-ViewPos.X, (float)-ViewPos.Y, (float)-ViewPos.Z); +} + +TriMatrix TriMatrix::viewToClip() +{ + float near = 5.0f; + float far = 65536.0f; + float width = (float)(FocalTangent * near); + float top = (float)(swrenderer::CenterY / swrenderer::InvZtoScale * near); + float bottom = (float)(top - viewheight / swrenderer::InvZtoScale * near); + return frustum(-width, width, bottom, top, near, far); +} + +TriMatrix TriMatrix::operator*(const TriMatrix &mult) const +{ + TriMatrix result; + for (int x = 0; x < 4; x++) + { + for (int y = 0; y < 4; y++) + { + result.matrix[x + y * 4] = + matrix[0 * 4 + x] * mult.matrix[y * 4 + 0] + + matrix[1 * 4 + x] * mult.matrix[y * 4 + 1] + + matrix[2 * 4 + x] * mult.matrix[y * 4 + 2] + + matrix[3 * 4 + x] * mult.matrix[y * 4 + 3]; + } + } + return result; +} + +ShadedTriVertex TriMatrix::operator*(TriVertex v) const +{ + float vx = matrix[0 * 4 + 0] * v.x + matrix[1 * 4 + 0] * v.y + matrix[2 * 4 + 0] * v.z + matrix[3 * 4 + 0] * v.w; + float vy = matrix[0 * 4 + 1] * v.x + matrix[1 * 4 + 1] * v.y + matrix[2 * 4 + 1] * v.z + matrix[3 * 4 + 1] * v.w; + float vz = matrix[0 * 4 + 2] * v.x + matrix[1 * 4 + 2] * v.y + matrix[2 * 4 + 2] * v.z + matrix[3 * 4 + 2] * v.w; + float vw = matrix[0 * 4 + 3] * v.x + matrix[1 * 4 + 3] * v.y + matrix[2 * 4 + 3] * v.z + matrix[3 * 4 + 3] * v.w; + ShadedTriVertex sv; + sv.x = vx; + sv.y = vy; + sv.z = vz; + sv.w = vw; + for (int i = 0; i < TriVertex::NumVarying; i++) + sv.varying[i] = v.varying[i]; + return sv; +} + +///////////////////////////////////////////////////////////////////////////// + +namespace +{ + int NextBufferVertex = 0; +} + +TriVertex *PolyVertexBuffer::GetVertices(int count) +{ + enum { VertexBufferSize = 256 * 1024 }; + static TriVertex Vertex[VertexBufferSize]; + + if (NextBufferVertex + count > VertexBufferSize) + return nullptr; + TriVertex *v = Vertex + NextBufferVertex; + NextBufferVertex += count; + return v; +} + +void PolyVertexBuffer::Clear() +{ + NextBufferVertex = 0; +} + +///////////////////////////////////////////////////////////////////////////// + +void ScreenTriangle::SetupNormal(const TriDrawTriangleArgs *args, WorkerThreadData *thread) +{ + const TriVertex &v1 = *args->v1; + const TriVertex &v2 = *args->v2; + const TriVertex &v3 = *args->v3; + int clipright = args->clipright; + int clipbottom = args->clipbottom; + + int stencilPitch = args->stencilPitch; + uint8_t * RESTRICT stencilValues = args->stencilValues; + uint32_t * RESTRICT stencilMasks = args->stencilMasks; + uint8_t stencilTestValue = args->stencilTestValue; + + TriFullSpan * RESTRICT span = thread->FullSpans; + TriPartialBlock * RESTRICT partial = thread->PartialBlocks; + + // 28.4 fixed-point coordinates + const int Y1 = (int)round(16.0f * v1.y); + const int Y2 = (int)round(16.0f * v2.y); + const int Y3 = (int)round(16.0f * v3.y); + + const int X1 = (int)round(16.0f * v1.x); + const int X2 = (int)round(16.0f * v2.x); + const int X3 = (int)round(16.0f * v3.x); + + // Deltas + const int DX12 = X1 - X2; + const int DX23 = X2 - X3; + const int DX31 = X3 - X1; + + const int DY12 = Y1 - Y2; + const int DY23 = Y2 - Y3; + const int DY31 = Y3 - Y1; + + // Fixed-point deltas + const int FDX12 = DX12 << 4; + const int FDX23 = DX23 << 4; + const int FDX31 = DX31 << 4; + + const int FDY12 = DY12 << 4; + const int FDY23 = DY23 << 4; + const int FDY31 = DY31 << 4; + + // Bounding rectangle + int minx = MAX((MIN(MIN(X1, X2), X3) + 0xF) >> 4, 0); + int maxx = MIN((MAX(MAX(X1, X2), X3) + 0xF) >> 4, clipright - 1); + int miny = MAX((MIN(MIN(Y1, Y2), Y3) + 0xF) >> 4, 0); + int maxy = MIN((MAX(MAX(Y1, Y2), Y3) + 0xF) >> 4, clipbottom - 1); + if (minx >= maxx || miny >= maxy) + { + thread->NumFullSpans = 0; + thread->NumPartialBlocks = 0; + return; + } + + // Block size, standard 8x8 (must be power of two) + const int q = 8; + + // Start in corner of 8x8 block + minx &= ~(q - 1); + miny &= ~(q - 1); + + // Half-edge constants + int C1 = DY12 * X1 - DX12 * Y1; + int C2 = DY23 * X2 - DX23 * Y2; + int C3 = DY31 * X3 - DX31 * Y3; + + // Correct for fill convention + if (DY12 < 0 || (DY12 == 0 && DX12 > 0)) C1++; + if (DY23 < 0 || (DY23 == 0 && DX23 > 0)) C2++; + if (DY31 < 0 || (DY31 == 0 && DX31 > 0)) C3++; + + // First block line for this thread + int core = thread->core; + int num_cores = thread->num_cores; + int core_skip = (num_cores - ((miny / q) - core) % num_cores) % num_cores; + miny += core_skip * q; + + thread->StartX = minx; + thread->StartY = miny; + span->Length = 0; + + // Loop through blocks + for (int y = miny; y < maxy; y += q * num_cores) + { + for (int x = minx; x < maxx; x += q) + { + // Corners of block + int x0 = x << 4; + int x1 = (x + q - 1) << 4; + int y0 = y << 4; + int y1 = (y + q - 1) << 4; + + // Evaluate half-space functions + bool a00 = C1 + DX12 * y0 - DY12 * x0 > 0; + bool a10 = C1 + DX12 * y0 - DY12 * x1 > 0; + bool a01 = C1 + DX12 * y1 - DY12 * x0 > 0; + bool a11 = C1 + DX12 * y1 - DY12 * x1 > 0; + int a = (a00 << 0) | (a10 << 1) | (a01 << 2) | (a11 << 3); + + bool b00 = C2 + DX23 * y0 - DY23 * x0 > 0; + bool b10 = C2 + DX23 * y0 - DY23 * x1 > 0; + bool b01 = C2 + DX23 * y1 - DY23 * x0 > 0; + bool b11 = C2 + DX23 * y1 - DY23 * x1 > 0; + int b = (b00 << 0) | (b10 << 1) | (b01 << 2) | (b11 << 3); + + bool c00 = C3 + DX31 * y0 - DY31 * x0 > 0; + bool c10 = C3 + DX31 * y0 - DY31 * x1 > 0; + bool c01 = C3 + DX31 * y1 - DY31 * x0 > 0; + bool c11 = C3 + DX31 * y1 - DY31 * x1 > 0; + int c = (c00 << 0) | (c10 << 1) | (c01 << 2) | (c11 << 3); + + // Stencil test the whole block, if possible + int block = x / 8 + y / 8 * stencilPitch; + uint8_t *stencilBlock = &stencilValues[block * 64]; + uint32_t *stencilBlockMask = &stencilMasks[block]; + bool blockIsSingleStencil = ((*stencilBlockMask) & 0xffffff00) == 0xffffff00; + bool skipBlock = blockIsSingleStencil && ((*stencilBlockMask) & 0xff) != stencilTestValue; + + // Skip block when outside an edge + if (a == 0 || b == 0 || c == 0 || skipBlock) + { + if (span->Length != 0) + { + span++; + span->Length = 0; + } + continue; + } + + // Accept whole block when totally covered + if (a == 0xf && b == 0xf && c == 0xf && x + q <= clipright && y + q <= clipbottom && blockIsSingleStencil) + { + if (span->Length != 0) + { + span->Length++; + } + else + { + span->X = x; + span->Y = y; + span->Length = 1; + } + } + else // Partially covered block + { + x0 = x << 4; + x1 = (x + q - 1) << 4; + int CY1 = C1 + DX12 * y0 - DY12 * x0; + int CY2 = C2 + DX23 * y0 - DY23 * x0; + int CY3 = C3 + DX31 * y0 - DY31 * x0; + + uint32_t mask0 = 0; + uint32_t mask1 = 0; + + for (int iy = 0; iy < 4; iy++) + { + int CX1 = CY1; + int CX2 = CY2; + int CX3 = CY3; + + for (int ix = 0; ix < q; ix++) + { + bool passStencilTest = blockIsSingleStencil || stencilBlock[ix + iy * q] == stencilTestValue; + bool covered = (CX1 > 0 && CX2 > 0 && CX3 > 0 && (x + ix) < clipright && (y + iy) < clipbottom && passStencilTest); + mask0 <<= 1; + mask0 |= (uint32_t)covered; + + CX1 -= FDY12; + CX2 -= FDY23; + CX3 -= FDY31; + } + + CY1 += FDX12; + CY2 += FDX23; + CY3 += FDX31; + } + + for (int iy = 4; iy < q; iy++) + { + int CX1 = CY1; + int CX2 = CY2; + int CX3 = CY3; + + for (int ix = 0; ix < q; ix++) + { + bool passStencilTest = blockIsSingleStencil || stencilBlock[ix + iy * q] == stencilTestValue; + bool covered = (CX1 > 0 && CX2 > 0 && CX3 > 0 && (x + ix) < clipright && (y + iy) < clipbottom && passStencilTest); + mask1 <<= 1; + mask1 |= (uint32_t)covered; + + CX1 -= FDY12; + CX2 -= FDY23; + CX3 -= FDY31; + } + + CY1 += FDX12; + CY2 += FDX23; + CY3 += FDX31; + } + + if (mask0 != 0xffffffff || mask1 != 0xffffffff) + { + if (span->Length > 0) + { + span++; + span->Length = 0; + } + + if (mask0 == 0 && mask1 == 0) + continue; + + partial->X = x; + partial->Y = y; + partial->Mask0 = mask0; + partial->Mask1 = mask1; + partial++; + } + else if (span->Length != 0) + { + span->Length++; + } + else + { + span->X = x; + span->Y = y; + span->Length = 1; + } + } + } + + if (span->Length != 0) + { + span++; + span->Length = 0; + } + } + + thread->NumFullSpans = (int)(span - thread->FullSpans); + thread->NumPartialBlocks = (int)(partial - thread->PartialBlocks); +} + +void ScreenTriangle::SetupSubsector(const TriDrawTriangleArgs *args, WorkerThreadData *thread) +{ + const TriVertex &v1 = *args->v1; + const TriVertex &v2 = *args->v2; + const TriVertex &v3 = *args->v3; + int clipright = args->clipright; + int clipbottom = args->clipbottom; + + int stencilPitch = args->stencilPitch; + uint8_t * RESTRICT stencilValues = args->stencilValues; + uint32_t * RESTRICT stencilMasks = args->stencilMasks; + uint8_t stencilTestValue = args->stencilTestValue; + + uint32_t * RESTRICT subsectorGBuffer = args->subsectorGBuffer; + uint32_t subsectorDepth = args->uniforms->subsectorDepth; + int32_t pitch = args->pitch; + + TriFullSpan * RESTRICT span = thread->FullSpans; + TriPartialBlock * RESTRICT partial = thread->PartialBlocks; + + // 28.4 fixed-point coordinates + const int Y1 = (int)round(16.0f * v1.y); + const int Y2 = (int)round(16.0f * v2.y); + const int Y3 = (int)round(16.0f * v3.y); + + const int X1 = (int)round(16.0f * v1.x); + const int X2 = (int)round(16.0f * v2.x); + const int X3 = (int)round(16.0f * v3.x); + + // Deltas + const int DX12 = X1 - X2; + const int DX23 = X2 - X3; + const int DX31 = X3 - X1; + + const int DY12 = Y1 - Y2; + const int DY23 = Y2 - Y3; + const int DY31 = Y3 - Y1; + + // Fixed-point deltas + const int FDX12 = DX12 << 4; + const int FDX23 = DX23 << 4; + const int FDX31 = DX31 << 4; + + const int FDY12 = DY12 << 4; + const int FDY23 = DY23 << 4; + const int FDY31 = DY31 << 4; + + // Bounding rectangle + int minx = MAX((MIN(MIN(X1, X2), X3) + 0xF) >> 4, 0); + int maxx = MIN((MAX(MAX(X1, X2), X3) + 0xF) >> 4, clipright - 1); + int miny = MAX((MIN(MIN(Y1, Y2), Y3) + 0xF) >> 4, 0); + int maxy = MIN((MAX(MAX(Y1, Y2), Y3) + 0xF) >> 4, clipbottom - 1); + if (minx >= maxx || miny >= maxy) + { + thread->NumFullSpans = 0; + thread->NumPartialBlocks = 0; + return; + } + + // Block size, standard 8x8 (must be power of two) + const int q = 8; + + // Start in corner of 8x8 block + minx &= ~(q - 1); + miny &= ~(q - 1); + + // Half-edge constants + int C1 = DY12 * X1 - DX12 * Y1; + int C2 = DY23 * X2 - DX23 * Y2; + int C3 = DY31 * X3 - DX31 * Y3; + + // Correct for fill convention + if (DY12 < 0 || (DY12 == 0 && DX12 > 0)) C1++; + if (DY23 < 0 || (DY23 == 0 && DX23 > 0)) C2++; + if (DY31 < 0 || (DY31 == 0 && DX31 > 0)) C3++; + + // First block line for this thread + int core = thread->core; + int num_cores = thread->num_cores; + int core_skip = (num_cores - ((miny / q) - core) % num_cores) % num_cores; + miny += core_skip * q; + + thread->StartX = minx; + thread->StartY = miny; + span->Length = 0; + + // Loop through blocks + for (int y = miny; y < maxy; y += q * num_cores) + { + for (int x = minx; x < maxx; x += q) + { + // Corners of block + int x0 = x << 4; + int x1 = (x + q - 1) << 4; + int y0 = y << 4; + int y1 = (y + q - 1) << 4; + + // Evaluate half-space functions + bool a00 = C1 + DX12 * y0 - DY12 * x0 > 0; + bool a10 = C1 + DX12 * y0 - DY12 * x1 > 0; + bool a01 = C1 + DX12 * y1 - DY12 * x0 > 0; + bool a11 = C1 + DX12 * y1 - DY12 * x1 > 0; + int a = (a00 << 0) | (a10 << 1) | (a01 << 2) | (a11 << 3); + + bool b00 = C2 + DX23 * y0 - DY23 * x0 > 0; + bool b10 = C2 + DX23 * y0 - DY23 * x1 > 0; + bool b01 = C2 + DX23 * y1 - DY23 * x0 > 0; + bool b11 = C2 + DX23 * y1 - DY23 * x1 > 0; + int b = (b00 << 0) | (b10 << 1) | (b01 << 2) | (b11 << 3); + + bool c00 = C3 + DX31 * y0 - DY31 * x0 > 0; + bool c10 = C3 + DX31 * y0 - DY31 * x1 > 0; + bool c01 = C3 + DX31 * y1 - DY31 * x0 > 0; + bool c11 = C3 + DX31 * y1 - DY31 * x1 > 0; + int c = (c00 << 0) | (c10 << 1) | (c01 << 2) | (c11 << 3); + + // Stencil test the whole block, if possible + int block = x / 8 + y / 8 * stencilPitch; + uint8_t *stencilBlock = &stencilValues[block * 64]; + uint32_t *stencilBlockMask = &stencilMasks[block]; + bool blockIsSingleStencil = ((*stencilBlockMask) & 0xffffff00) == 0xffffff00; + bool skipBlock = blockIsSingleStencil && ((*stencilBlockMask) & 0xff) < stencilTestValue; + + // Skip block when outside an edge + if (a == 0 || b == 0 || c == 0 || skipBlock) + { + if (span->Length != 0) + { + span++; + span->Length = 0; + } + continue; + } + + // Accept whole block when totally covered + if (a == 0xf && b == 0xf && c == 0xf && x + q <= clipright && y + q <= clipbottom && blockIsSingleStencil) + { + // Totally covered block still needs a subsector coverage test: + + uint32_t *subsector = subsectorGBuffer + x + y * pitch; + + uint32_t mask0 = 0; + uint32_t mask1 = 0; + + for (int iy = 0; iy < 4; iy++) + { + for (int ix = 0; ix < q; ix++) + { + bool covered = subsector[ix] >= subsectorDepth; + mask0 <<= 1; + mask0 |= (uint32_t)covered; + } + subsector += pitch; + } + + for (int iy = 4; iy < q; iy++) + { + for (int ix = 0; ix < q; ix++) + { + bool covered = subsector[ix] >= subsectorDepth; + mask1 <<= 1; + mask1 |= (uint32_t)covered; + } + subsector += pitch; + } + + if (mask0 != 0xffffffff || mask1 != 0xffffffff) + { + if (span->Length > 0) + { + span++; + span->Length = 0; + } + + if (mask0 == 0 && mask1 == 0) + continue; + + partial->X = x; + partial->Y = y; + partial->Mask0 = mask0; + partial->Mask1 = mask1; + partial++; + } + else if (span->Length != 0) + { + span->Length++; + } + else + { + span->X = x; + span->Y = y; + span->Length = 1; + } + } + else // Partially covered block + { + x0 = x << 4; + x1 = (x + q - 1) << 4; + int CY1 = C1 + DX12 * y0 - DY12 * x0; + int CY2 = C2 + DX23 * y0 - DY23 * x0; + int CY3 = C3 + DX31 * y0 - DY31 * x0; + + uint32_t *subsector = subsectorGBuffer + x + y * pitch; + + uint32_t mask0 = 0; + uint32_t mask1 = 0; + + for (int iy = 0; iy < 4; iy++) + { + int CX1 = CY1; + int CX2 = CY2; + int CX3 = CY3; + + for (int ix = 0; ix < q; ix++) + { + bool passStencilTest = blockIsSingleStencil || stencilBlock[ix + iy * q] >= stencilTestValue; + bool covered = (CX1 > 0 && CX2 > 0 && CX3 > 0 && (x + ix) < clipright && (y + iy) < clipbottom && passStencilTest && subsector[ix] >= subsectorDepth); + mask0 <<= 1; + mask0 |= (uint32_t)covered; + + CX1 -= FDY12; + CX2 -= FDY23; + CX3 -= FDY31; + } + + CY1 += FDX12; + CY2 += FDX23; + CY3 += FDX31; + subsector += pitch; + } + + for (int iy = 4; iy < q; iy++) + { + int CX1 = CY1; + int CX2 = CY2; + int CX3 = CY3; + + for (int ix = 0; ix < q; ix++) + { + bool passStencilTest = blockIsSingleStencil || stencilBlock[ix + iy * q] >= stencilTestValue; + bool covered = (CX1 > 0 && CX2 > 0 && CX3 > 0 && (x + ix) < clipright && (y + iy) < clipbottom && passStencilTest && subsector[ix] >= subsectorDepth); + mask1 <<= 1; + mask1 |= (uint32_t)covered; + + CX1 -= FDY12; + CX2 -= FDY23; + CX3 -= FDY31; + } + + CY1 += FDX12; + CY2 += FDX23; + CY3 += FDX31; + subsector += pitch; + } + + if (mask0 != 0xffffffff || mask1 != 0xffffffff) + { + if (span->Length > 0) + { + span++; + span->Length = 0; + } + + if (mask0 == 0 && mask1 == 0) + continue; + + partial->X = x; + partial->Y = y; + partial->Mask0 = mask0; + partial->Mask1 = mask1; + partial++; + } + else if (span->Length != 0) + { + span->Length++; + } + else + { + span->X = x; + span->Y = y; + span->Length = 1; + } + } + } + + if (span->Length != 0) + { + span++; + span->Length = 0; + } + } + + thread->NumFullSpans = (int)(span - thread->FullSpans); + thread->NumPartialBlocks = (int)(partial - thread->PartialBlocks); +} + +void ScreenTriangle::StencilWrite(const TriDrawTriangleArgs *args, WorkerThreadData *thread) +{ + uint8_t * RESTRICT stencilValues = args->stencilValues; + uint32_t * RESTRICT stencilMasks = args->stencilMasks; + uint32_t stencilWriteValue = args->stencilWriteValue; + uint32_t stencilPitch = args->stencilPitch; + + int numSpans = thread->NumFullSpans; + auto fullSpans = thread->FullSpans; + int numBlocks = thread->NumPartialBlocks; + auto partialBlocks = thread->PartialBlocks; + + for (int i = 0; i < numSpans; i++) + { + const auto &span = fullSpans[i]; + + int block = span.X / 8 + span.Y / 8 * stencilPitch; + uint8_t *stencilBlock = &stencilValues[block * 64]; + uint32_t *stencilBlockMask = &stencilMasks[block]; + + int width = span.Length; + for (int x = 0; x < width; x++) + stencilBlockMask[x] = 0xffffff00 | stencilWriteValue; + } + + for (int i = 0; i < numBlocks; i++) + { + const auto &block = partialBlocks[i]; + + uint32_t mask0 = block.Mask0; + uint32_t mask1 = block.Mask1; + + int sblock = block.X / 8 + block.Y / 8 * stencilPitch; + uint8_t *stencilBlock = &stencilValues[sblock * 64]; + uint32_t *stencilBlockMask = &stencilMasks[sblock]; + + bool isSingleValue = ((*stencilBlockMask) & 0xffffff00) == 0xffffff00; + if (isSingleValue) + { + uint8_t value = (*stencilBlockMask) & 0xff; + for (int v = 0; v < 64; v++) + stencilBlock[v] = value; + *stencilBlockMask = 0; + } + + int count = 0; + for (int v = 0; v < 32; v++) + { + if ((mask0 & (1 << 31)) || stencilBlock[v] == stencilWriteValue) + { + stencilBlock[v] = stencilWriteValue; + count++; + } + mask0 <<= 1; + } + for (int v = 32; v < 64; v++) + { + if ((mask1 & (1 << 31)) || stencilBlock[v] == stencilWriteValue) + { + stencilBlock[v] = stencilWriteValue; + count++; + } + mask1 <<= 1; + } + + if (count == 64) + *stencilBlockMask = 0xffffff00 | stencilWriteValue; + } +} + +void ScreenTriangle::SubsectorWrite(const TriDrawTriangleArgs *args, WorkerThreadData *thread) +{ + uint32_t * RESTRICT subsectorGBuffer = args->subsectorGBuffer; + uint32_t subsectorDepth = args->uniforms->subsectorDepth; + int pitch = args->pitch; + + int numSpans = thread->NumFullSpans; + auto fullSpans = thread->FullSpans; + int numBlocks = thread->NumPartialBlocks; + auto partialBlocks = thread->PartialBlocks; + + for (int i = 0; i < numSpans; i++) + { + const auto &span = fullSpans[i]; + + uint32_t *subsector = subsectorGBuffer + span.X + span.Y * pitch; + int width = span.Length * 8; + int height = 8; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + subsector[x] = subsectorDepth; + subsector += pitch; + } + } + + for (int i = 0; i < numBlocks; i++) + { + const auto &block = partialBlocks[i]; + + uint32_t *subsector = subsectorGBuffer + block.X + block.Y * pitch; + uint32_t mask0 = block.Mask0; + uint32_t mask1 = block.Mask1; + for (int y = 0; y < 4; y++) + { + for (int x = 0; x < 8; x++) + { + if (mask0 & (1 << 31)) + subsector[x] = subsectorDepth; + mask0 <<= 1; + } + subsector += pitch; + } + for (int y = 4; y < 8; y++) + { + for (int x = 0; x < 8; x++) + { + if (mask1 & (1 << 31)) + subsector[x] = subsectorDepth; + mask1 <<= 1; + } + subsector += pitch; + } + } +} + +#if 0 +float ScreenTriangle::FindGradientX(float x0, float y0, float x1, float y1, float x2, float y2, float c0, float c1, float c2) +{ + float top = (c1 - c2) * (y0 - y2) - (c0 - c2) * (y1 - y2); + float bottom = (x1 - x2) * (y0 - y2) - (x0 - x2) * (y1 - y2); + return top / bottom; +} + +float ScreenTriangle::FindGradientY(float x0, float y0, float x1, float y1, float x2, float y2, float c0, float c1, float c2) +{ + float top = (c1 - c2) * (x0 - x2) - (c0 - c2) * (x1 - x2); + float bottom = (x0 - x2) * (y1 - y2) - (x1 - x2) * (y0 - y2); + return top / bottom; +} + +void ScreenTriangle::Draw(const TriDrawTriangleArgs *args, WorkerThreadData *thread) +{ + int numSpans = thread->NumFullSpans; + auto fullSpans = thread->FullSpans; + int numBlocks = thread->NumPartialBlocks; + auto partialBlocks = thread->PartialBlocks; + int startX = thread->StartX; + int startY = thread->StartY; + + // Calculate gradients + const TriVertex &v1 = *args->v1; + const TriVertex &v2 = *args->v2; + const TriVertex &v3 = *args->v3; + ScreenTriangleStepVariables gradientX; + ScreenTriangleStepVariables gradientY; + ScreenTriangleStepVariables start; + gradientX.W = FindGradientX(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.w, v2.w, v3.w); + gradientY.W = FindGradientY(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.w, v2.w, v3.w); + start.W = v1.w + gradientX.W * (startX - v1.x) + gradientY.W * (startY - v1.y); + for (int i = 0; i < TriVertex::NumVarying; i++) + { + gradientX.Varying[i] = FindGradientX(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.varying[i] * v1.w, v2.varying[i] * v2.w, v3.varying[i] * v3.w); + gradientY.Varying[i] = FindGradientY(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.varying[i] * v1.w, v2.varying[i] * v2.w, v3.varying[i] * v3.w); + start.Varying[i] = v1.varying[i] * v1.w + gradientX.Varying[i] * (startX - v1.x) + gradientY.Varying[i] * (startY - v1.y); + } + + const uint32_t * RESTRICT texPixels = (const uint32_t *)args->texturePixels; + uint32_t texWidth = args->textureWidth; + uint32_t texHeight = args->textureHeight; + + uint32_t * RESTRICT destOrg = (uint32_t*)args->dest; + uint32_t * RESTRICT subsectorGBuffer = (uint32_t*)args->subsectorGBuffer; + int pitch = args->pitch; + + uint32_t subsectorDepth = args->uniforms->subsectorDepth; + + uint32_t light = args->uniforms->light; + float shade = (64.0f - (light * 255 / 256 + 12.0f) * 32.0f / 128.0f) / 32.0f; + float globVis = 1706.0f; + + for (int i = 0; i < numSpans; i++) + { + const auto &span = fullSpans[i]; + + uint32_t *dest = destOrg + span.X + span.Y * pitch; + uint32_t *subsector = subsectorGBuffer + span.X + span.Y * pitch; + int width = span.Length; + int height = 8; + + ScreenTriangleStepVariables blockPosY; + blockPosY.W = start.W + gradientX.W * (span.X - startX) + gradientY.W * (span.Y - startY); + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] = start.Varying[j] + gradientX.Varying[j] * (span.X - startX) + gradientY.Varying[j] * (span.Y - startY); + + for (int y = 0; y < height; y++) + { + ScreenTriangleStepVariables blockPosX = blockPosY; + + float rcpW = 0x01000000 / blockPosX.W; + int32_t varyingPos[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = (int32_t)(blockPosX.Varying[j] * rcpW); + int lightpos = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + + for (int x = 0; x < width; x++) + { + blockPosX.W += gradientX.W * 8; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] += gradientX.Varying[j] * 8; + + rcpW = 0x01000000 / blockPosX.W; + int32_t varyingStep[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + { + int32_t nextPos = (int32_t)(blockPosX.Varying[j] * rcpW); + varyingStep[j] = (nextPos - varyingPos[j]) / 8; + } + + int lightnext = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + int lightstep = (lightnext - lightpos) / 8; + + for (int ix = 0; ix < 8; ix++) + { + int texelX = ((((uint32_t)varyingPos[0] << 8) >> 16) * texWidth) >> 16; + int texelY = ((((uint32_t)varyingPos[1] << 8) >> 16) * texHeight) >> 16; + uint32_t fg = texPixels[texelX * texHeight + texelY]; + + uint32_t r = RPART(fg); + uint32_t g = GPART(fg); + uint32_t b = BPART(fg); + r = r * lightpos / 256; + g = g * lightpos / 256; + b = b * lightpos / 256; + fg = 0xff000000 | (r << 16) | (g << 8) | b; + + dest[x * 8 + ix] = fg; + subsector[x * 8 + ix] = subsectorDepth; + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] += varyingStep[j]; + lightpos += lightstep; + } + } + + blockPosY.W += gradientY.W; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] += gradientY.Varying[j]; + + dest += pitch; + subsector += pitch; + } + } + + for (int i = 0; i < numBlocks; i++) + { + const auto &block = partialBlocks[i]; + + ScreenTriangleStepVariables blockPosY; + blockPosY.W = start.W + gradientX.W * (block.X - startX) + gradientY.W * (block.Y - startY); + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] = start.Varying[j] + gradientX.Varying[j] * (block.X - startX) + gradientY.Varying[j] * (block.Y - startY); + + uint32_t *dest = destOrg + block.X + block.Y * pitch; + uint32_t *subsector = subsectorGBuffer + block.X + block.Y * pitch; + uint32_t mask0 = block.Mask0; + uint32_t mask1 = block.Mask1; + for (int y = 0; y < 4; y++) + { + ScreenTriangleStepVariables blockPosX = blockPosY; + + float rcpW = 0x01000000 / blockPosX.W; + int32_t varyingPos[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = (int32_t)(blockPosX.Varying[j] * rcpW); + + int lightpos = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + + blockPosX.W += gradientX.W * 8; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] += gradientX.Varying[j] * 8; + + rcpW = 0x01000000 / blockPosX.W; + int32_t varyingStep[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + { + int32_t nextPos = (int32_t)(blockPosX.Varying[j] * rcpW); + varyingStep[j] = (nextPos - varyingPos[j]) / 8; + } + + int lightnext = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + int lightstep = (lightnext - lightpos) / 8; + + for (int x = 0; x < 8; x++) + { + if (mask0 & (1 << 31)) + { + int texelX = ((((uint32_t)varyingPos[0] << 8) >> 16) * texWidth) >> 16; + int texelY = ((((uint32_t)varyingPos[1] << 8) >> 16) * texHeight) >> 16; + uint32_t fg = texPixels[texelX * texHeight + texelY]; + + uint32_t r = RPART(fg); + uint32_t g = GPART(fg); + uint32_t b = BPART(fg); + r = r * lightpos / 256; + g = g * lightpos / 256; + b = b * lightpos / 256; + fg = 0xff000000 | (r << 16) | (g << 8) | b; + + dest[x] = fg; + subsector[x] = subsectorDepth; + } + mask0 <<= 1; + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] += varyingStep[j]; + lightpos += lightstep; + } + + blockPosY.W += gradientY.W; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] += gradientY.Varying[j]; + + dest += pitch; + subsector += pitch; + } + for (int y = 4; y < 8; y++) + { + ScreenTriangleStepVariables blockPosX = blockPosY; + + float rcpW = 0x01000000 / blockPosX.W; + int32_t varyingPos[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = (int32_t)(blockPosX.Varying[j] * rcpW); + + int lightpos = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + + blockPosX.W += gradientX.W * 8; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] += gradientX.Varying[j] * 8; + + rcpW = 0x01000000 / blockPosX.W; + int32_t varyingStep[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + { + int32_t nextPos = (int32_t)(blockPosX.Varying[j] * rcpW); + varyingStep[j] = (nextPos - varyingPos[j]) / 8; + } + + int lightnext = 256 - (int)(clamp(shade - MIN(24.0f, globVis * blockPosX.W) / 32.0f, 0.0f, 31.0f / 32.0f) * 256.0f); + int lightstep = (lightnext - lightpos) / 8; + + for (int x = 0; x < 8; x++) + { + if (mask1 & (1 << 31)) + { + int texelX = ((((uint32_t)varyingPos[0] << 8) >> 16) * texWidth) >> 16; + int texelY = ((((uint32_t)varyingPos[1] << 8) >> 16) * texHeight) >> 16; + uint32_t fg = texPixels[texelX * texHeight + texelY]; + + uint32_t r = RPART(fg); + uint32_t g = GPART(fg); + uint32_t b = BPART(fg); + r = r * lightpos / 256; + g = g * lightpos / 256; + b = b * lightpos / 256; + fg = 0xff000000 | (r << 16) | (g << 8) | b; + + dest[x] = fg; + subsector[x] = subsectorDepth; + } + mask1 <<= 1; + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] += varyingStep[j]; + lightpos += lightstep; + } + + blockPosY.W += gradientY.W; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] += gradientY.Varying[j]; + + dest += pitch; + subsector += pitch; + } + } +} +#endif diff --git a/src/r_poly_triangle.h b/src/r_poly_triangle.h new file mode 100644 index 000000000..5b66e80e2 --- /dev/null +++ b/src/r_poly_triangle.h @@ -0,0 +1,287 @@ +/* +** Triangle drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_draw.h" +#include "r_thread.h" +#include "r_drawers.h" +#include "r_data/r_translate.h" +#include "r_data/colormaps.h" + +class FTexture; + +enum class TriangleDrawMode +{ + Normal, + Fan, + Strip +}; + +struct TriDrawTriangleArgs; +struct TriMatrix; + +class PolyDrawArgs +{ +public: + TriUniforms uniforms; + const TriMatrix *objectToClip = nullptr; + const TriVertex *vinput = nullptr; + int vcount = 0; + TriangleDrawMode mode = TriangleDrawMode::Normal; + bool ccw = false; + // bool stencilTest = true; // Always true for now + bool subsectorTest = false; + bool writeStencil = true; + bool writeColor = true; + bool writeSubsector = true; + const uint8_t *texturePixels = nullptr; + int textureWidth = 0; + int textureHeight = 0; + const uint8_t *translation = nullptr; + uint8_t stenciltestvalue = 0; + uint8_t stencilwritevalue = 0; + const uint8_t *colormaps = nullptr; + float clipPlane[4]; + TriBlendMode blendmode = TriBlendMode::Copy; + + void SetClipPlane(float a, float b, float c, float d) + { + clipPlane[0] = a; + clipPlane[1] = b; + clipPlane[2] = c; + clipPlane[3] = d; + } + + void SetTexture(FTexture *texture) + { + textureWidth = texture->GetWidth(); + textureHeight = texture->GetHeight(); + if (swrenderer::r_swtruecolor) + texturePixels = (const uint8_t *)texture->GetPixelsBgra(); + else + texturePixels = texture->GetPixels(); + translation = nullptr; + } + + void SetTexture(FTexture *texture, uint32_t translationID, bool forcePal = false) + { + if (translationID != 0xffffffff && translationID != 0) + { + FRemapTable *table = TranslationToTable(translationID); + if (table != nullptr && !table->Inactive) + { + if (swrenderer::r_swtruecolor) + translation = (uint8_t*)table->Palette; + else + translation = table->Remap; + + textureWidth = texture->GetWidth(); + textureHeight = texture->GetHeight(); + texturePixels = texture->GetPixels(); + return; + } + } + + if (forcePal) + { + textureWidth = texture->GetWidth(); + textureHeight = texture->GetHeight(); + texturePixels = texture->GetPixels(); + } + else + { + SetTexture(texture); + } + } + + void SetColormap(FSWColormap *base_colormap) + { + uniforms.light_red = base_colormap->Color.r * 256 / 255; + uniforms.light_green = base_colormap->Color.g * 256 / 255; + uniforms.light_blue = base_colormap->Color.b * 256 / 255; + uniforms.light_alpha = base_colormap->Color.a * 256 / 255; + uniforms.fade_red = base_colormap->Fade.r; + uniforms.fade_green = base_colormap->Fade.g; + uniforms.fade_blue = base_colormap->Fade.b; + uniforms.fade_alpha = base_colormap->Fade.a; + uniforms.desaturate = MIN(abs(base_colormap->Desaturate), 255) * 255 / 256; + bool simple_shade = (base_colormap->Color.d == 0x00ffffff && base_colormap->Fade.d == 0x00000000 && base_colormap->Desaturate == 0); + if (simple_shade) + uniforms.flags |= TriUniforms::simple_shade; + else + uniforms.flags &= ~TriUniforms::simple_shade; + colormaps = base_colormap->Maps; + } +}; + +struct ShadedTriVertex : public TriVertex +{ + float clipDistance0; +}; + +struct TriMatrix +{ + static TriMatrix null(); + static TriMatrix identity(); + static TriMatrix translate(float x, float y, float z); + static TriMatrix scale(float x, float y, float z); + static TriMatrix rotate(float angle, float x, float y, float z); + static TriMatrix swapYZ(); + static TriMatrix perspective(float fovy, float aspect, float near, float far); + static TriMatrix frustum(float left, float right, float bottom, float top, float near, float far); + + static TriMatrix worldToView(); // Software renderer world to view space transform + static TriMatrix viewToClip(); // Software renderer shearing projection + + ShadedTriVertex operator*(TriVertex v) const; + TriMatrix operator*(const TriMatrix &m) const; + + float matrix[16]; +}; + +typedef void(*PolyDrawFuncPtr)(const TriDrawTriangleArgs *, WorkerThreadData *); + +class PolyTriangleDrawer +{ +public: + static void set_viewport(int x, int y, int width, int height, DCanvas *canvas); + static void draw(const PolyDrawArgs &args); + static void toggle_mirror(); + +private: + static ShadedTriVertex shade_vertex(const TriMatrix &objectToClip, const float *clipPlane, const TriVertex &v); + static void draw_arrays(const PolyDrawArgs &args, WorkerThreadData *thread); + static void draw_shaded_triangle(const ShadedTriVertex *vertices, bool ccw, TriDrawTriangleArgs *args, WorkerThreadData *thread, PolyDrawFuncPtr *drawfuncs, int num_drawfuncs); + static bool cullhalfspace(float clipdistance1, float clipdistance2, float &t1, float &t2); + static void clipedge(const ShadedTriVertex *verts, TriVertex *clippedvert, int &numclipvert); + + static int viewport_x, viewport_y, viewport_width, viewport_height, dest_pitch, dest_width, dest_height; + static bool dest_bgra; + static uint8_t *dest; + static bool mirror; + + enum { max_additional_vertices = 16 }; + + friend class DrawPolyTrianglesCommand; +}; + +class PolySubsectorGBuffer +{ +public: + static PolySubsectorGBuffer *Instance() + { + static PolySubsectorGBuffer buffer; + return &buffer; + } + + void Resize(int newwidth, int newheight) + { + width = newwidth; + height = newheight; + values.resize(width * height); + } + + int Width() const { return width; } + int Height() const { return height; } + uint32_t *Values() { return values.data(); } + +private: + int width; + int height; + std::vector values; +}; + +class PolyStencilBuffer +{ +public: + static PolyStencilBuffer *Instance() + { + static PolyStencilBuffer buffer; + return &buffer; + } + + void Clear(int newwidth, int newheight, uint8_t stencil_value = 0) + { + width = newwidth; + height = newheight; + int count = BlockWidth() * BlockHeight(); + values.resize(count * 64); + masks.resize(count); + + uint8_t *v = Values(); + uint32_t *m = Masks(); + for (int i = 0; i < count; i++) + { + m[i] = 0xffffff00 | stencil_value; + } + } + + int Width() const { return width; } + int Height() const { return height; } + int BlockWidth() const { return (width + 7) / 8; } + int BlockHeight() const { return (height + 7) / 8; } + uint8_t *Values() { return values.data(); } + uint32_t *Masks() { return masks.data(); } + +private: + int width; + int height; + + // 8x8 blocks of stencil values, plus a mask for each block indicating if values are the same for early out stencil testing + std::vector values; + std::vector masks; +}; + +class DrawPolyTrianglesCommand : public DrawerCommand +{ +public: + DrawPolyTrianglesCommand(const PolyDrawArgs &args, bool mirror); + + void Execute(DrawerThread *thread) override; + FString DebugInfo() override; + +private: + PolyDrawArgs args; +}; + +class PolyVertexBuffer +{ +public: + static TriVertex *GetVertices(int count); + static void Clear(); +}; + +struct ScreenTriangleStepVariables +{ + float W; + float Varying[TriVertex::NumVarying]; +}; + +class ScreenTriangle +{ +public: + static void SetupNormal(const TriDrawTriangleArgs *args, WorkerThreadData *thread); + static void SetupSubsector(const TriDrawTriangleArgs *args, WorkerThreadData *thread); + static void StencilWrite(const TriDrawTriangleArgs *args, WorkerThreadData *thread); + static void SubsectorWrite(const TriDrawTriangleArgs *args, WorkerThreadData *thread); +}; diff --git a/src/r_poly_wall.cpp b/src/r_poly_wall.cpp new file mode 100644 index 000000000..f9d409b60 --- /dev/null +++ b/src/r_poly_wall.cpp @@ -0,0 +1,478 @@ +/* +** Handling drawing a wall +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "doomstat.h" +#include "doomdata.h" +#include "p_lnspec.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_wall.h" +#include "r_poly_decal.h" +#include "r_poly.h" +#include "r_sky.h" + +EXTERN_CVAR(Bool, r_drawmirrors) + +bool RenderPolyWall::RenderLine(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth, uint32_t stencilValue, std::vector &translucentWallsOutput, std::vector> &linePortals) +{ + PolyDrawLinePortal *polyportal = nullptr; + if (line->backsector == nullptr && line->linedef && line->sidedef == line->linedef->sidedef[0] && (line->linedef->special == Line_Mirror && r_drawmirrors)) + { + if (PolyRenderer::Instance()->InsertSeenMirror(line->linedef)) + { + linePortals.push_back(std::make_unique(line->linedef)); + polyportal = linePortals.back().get(); + } + } + else if (line->linedef && line->linedef->isVisualPortal()) + { + FLinePortal *portal = line->linedef->getPortal(); + if (PolyRenderer::Instance()->InsertSeenLinePortal(portal)) + { + for (auto &p : linePortals) + { + if (p->Portal == portal) // To do: what other criterias do we need to check for? + { + polyportal = p.get(); + break; + } + } + if (!polyportal) + { + linePortals.push_back(std::make_unique(portal)); + polyportal = linePortals.back().get(); + } + } + } + + RenderPolyWall wall; + wall.LineSeg = line; + wall.Line = line->linedef; + wall.Side = line->sidedef; + wall.Colormap = frontsector->ColorMap; + wall.Masked = false; + wall.SubsectorDepth = subsectorDepth; + wall.StencilValue = stencilValue; + + double frontceilz1 = frontsector->ceilingplane.ZatPoint(line->v1); + double frontfloorz1 = frontsector->floorplane.ZatPoint(line->v1); + double frontceilz2 = frontsector->ceilingplane.ZatPoint(line->v2); + double frontfloorz2 = frontsector->floorplane.ZatPoint(line->v2); + + if (line->backsector == nullptr) + { + if (line->sidedef) + { + wall.SetCoords(line->v1->fPos(), line->v2->fPos(), frontceilz1, frontfloorz1, frontceilz2, frontfloorz2); + wall.TopZ = frontceilz1; + wall.BottomZ = frontfloorz1; + wall.UnpeggedCeil = frontceilz1; + wall.Texpart = side_t::mid; + wall.Polyportal = polyportal; + wall.Render(worldToClip, clipPlane, cull); + return true; + } + } + else + { + sector_t *backsector = (line->backsector != line->frontsector) ? line->backsector : line->frontsector; + + double backceilz1 = backsector->ceilingplane.ZatPoint(line->v1); + double backfloorz1 = backsector->floorplane.ZatPoint(line->v1); + double backceilz2 = backsector->ceilingplane.ZatPoint(line->v2); + double backfloorz2 = backsector->floorplane.ZatPoint(line->v2); + + double topceilz1 = frontceilz1; + double topceilz2 = frontceilz2; + double topfloorz1 = MIN(backceilz1, frontceilz1); + double topfloorz2 = MIN(backceilz2, frontceilz2); + double bottomceilz1 = MAX(frontfloorz1, backfloorz1); + double bottomceilz2 = MAX(frontfloorz2, backfloorz2); + double bottomfloorz1 = frontfloorz1; + double bottomfloorz2 = frontfloorz2; + double middleceilz1 = topfloorz1; + double middleceilz2 = topfloorz2; + double middlefloorz1 = MIN(bottomceilz1, middleceilz1); + double middlefloorz2 = MIN(bottomceilz2, middleceilz2); + + bool bothSkyCeiling = frontsector->GetTexture(sector_t::ceiling) == skyflatnum && backsector->GetTexture(sector_t::ceiling) == skyflatnum; + + if ((topceilz1 > topfloorz1 || topceilz2 > topfloorz2) && line->sidedef && !bothSkyCeiling) + { + wall.SetCoords(line->v1->fPos(), line->v2->fPos(), topceilz1, topfloorz1, topceilz2, topfloorz2); + wall.TopZ = topceilz1; + wall.BottomZ = topfloorz1; + wall.UnpeggedCeil = topceilz1; + wall.Texpart = side_t::top; + wall.Render(worldToClip, clipPlane, cull); + } + + if ((bottomfloorz1 < bottomceilz1 || bottomfloorz2 < bottomceilz2) && line->sidedef) + { + wall.SetCoords(line->v1->fPos(), line->v2->fPos(), bottomceilz1, bottomfloorz1, bottomceilz2, bottomfloorz2); + wall.TopZ = bottomceilz1; + wall.BottomZ = bottomfloorz2; + wall.UnpeggedCeil = topceilz1; + wall.Texpart = side_t::bottom; + wall.Render(worldToClip, clipPlane, cull); + } + + if (line->sidedef) + { + wall.SetCoords(line->v1->fPos(), line->v2->fPos(), middleceilz1, middlefloorz1, middleceilz2, middlefloorz2); + wall.TopZ = middleceilz1; + wall.BottomZ = middlefloorz1; + wall.UnpeggedCeil = topceilz1; + wall.Texpart = side_t::mid; + wall.Masked = true; + + FTexture *midtex = TexMan(line->sidedef->GetTexture(side_t::mid), true); + if (midtex && midtex->UseType != FTexture::TEX_Null) + translucentWallsOutput.push_back({ wall }); + + if (polyportal) + { + wall.Polyportal = polyportal; + wall.Render(worldToClip, clipPlane, cull); + } + } + } + return polyportal != nullptr; +} + +void RenderPolyWall::Render3DFloorLine(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth, uint32_t stencilValue, F3DFloor *fakeFloor, std::vector &translucentWallsOutput) +{ + double frontceilz1 = fakeFloor->top.plane->ZatPoint(line->v1); + double frontfloorz1 = fakeFloor->bottom.plane->ZatPoint(line->v1); + double frontceilz2 = fakeFloor->top.plane->ZatPoint(line->v2); + double frontfloorz2 = fakeFloor->bottom.plane->ZatPoint(line->v2); + + RenderPolyWall wall; + wall.LineSeg = line; + wall.Line = fakeFloor->master; + wall.Side = fakeFloor->master->sidedef[0]; + wall.Colormap = frontsector->ColorMap; + wall.Masked = false; + wall.SubsectorDepth = subsectorDepth; + wall.StencilValue = stencilValue; + wall.SetCoords(line->v1->fPos(), line->v2->fPos(), frontceilz1, frontfloorz1, frontceilz2, frontfloorz2); + wall.TopZ = frontceilz1; + wall.BottomZ = frontfloorz1; + wall.UnpeggedCeil = frontceilz1; + wall.Texpart = side_t::mid; + wall.Render(worldToClip, clipPlane, cull); +} + +void RenderPolyWall::SetCoords(const DVector2 &v1, const DVector2 &v2, double ceil1, double floor1, double ceil2, double floor2) +{ + this->v1 = v1; + this->v2 = v2; + this->ceil1 = ceil1; + this->floor1 = floor1; + this->ceil2 = ceil2; + this->floor2 = floor2; +} + +void RenderPolyWall::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull) +{ + FTexture *tex = GetTexture(); + if (!tex && !Polyportal) + return; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(4); + if (!vertices) + return; + + vertices[0].x = (float)v1.X; + vertices[0].y = (float)v1.Y; + vertices[0].z = (float)ceil1; + vertices[0].w = 1.0f; + + vertices[1].x = (float)v2.X; + vertices[1].y = (float)v2.Y; + vertices[1].z = (float)ceil2; + vertices[1].w = 1.0f; + + vertices[2].x = (float)v2.X; + vertices[2].y = (float)v2.Y; + vertices[2].z = (float)floor2; + vertices[2].w = 1.0f; + + vertices[3].x = (float)v1.X; + vertices[3].y = (float)v1.Y; + vertices[3].z = (float)floor1; + vertices[3].w = 1.0f; + + if (tex) + { + PolyWallTextureCoords texcoords(tex, LineSeg, Line, Side, Texpart, TopZ, BottomZ, UnpeggedCeil); + vertices[0].varying[0] = (float)texcoords.u1; + vertices[0].varying[1] = (float)texcoords.v1; + vertices[1].varying[0] = (float)texcoords.u2; + vertices[1].varying[1] = (float)texcoords.v1; + vertices[2].varying[0] = (float)texcoords.u2; + vertices[2].varying[1] = (float)texcoords.v2; + vertices[3].varying[0] = (float)texcoords.u1; + vertices[3].varying[1] = (float)texcoords.v2; + } + + // Masked walls clamp to the 0-1 range (no texture repeat) + if (Masked) + { + ClampHeight(vertices[0], vertices[3]); + ClampHeight(vertices[1], vertices[2]); + } + + PolyDrawArgs args; + args.uniforms.light = (uint32_t)(GetLightLevel() / 255.0f * 256.0f); + args.uniforms.flags = 0; + args.uniforms.subsectorDepth = SubsectorDepth; + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = 4; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = StencilValue; + args.stencilwritevalue = StencilValue + 1; + if (tex) + args.SetTexture(tex); + args.SetColormap(Line->frontsector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + + //if (Side && Side->lighthead) + // args.uniforms.light = 255; // Make walls touched by a light fullbright! + + if (Polyportal) + { + args.stencilwritevalue = Polyportal->StencilValue; + args.writeColor = false; + args.writeSubsector = false; + PolyTriangleDrawer::draw(args); + Polyportal->Shape.push_back({ args.vinput, args.vcount, args.ccw, args.uniforms.subsectorDepth }); + + int sx1, sx2; + LineSegmentRange range = cull.GetSegmentRangeForLine(v1.X, v1.Y, v2.X, v2.Y, sx1, sx2); + if (range == LineSegmentRange::HasSegment) + Polyportal->Segments.push_back({ sx1, sx2 }); + } + else if (!Masked) + { + args.blendmode = TriBlendMode::Copy; + PolyTriangleDrawer::draw(args); + } + else + { + args.uniforms.destalpha = (Line->flags & ML_ADDTRANS) ? 256 : (uint32_t)(256 - Line->alpha * 256); + args.uniforms.srcalpha = (uint32_t)(Line->alpha * 256); + args.subsectorTest = true; + args.writeSubsector = false; + args.writeStencil = false; + if (args.uniforms.destalpha == 0 && args.uniforms.srcalpha == 256) + args.blendmode = TriBlendMode::AlphaBlend; + else + args.blendmode = TriBlendMode::Add; + PolyTriangleDrawer::draw(args); + } + + RenderPolyDecal::RenderWallDecals(worldToClip, clipPlane, LineSeg, SubsectorDepth, StencilValue); +} + +void RenderPolyWall::ClampHeight(TriVertex &v1, TriVertex &v2) +{ + float top = v1.z; + float bottom = v2.z; + float texv1 = v1.varying[1]; + float texv2 = v2.varying[1]; + float delta = (texv2 - texv1); + + float t1 = texv1 < 0.0f ? -texv1 / delta : 0.0f; + float t2 = texv2 > 1.0f ? (1.0f - texv1) / delta : 1.0f; + float inv_t1 = 1.0f - t1; + float inv_t2 = 1.0f - t2; + + v1.z = top * inv_t1 + bottom * t1; + v1.varying[1] = texv1 * inv_t1 + texv2 * t1; + + v2.z = top * inv_t2 + bottom * t2; + v2.varying[1] = texv1 * inv_t2 + texv2 * t2; +} + +FTexture *RenderPolyWall::GetTexture() +{ + FTexture *tex = TexMan(Side->GetTexture(Texpart), true); + if (tex == nullptr || tex->UseType == FTexture::TEX_Null) + { + // Mapping error. Doom floodfills this with a plane. + // This code doesn't do that, but at least it uses the "right" texture.. + + if (Line && Line->backsector && Line->sidedef[0] == Side) + { + if (Texpart == side_t::top) + tex = TexMan(Line->backsector->GetTexture(sector_t::ceiling), true); + else if (Texpart == side_t::bottom) + tex = TexMan(Line->backsector->GetTexture(sector_t::floor), true); + } + if (Line && Line->backsector && Line->sidedef[1] == Side) + { + if (Texpart == side_t::top) + tex = TexMan(Line->frontsector->GetTexture(sector_t::ceiling), true); + else if (Texpart == side_t::bottom) + tex = TexMan(Line->frontsector->GetTexture(sector_t::floor), true); + } + + if (tex == nullptr || tex->UseType == FTexture::TEX_Null) + return nullptr; + } + return tex; +} + +int RenderPolyWall::GetLightLevel() +{ + if (swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + { + return 255; + } + else + { + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + return clamp(Side->GetLightLevel(foggy, LineSeg->frontsector->lightlevel) + actualextralight, 0, 255); + } +} + +///////////////////////////////////////////////////////////////////////////// + +PolyWallTextureCoords::PolyWallTextureCoords(FTexture *tex, const seg_t *lineseg, const line_t *line, const side_t *side, side_t::ETexpart texpart, double topz, double bottomz, double unpeggedceil) +{ + CalcU(tex, lineseg, line, side, texpart); + CalcV(tex, line, side, texpart, topz, bottomz, unpeggedceil); +} + +void PolyWallTextureCoords::CalcU(FTexture *tex, const seg_t *lineseg, const line_t *line, const side_t *side, side_t::ETexpart texpart) +{ + double lineLength = side->TexelLength; + double lineStart = 0.0; + + bool entireSegment = ((lineseg->v1 == line->v1) && (lineseg->v2 == line->v2)) || ((lineseg->v2 == line->v1) && (lineseg->v1 == line->v2)); + if (!entireSegment) + { + lineLength = (lineseg->v2->fPos() - lineseg->v1->fPos()).Length(); + lineStart = (lineseg->v1->fPos() - line->v1->fPos()).Length(); + } + + int texWidth = tex->GetWidth(); + double uscale = side->GetTextureXScale(texpart) * tex->Scale.X; + u1 = lineStart + side->GetTextureXOffset(texpart); + u2 = u1 + lineLength; + u1 *= uscale; + u2 *= uscale; + u1 /= texWidth; + u2 /= texWidth; +} + +void PolyWallTextureCoords::CalcV(FTexture *tex, const line_t *line, const side_t *side, side_t::ETexpart texpart, double topz, double bottomz, double unpeggedceil) +{ + double vscale = side->GetTextureYScale(texpart) * tex->Scale.Y; + + double yoffset = side->GetTextureYOffset(texpart); + if (tex->bWorldPanning) + yoffset *= vscale; + + switch (texpart) + { + default: + case side_t::mid: + CalcVMidPart(tex, line, side, topz, bottomz, vscale, yoffset); + break; + case side_t::top: + CalcVTopPart(tex, line, side, topz, bottomz, vscale, yoffset); + break; + case side_t::bottom: + CalcVBottomPart(tex, line, side, topz, bottomz, unpeggedceil, vscale, yoffset); + break; + } + + int texHeight = tex->GetHeight(); + v1 /= texHeight; + v2 /= texHeight; +} + +void PolyWallTextureCoords::CalcVTopPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double vscale, double yoffset) +{ + bool pegged = (line->flags & ML_DONTPEGTOP) == 0; + if (pegged) // bottom to top + { + int texHeight = tex->GetHeight(); + v1 = -yoffset; + v2 = v1 + (topz - bottomz); + v1 *= vscale; + v2 *= vscale; + v1 = texHeight - v1; + v2 = texHeight - v2; + std::swap(v1, v2); + } + else // top to bottom + { + v1 = yoffset; + v2 = v1 + (topz - bottomz); + v1 *= vscale; + v2 *= vscale; + } +} + +void PolyWallTextureCoords::CalcVMidPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double vscale, double yoffset) +{ + bool pegged = (line->flags & ML_DONTPEGBOTTOM) == 0; + if (pegged) // top to bottom + { + v1 = yoffset * vscale; + v2 = (yoffset + (topz - bottomz)) * vscale; + } + else // bottom to top + { + int texHeight = tex->GetHeight(); + v1 = texHeight - (-yoffset + (topz - bottomz)) * vscale; + v2 = texHeight + yoffset * vscale; + } +} + +void PolyWallTextureCoords::CalcVBottomPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double unpeggedceil, double vscale, double yoffset) +{ + bool pegged = (line->flags & ML_DONTPEGBOTTOM) == 0; + if (pegged) // top to bottom + { + v1 = yoffset; + v2 = v1 + (topz - bottomz); + v1 *= vscale; + v2 *= vscale; + } + else + { + v1 = yoffset + (unpeggedceil - topz); + v2 = v1 + (topz - bottomz); + v1 *= vscale; + v2 *= vscale; + } +} diff --git a/src/r_poly_wall.h b/src/r_poly_wall.h new file mode 100644 index 000000000..8443a174a --- /dev/null +++ b/src/r_poly_wall.h @@ -0,0 +1,82 @@ +/* +** Handling drawing a wall +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class PolyTranslucentObject; +class PolyDrawLinePortal; +class PolyCull; +class Vec4f; + +class RenderPolyWall +{ +public: + static bool RenderLine(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth, uint32_t stencilValue, std::vector &translucentWallsOutput, std::vector> &linePortals); + static void Render3DFloorLine(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull, seg_t *line, sector_t *frontsector, uint32_t subsectorDepth, uint32_t stencilValue, F3DFloor *fakeFloor, std::vector &translucentWallsOutput); + + void SetCoords(const DVector2 &v1, const DVector2 &v2, double ceil1, double floor1, double ceil2, double floor2); + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, PolyCull &cull); + + DVector2 v1; + DVector2 v2; + double ceil1 = 0.0; + double floor1 = 0.0; + double ceil2 = 0.0; + double floor2 = 0.0; + + const seg_t *LineSeg = nullptr; + const line_t *Line = nullptr; + const side_t *Side = nullptr; + side_t::ETexpart Texpart = side_t::mid; + double TopZ = 0.0; + double BottomZ = 0.0; + double UnpeggedCeil = 0.0; + FSWColormap *Colormap = nullptr; + bool Masked = false; + uint32_t SubsectorDepth = 0; + uint32_t StencilValue = 0; + PolyDrawLinePortal *Polyportal = nullptr; + +private: + void ClampHeight(TriVertex &v1, TriVertex &v2); + FTexture *GetTexture(); + int GetLightLevel(); +}; + +// Texture coordinates for a wall +class PolyWallTextureCoords +{ +public: + PolyWallTextureCoords(FTexture *tex, const seg_t *lineseg, const line_t *line, const side_t *side, side_t::ETexpart texpart, double topz, double bottomz, double unpeggedceil); + + double u1, u2; + double v1, v2; + +private: + void CalcU(FTexture *tex, const seg_t *lineseg, const line_t *line, const side_t *side, side_t::ETexpart texpart); + void CalcV(FTexture *tex, const line_t *line, const side_t *side, side_t::ETexpart texpart, double topz, double bottomz, double unpeggedceil); + void CalcVTopPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double vscale, double yoffset); + void CalcVMidPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double vscale, double yoffset); + void CalcVBottomPart(FTexture *tex, const line_t *line, const side_t *side, double topz, double bottomz, double unpeggedceil, double vscale, double yoffset); +}; diff --git a/src/r_poly_wallsprite.cpp b/src/r_poly_wallsprite.cpp new file mode 100644 index 000000000..fe12b271d --- /dev/null +++ b/src/r_poly_wallsprite.cpp @@ -0,0 +1,129 @@ +/* +** Handling drawing a sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_poly_wallsprite.h" +#include "r_poly.h" + +void RenderPolyWallSprite::Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, AActor *thing, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue) +{ + if (RenderPolySprite::IsThingCulled(thing)) + return; + + DVector3 pos = thing->InterpolatedPosition(r_TicFracF); + pos.Z += thing->GetBobOffset(r_TicFracF); + + bool flipTextureX = false; + FTexture *tex = RenderPolySprite::GetSpriteTexture(thing, flipTextureX); + if (tex == nullptr || tex->UseType == FTexture::TEX_Null) + return; + + DVector2 spriteScale = thing->Scale; + double thingxscalemul = spriteScale.X / tex->Scale.X; + double thingyscalemul = spriteScale.Y / tex->Scale.Y; + double spriteHeight = thingyscalemul * tex->GetHeight(); + + DAngle ang = thing->Angles.Yaw + 90; + double angcos = ang.Cos(); + double angsin = ang.Sin(); + + // Determine left and right edges of sprite. The sprite's angle is its normal, + // so the edges are 90 degrees each side of it. + double x2 = tex->GetScaledWidth() * spriteScale.X; + double x1 = tex->GetScaledLeftOffset() * spriteScale.X; + DVector2 left, right; + left.X = pos.X - x1 * angcos; + left.Y = pos.Y - x1 * angsin; + right.X = left.X + x2 * angcos; + right.Y = right.Y + x2 * angsin; + + //int scaled_to = tex->GetScaledTopOffset(); + //int scaled_bo = scaled_to - tex->GetScaledHeight(); + //gzt = pos.Z + scale.Y * scaled_to; + //gzb = pos.Z + scale.Y * scaled_bo; + + DVector2 points[2] = { left, right }; + + TriVertex *vertices = PolyVertexBuffer::GetVertices(4); + if (!vertices) + return; + + bool foggy = false; + int actualextralight = foggy ? 0 : extralight << 4; + + std::pair offsets[4] = + { + { 0.0f, 1.0f }, + { 1.0f, 1.0f }, + { 1.0f, 0.0f }, + { 0.0f, 0.0f }, + }; + + for (int i = 0; i < 4; i++) + { + auto &p = (i == 0 || i == 3) ? points[0] : points[1]; + + vertices[i].x = (float)p.X; + vertices[i].y = (float)p.Y; + vertices[i].z = (float)(pos.Z + spriteHeight * offsets[i].second); + vertices[i].w = 1.0f; + vertices[i].varying[0] = (float)(offsets[i].first * tex->Scale.X); + vertices[i].varying[1] = (float)((1.0f - offsets[i].second) * tex->Scale.Y); + if (flipTextureX) + vertices[i].varying[0] = 1.0f - vertices[i].varying[0]; + } + + bool fullbrightSprite = ((thing->renderflags & RF_FULLBRIGHT) || (thing->flags5 & MF5_BRIGHT)); + + PolyDrawArgs args; + if (fullbrightSprite || swrenderer::fixedlightlev >= 0 || swrenderer::fixedcolormap) + { + args.uniforms.light = 256; + args.uniforms.flags = TriUniforms::fixed_light; + } + else + { + args.uniforms.light = (uint32_t)((thing->Sector->lightlevel + actualextralight) / 255.0f * 256.0f); + args.uniforms.flags = 0; + } + args.uniforms.subsectorDepth = subsectorDepth; + + args.objectToClip = &worldToClip; + args.vinput = vertices; + args.vcount = 4; + args.mode = TriangleDrawMode::Fan; + args.ccw = true; + args.stenciltestvalue = stencilValue; + args.stencilwritevalue = stencilValue; + args.SetTexture(tex); + args.SetColormap(sub->sector->ColorMap); + args.SetClipPlane(clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); + args.subsectorTest = true; + args.writeSubsector = false; + args.writeStencil = false; + args.blendmode = TriBlendMode::AlphaBlend; + PolyTriangleDrawer::draw(args); +} diff --git a/src/r_poly_wallsprite.h b/src/r_poly_wallsprite.h new file mode 100644 index 000000000..51cf28de6 --- /dev/null +++ b/src/r_poly_wallsprite.h @@ -0,0 +1,33 @@ +/* +** Handling drawing a wall sprite +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "r_poly_triangle.h" + +class Vec4f; + +class RenderPolyWallSprite +{ +public: + void Render(const TriMatrix &worldToClip, const Vec4f &clipPlane, AActor *thing, subsector_t *sub, uint32_t subsectorDepth, uint32_t stencilValue); +}; diff --git a/src/r_segs.cpp b/src/r_segs.cpp index ccf6ccf20..eff303acb 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -54,12 +54,13 @@ CVAR(Bool, r_fogboundary, true, 0) CVAR(Bool, r_drawmirrors, true, 0) EXTERN_CVAR(Bool, r_fullbrightignoresectorcolor); +EXTERN_CVAR(Bool, r_mipmap) namespace swrenderer { using namespace drawerargs; - void R_DrawWallSegment(FTexture *rw_pic, int x1, int x2, short *walltop, short *wallbottom, float *swall, fixed_t *lwall, double yscale, double top, double bottom, bool mask); + void R_DrawWallSegment(FTexture *rw_pic, int x1, int x2, short *walltop, short *wallbottom, float *swall, fixed_t *lwall, double yscale, double top, double bottom, bool mask, FLightNode *light_list = nullptr); void R_DrawDrawSeg(drawseg_t *ds, int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat); #define HEIGHTBITS 12 @@ -152,7 +153,7 @@ inline bool IsFogBoundary (sector_t *front, sector_t *back) float *MaskedSWall; float MaskedScaleY; -static void BlastMaskedColumn (FTexture *tex, bool useRt) +static void BlastMaskedColumn (FTexture *tex) { // calculate lighting if (fixedcolormap == NULL && fixedlightlev < 0) @@ -175,7 +176,7 @@ static void BlastMaskedColumn (FTexture *tex, bool useRt) // when forming multipatched textures (see r_data.c). // draw the texture - R_DrawMaskedColumn(tex, maskedtexturecol[dc_x], useRt); + R_DrawMaskedColumn(tex, maskedtexturecol[dc_x]); rw_light += rw_lightstep; spryscale += rw_scalestep; } @@ -217,14 +218,10 @@ void R_RenderMaskedSegRange (drawseg_t *ds, int x1, int x2) curline = ds->curline; - // killough 4/11/98: draw translucent 2s normal textures - // [RH] modified because we don't use user-definable translucency maps - ESPSResult drawmode; - - drawmode = R_SetPatchStyle (LegacyRenderStyles[curline->linedef->flags & ML_ADDTRANS ? STYLE_Add : STYLE_Translucent], + bool visible = R_SetPatchStyle (LegacyRenderStyles[curline->linedef->flags & ML_ADDTRANS ? STYLE_Add : STYLE_Translucent], (float)MIN(curline->linedef->alpha, 1.), 0, 0); - if ((drawmode == DontDraw && !ds->bFogBoundary && !ds->bFakeBoundary)) + if (!visible && !ds->bFogBoundary && !ds->bFakeBoundary) { return; } @@ -279,7 +276,7 @@ void R_RenderMaskedSegRange (drawseg_t *ds, int x1, int x2) goto clearfog; } } - if ((ds->bFakeBoundary && !(ds->bFakeBoundary & 4)) || drawmode == DontDraw) + if ((ds->bFakeBoundary && !(ds->bFakeBoundary & 4)) || !visible) { goto clearfog; } @@ -414,44 +411,11 @@ void R_RenderMaskedSegRange (drawseg_t *ds, int x1, int x2) mceilingclip = wallupper; // draw the columns one at a time - if (drawmode == DoDraw0) + if (visible) { for (dc_x = x1; dc_x < x2; ++dc_x) { - BlastMaskedColumn (tex, false); - } - } - else - { - // [RH] Draw up to four columns at once - int stop = x2 & ~3; - - if (x1 >= x2) - goto clearfog; - - dc_x = x1; - - while ((dc_x < stop) && (dc_x & 3)) - { - BlastMaskedColumn (tex, false); - dc_x++; - } - - while (dc_x < stop) - { - rt_initcols(nullptr); - BlastMaskedColumn (tex, true); dc_x++; - BlastMaskedColumn (tex, true); dc_x++; - BlastMaskedColumn (tex, true); dc_x++; - BlastMaskedColumn (tex, true); - rt_draw4cols (dc_x - 3); - dc_x++; - } - - while (dc_x < x2) - { - BlastMaskedColumn (tex, false); - dc_x++; + BlastMaskedColumn (tex); } } } @@ -544,11 +508,10 @@ void R_RenderFakeWall(drawseg_t *ds, int x1, int x2, F3DFloor *rover) double yscale; fixed_t Alpha = Scale(rover->alpha, OPAQUE, 255); - ESPSResult drawmode; - drawmode = R_SetPatchStyle (LegacyRenderStyles[rover->flags & FF_ADDITIVETRANS ? STYLE_Add : STYLE_Translucent], + bool visible = R_SetPatchStyle (LegacyRenderStyles[rover->flags & FF_ADDITIVETRANS ? STYLE_Add : STYLE_Translucent], Alpha, 0, 0); - if(drawmode == DontDraw) { + if(!visible) { R_FinishSetPatchStyle(); return; } @@ -1138,6 +1101,8 @@ void R_RenderSegLoop () } if(fake3D & 7) return; + FLightNode *light_list = (curline && curline->sidedef) ? curline->sidedef->lighthead : nullptr; + // draw the wall tiers if (midtexture) { // one sided line @@ -1164,7 +1129,7 @@ void R_RenderSegLoop () { rw_offset = -rw_offset; } - R_DrawWallSegment(rw_pic, x1, x2, walltop, wallbottom, swall, lwall, yscale, MAX(rw_frontcz1, rw_frontcz2), MIN(rw_frontfz1, rw_frontfz2), false); + R_DrawWallSegment(rw_pic, x1, x2, walltop, wallbottom, swall, lwall, yscale, MAX(rw_frontcz1, rw_frontcz2), MIN(rw_frontfz1, rw_frontfz2), false, light_list); } fillshort (ceilingclip+x1, x2-x1, viewheight); fillshort (floorclip+x1, x2-x1, 0xffff); @@ -1200,7 +1165,7 @@ void R_RenderSegLoop () { rw_offset = -rw_offset; } - R_DrawWallSegment(rw_pic, x1, x2, walltop, wallupper, swall, lwall, yscale, MAX(rw_frontcz1, rw_frontcz2), MIN(rw_backcz1, rw_backcz2), false); + R_DrawWallSegment(rw_pic, x1, x2, walltop, wallupper, swall, lwall, yscale, MAX(rw_frontcz1, rw_frontcz2), MIN(rw_backcz1, rw_backcz2), false, light_list); } memcpy (ceilingclip+x1, wallupper+x1, (x2-x1)*sizeof(short)); } @@ -1239,7 +1204,7 @@ void R_RenderSegLoop () { rw_offset = -rw_offset; } - R_DrawWallSegment(rw_pic, x1, x2, walllower, wallbottom, swall, lwall, yscale, MAX(rw_backfz1, rw_backfz2), MIN(rw_frontfz1, rw_frontfz2), false); + R_DrawWallSegment(rw_pic, x1, x2, walllower, wallbottom, swall, lwall, yscale, MAX(rw_backfz1, rw_backfz2), MIN(rw_frontfz1, rw_frontfz2), false, light_list); } memcpy (floorclip+x1, walllower+x1, (x2-x1)*sizeof(short)); } @@ -2327,9 +2292,8 @@ static void R_RenderDecal (side_t *wall, DBaseDecal *decal, drawseg_t *clipper, do { dc_x = x1; - ESPSResult mode; - mode = R_SetPatchStyle (decal->RenderStyle, (float)decal->Alpha, decal->Translation, decal->AlphaColor); + bool visible = R_SetPatchStyle (decal->RenderStyle, (float)decal->Alpha, decal->Translation, decal->AlphaColor); // R_SetPatchStyle can modify basecolormap. if (rereadcolormap) @@ -2337,55 +2301,15 @@ static void R_RenderDecal (side_t *wall, DBaseDecal *decal, drawseg_t *clipper, usecolormap = basecolormap; } - if (mode == DontDraw) + if (visible) { - needrepeat = 0; - } - else - { - int stop4; - - if (mode == DoDraw0) - { // 1 column at a time - stop4 = dc_x; - } - else // DoDraw1 - { // up to 4 columns at a time - stop4 = x2 & ~3; - } - - while ((dc_x < stop4) && (dc_x & 3)) - { - if (calclighting) - { // calculate lighting - R_SetColorMapLight(usecolormap, rw_light, wallshade); - } - R_WallSpriteColumn (false); - dc_x++; - } - - while (dc_x < stop4) - { - if (calclighting) - { // calculate lighting - R_SetColorMapLight(usecolormap, rw_light, wallshade); - } - rt_initcols(nullptr); - for (int zz = 4; zz; --zz) - { - R_WallSpriteColumn (true); - dc_x++; - } - rt_draw4cols (dc_x - 4); - } - while (dc_x < x2) { if (calclighting) { // calculate lighting R_SetColorMapLight(usecolormap, rw_light, wallshade); } - R_WallSpriteColumn (false); + R_WallSpriteColumn (); dc_x++; } } @@ -2399,8 +2323,6 @@ static void R_RenderDecal (side_t *wall, DBaseDecal *decal, drawseg_t *clipper, } while (needrepeat--); colfunc = basecolfunc; - hcolfunc_post1 = rt_map1col; - hcolfunc_post4 = rt_map4cols; R_FinishSetPatchStyle (); done: diff --git a/src/r_sky.h b/src/r_sky.h index 6ece74d74..132817983 100644 --- a/src/r_sky.h +++ b/src/r_sky.h @@ -24,7 +24,6 @@ #include "textures/textures.h" - extern FTextureID skyflatnum; extern fixed_t sky1cyl, sky2cyl; extern FTextureID sky1texture, sky2texture; diff --git a/src/r_swrenderer.cpp b/src/r_swrenderer.cpp index 87bce4013..77cbb28eb 100644 --- a/src/r_swrenderer.cpp +++ b/src/r_swrenderer.cpp @@ -42,7 +42,30 @@ #include "r_3dfloors.h" #include "textures/textures.h" #include "r_data/voxels.h" -#include "r_thread.h" +#include "r_draw_rgba.h" +#include "r_drawers.h" +#include "r_poly.h" +#include "p_setup.h" + +void gl_ParseDefs(); +void gl_InitData(); + +EXTERN_CVAR(Bool, r_shadercolormaps) +EXTERN_CVAR(Float, maxviewpitch) // [SP] CVAR from GZDoom + +CUSTOM_CVAR(Bool, r_polyrenderer, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if (self == 1 && !hasglnodes) + { + Printf("No GL BSP detected. You must restart the map before rendering will be correct\n"); + } + + if (usergame) + { + // [SP] Update pitch limits to the netgame/gamesim. + players[consoleplayer].SendPitchLimits(); + } +} namespace swrenderer { @@ -56,6 +79,14 @@ void R_InitRenderer(); using namespace swrenderer; +FSoftwareRenderer::FSoftwareRenderer() +{ +} + +FSoftwareRenderer::~FSoftwareRenderer() +{ +} + //========================================================================== // // DCanvas :: Init @@ -64,6 +95,9 @@ using namespace swrenderer; void FSoftwareRenderer::Init() { + gl_ParseDefs(); + + r_swtruecolor = screen->IsBgra(); R_InitRenderer(); } @@ -91,11 +125,17 @@ void FSoftwareRenderer::PrecacheTexture(FTexture *tex, int cache) if (cache & FTextureManager::HIT_Columnmode) { const FTexture::Span *spanp; - tex->GetColumn(0, &spanp); + if (r_swtruecolor) + tex->GetColumnBgra(0, &spanp); + else + tex->GetColumn(0, &spanp); } else if (cache != 0) { - tex->GetPixels (); + if (r_swtruecolor) + tex->GetPixelsBgra(); + else + tex->GetPixels (); } else { @@ -161,10 +201,44 @@ void FSoftwareRenderer::Precache(BYTE *texhitlist, TMap &act void FSoftwareRenderer::RenderView(player_t *player) { + if (r_polyrenderer) + { + bool saved_swtruecolor = r_swtruecolor; + r_swtruecolor = screen->IsBgra(); + + PolyRenderer::Instance()->RenderActorView(player->mo, false); + FCanvasTextureInfo::UpdateAll(); + + // Apply special colormap if the target cannot do it + if (realfixedcolormap && r_swtruecolor && !(r_shadercolormaps && screen->Accel2D)) + { + R_BeginDrawerCommands(); + DrawerCommandQueue::QueueCommand(realfixedcolormap, screen); + R_EndDrawerCommands(); + } + + r_swtruecolor = saved_swtruecolor; + + return; + } + + if (r_swtruecolor != screen->IsBgra()) + { + r_swtruecolor = screen->IsBgra(); + R_InitColumnDrawers(); + } + R_BeginDrawerCommands(); R_RenderActorView (player->mo); // [RH] Let cameras draw onto textures that were visible this frame. FCanvasTextureInfo::UpdateAll (); + + // Apply special colormap if the target cannot do it + if (realfixedcolormap && r_swtruecolor && !(r_shadercolormaps && screen->Accel2D)) + { + DrawerCommandQueue::QueueCommand(realfixedcolormap, screen); + } + R_EndDrawerCommands(); } @@ -190,13 +264,16 @@ void FSoftwareRenderer::RemapVoxels() void FSoftwareRenderer::WriteSavePic (player_t *player, FileWriter *file, int width, int height) { - DCanvas *pic = new DSimpleCanvas (width, height); + DCanvas *pic = new DSimpleCanvas (width, height, false); PalEntry palette[256]; // Take a snapshot of the player's view pic->ObjectFlags |= OF_Fixed; pic->Lock (); - R_RenderViewToCanvas (player->mo, pic, 0, 0, width, height); + if (r_polyrenderer) + PolyRenderer::Instance()->RenderViewToCanvas(player->mo, pic, 0, 0, width, height, true); + else + R_RenderViewToCanvas (player->mo, pic, 0, 0, width, height); screen->GetFlashedPalette (palette); M_CreatePNG (file, pic->GetBuffer(), palette, SS_PAL, width, height, pic->GetPitch()); pic->Unlock (); @@ -213,7 +290,14 @@ void FSoftwareRenderer::WriteSavePic (player_t *player, FileWriter *file, int wi void FSoftwareRenderer::DrawRemainingPlayerSprites() { - R_DrawRemainingPlayerSprites(); + if (!r_polyrenderer) + { + R_DrawRemainingPlayerSprites(); + } + else + { + PolyRenderer::Instance()->RenderRemainingPlayerSprites(); + } } //=========================================================================== @@ -226,7 +310,12 @@ void FSoftwareRenderer::DrawRemainingPlayerSprites() int FSoftwareRenderer::GetMaxViewPitch(bool down) { - return down ? MAX_DN_ANGLE : MAX_UP_ANGLE; + return (r_polyrenderer) ? int(maxviewpitch) : (down ? MAX_DN_ANGLE : MAX_UP_ANGLE); +} + +bool FSoftwareRenderer::RequireGLNodes() +{ + return true; } //========================================================================== @@ -274,7 +363,12 @@ void FSoftwareRenderer::ErrorCleanup () void FSoftwareRenderer::ClearBuffer(int color) { - memset(RenderTarget->GetBuffer(), color, RenderTarget->GetPitch() * RenderTarget->GetHeight()); + // [SP] For now, for truecolor, this just outputs black. We'll figure out how to get something more meaningful + // later when this actually matters more. This is just to clear HOMs for now. + if (!r_swtruecolor) + memset(RenderTarget->GetBuffer(), color, RenderTarget->GetPitch() * RenderTarget->GetHeight()); + else + memset(RenderTarget->GetBuffer(), 0, RenderTarget->GetPitch() * RenderTarget->GetHeight() * 4); } //=========================================================================== @@ -319,27 +413,70 @@ void FSoftwareRenderer::CopyStackedViewParameters() void FSoftwareRenderer::RenderTextureView (FCanvasTexture *tex, AActor *viewpoint, int fov) { - BYTE *Pixels = const_cast(tex->GetPixels()); - DSimpleCanvas *Canvas = tex->GetCanvas(); + BYTE *Pixels = r_swtruecolor ? (BYTE*)tex->GetPixelsBgra() : (BYTE*)tex->GetPixels(); + DSimpleCanvas *Canvas = r_swtruecolor ? tex->GetCanvasBgra() : tex->GetCanvas(); // curse Doom's overuse of global variables in the renderer. // These get clobbered by rendering to a camera texture but they need to be preserved so the final rendering can be done with the correct palette. - unsigned char *savecolormap = fixedcolormap; + FSWColormap *savecolormap = fixedcolormap; FSpecialColormap *savecm = realfixedcolormap; DAngle savedfov = FieldOfView; R_SetFOV ((double)fov); - R_RenderViewToCanvas (viewpoint, Canvas, 0, 0, tex->GetWidth(), tex->GetHeight(), tex->bFirstUpdate); + if (r_polyrenderer) + PolyRenderer::Instance()->RenderViewToCanvas(viewpoint, Canvas, 0, 0, tex->GetWidth(), tex->GetHeight(), tex->bFirstUpdate); + else + R_RenderViewToCanvas (viewpoint, Canvas, 0, 0, tex->GetWidth(), tex->GetHeight(), tex->bFirstUpdate); R_SetFOV (savedfov); - if (Pixels == Canvas->GetBuffer()) + + if (Canvas->IsBgra()) { - FTexture::FlipSquareBlockRemap (Pixels, tex->GetWidth(), tex->GetHeight(), GPalette.Remap); + if (Pixels == Canvas->GetBuffer()) + { + FTexture::FlipSquareBlockBgra((uint32_t*)Pixels, tex->GetWidth(), tex->GetHeight()); + } + else + { + FTexture::FlipNonSquareBlockBgra((uint32_t*)Pixels, (const uint32_t*)Canvas->GetBuffer(), tex->GetWidth(), tex->GetHeight(), Canvas->GetPitch()); + } } else { - FTexture::FlipNonSquareBlockRemap (Pixels, Canvas->GetBuffer(), tex->GetWidth(), tex->GetHeight(), Canvas->GetPitch(), GPalette.Remap); + if (Pixels == Canvas->GetBuffer()) + { + FTexture::FlipSquareBlockRemap(Pixels, tex->GetWidth(), tex->GetHeight(), GPalette.Remap); + } + else + { + FTexture::FlipNonSquareBlockRemap(Pixels, Canvas->GetBuffer(), tex->GetWidth(), tex->GetHeight(), Canvas->GetPitch(), GPalette.Remap); + } } + + if (r_swtruecolor) + { + // True color render still sometimes uses palette textures (for sprites, mostly). + // We need to make sure that both pixel buffers contain data: + int width = tex->GetWidth(); + int height = tex->GetHeight(); + BYTE *palbuffer = (BYTE *)tex->GetPixels(); + uint32_t *bgrabuffer = (uint32_t*)tex->GetPixelsBgra(); + for (int x = 0; x < width; x++) + { + for (int y = 0; y < height; y++) + { + uint32_t color = bgrabuffer[y]; + int r = RPART(color); + int g = GPART(color); + int b = BPART(color); + palbuffer[y] = RGB32k.RGB[r >> 3][g >> 3][b >> 3]; + } + palbuffer += height; + bgrabuffer += height; + } + } + tex->SetUpdated(); + fixedcolormap = savecolormap; realfixedcolormap = savecm; } diff --git a/src/r_swrenderer.h b/src/r_swrenderer.h index f9d5609a0..812ec32b5 100644 --- a/src/r_swrenderer.h +++ b/src/r_swrenderer.h @@ -3,8 +3,15 @@ #include "r_renderer.h" +void gl_SetActorLights(AActor *); +void gl_PreprocessLevel(); +void gl_CleanLevelData(); + struct FSoftwareRenderer : public FRenderer { + FSoftwareRenderer(); + ~FSoftwareRenderer(); + // Can be overridden so that the colormaps for sector color/fade won't be built. virtual bool UsesColormap() const override; @@ -25,6 +32,7 @@ struct FSoftwareRenderer : public FRenderer virtual void DrawRemainingPlayerSprites() override; virtual int GetMaxViewPitch(bool down) override; + bool RequireGLNodes() override; void OnModeSet () override; void ErrorCleanup () override; @@ -36,6 +44,21 @@ struct FSoftwareRenderer : public FRenderer void RenderTextureView (FCanvasTexture *tex, AActor *viewpoint, int fov) override; sector_t *FakeFlat(sector_t *sec, sector_t *tempsec, int *floorlightlevel, int *ceilinglightlevel, bool back) override; + void StateChanged(AActor *actor) override + { + gl_SetActorLights(actor); + } + + void PreprocessLevel() override + { + gl_PreprocessLevel(); + } + + void CleanLevelData() override + { + gl_CleanLevelData(); + } + }; diff --git a/src/r_things.cpp b/src/r_things.cpp index 43a4dd15f..8d8ae3eef 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -58,13 +58,15 @@ #include "r_plane.h" #include "r_segs.h" #include "r_3dfloors.h" +#include "r_draw_rgba.h" +#include "r_draw_pal.h" #include "v_palette.h" #include "r_data/r_translate.h" #include "r_data/colormaps.h" #include "r_data/voxels.h" #include "p_local.h" #include "p_maputl.h" -#include "r_thread.h" +#include "r_voxel.h" EXTERN_CVAR(Bool, st_scale) EXTERN_CVAR(Bool, r_shadercolormaps) @@ -72,9 +74,10 @@ EXTERN_CVAR(Int, r_drawfuzz) EXTERN_CVAR(Bool, r_deathcamera); EXTERN_CVAR(Bool, r_drawplayersprites) EXTERN_CVAR(Bool, r_drawvoxels) +EXTERN_CVAR(Bool, r_blendmethod) CVAR(Bool, r_fullbrightignoresectorcolor, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG); -//CVAR(Bool, r_splitsprites, true, CVAR_ARCHIVE) +CVAR(Bool, r_splitsprites, true, CVAR_ARCHIVE) namespace swrenderer { @@ -141,6 +144,7 @@ FTexture *WallSpriteTile; short zeroarray[MAXWIDTH]; short screenheightarray[MAXWIDTH]; + // // INITIALIZATION FUNCTIONS // @@ -256,12 +260,137 @@ double sprtopscreen; bool sprflipvert; -void R_DrawMaskedColumn (FTexture *tex, fixed_t col, bool useRt, bool unmasked) +void R_DrawMaskedColumnBgra(FTexture *tex, fixed_t col, bool unmasked) { + fixed_t saved_iscale = dc_iscale; // Save this because we need to modify it for mipmaps + + // Normalize to 0-1 range: + double uv_stepd = FIXED2DBL(dc_iscale); + double v_step = uv_stepd / tex->GetHeight(); + + // Convert to uint32: + dc_iscale = (uint32_t)(v_step * (1 << 30)); + + // Texture mipmap and filter selection: + fixed_t xoffset = col; + + double xmagnitude = 1.0; // To do: pass this into R_DrawMaskedColumn + double ymagnitude = fabs(uv_stepd); + double magnitude = MAX(ymagnitude, xmagnitude); + double min_lod = -1000.0; + double lod = MAX(log2(magnitude) + r_lod_bias, min_lod); + bool magnifying = lod < 0.0f; + + int mipmap_offset = 0; + int mip_width = tex->GetWidth(); + int mip_height = tex->GetHeight(); + uint32_t xpos = (uint32_t)((((uint64_t)xoffset) << FRACBITS) / mip_width); + if (r_mipmap && tex->Mipmapped() && mip_width > 1 && mip_height > 1) + { + int level = (int)lod; + while (level > 0 && mip_width > 1 && mip_height > 1) + { + mipmap_offset += mip_width * mip_height; + level--; + mip_width = MAX(mip_width >> 1, 1); + mip_height = MAX(mip_height >> 1, 1); + } + } + xoffset = (xpos >> FRACBITS) * mip_width; + + const uint32_t *pixels = tex->GetPixelsBgra() + mipmap_offset; + + bool filter_nearest = (magnifying && !r_magfilter) || (!magnifying && !r_minfilter); + if (filter_nearest) + { + xoffset = MAX(MIN(xoffset, (mip_width << FRACBITS) - 1), 0); + + int tx = xoffset >> FRACBITS; + dc_source = (BYTE*)(pixels + tx * mip_height); + dc_source2 = nullptr; + dc_textureheight = mip_height; + dc_texturefracx = 0; + } + else + { + xoffset = MAX(MIN(xoffset - (FRACUNIT / 2), (mip_width << FRACBITS) - 1), 0); + + int tx0 = xoffset >> FRACBITS; + int tx1 = MIN(tx0 + 1, mip_width - 1); + dc_source = (BYTE*)(pixels + tx0 * mip_height); + dc_source2 = (BYTE*)(pixels + tx1 * mip_height); + dc_textureheight = mip_height; + dc_texturefracx = (xoffset >> (FRACBITS - 4)) & 15; + } + + // Grab the posts we need to draw + const FTexture::Span *span; + tex->GetColumnBgra(col >> FRACBITS, &span); + FTexture::Span unmaskedSpan[2]; + if (unmasked) + { + span = unmaskedSpan; + unmaskedSpan[0].TopOffset = 0; + unmaskedSpan[0].Length = tex->GetHeight(); + unmaskedSpan[1].TopOffset = 0; + unmaskedSpan[1].Length = 0; + } + + // Draw each span post + while (span->Length != 0) + { + const int length = span->Length; + const int top = span->TopOffset; + + // calculate unclipped screen coordinates for post + dc_yl = (int)(sprtopscreen + spryscale * top + 0.5); + dc_yh = (int)(sprtopscreen + spryscale * (top + length) + 0.5) - 1; + + if (sprflipvert) + { + swapvalues(dc_yl, dc_yh); + } + + if (dc_yh >= mfloorclip[dc_x]) + { + dc_yh = mfloorclip[dc_x] - 1; + } + if (dc_yl < mceilingclip[dc_x]) + { + dc_yl = mceilingclip[dc_x]; + } + + if (dc_yl <= dc_yh) + { + dc_dest = (ylookup[dc_yl] + dc_x) * 4 + dc_destorg; + dc_count = dc_yh - dc_yl + 1; + + double v = ((dc_yl + 0.5 - sprtopscreen) / spryscale) / tex->GetHeight(); + dc_texturefrac = (uint32_t)(v * (1 << 30)); + + colfunc(); + } + span++; + } + + dc_iscale = saved_iscale; +} + +void R_DrawMaskedColumn (FTexture *tex, fixed_t col, bool unmasked) +{ + // Handle the linear filtered version in a different function to reduce chances of merge conflicts from zdoom. + if (r_swtruecolor && !drawer_needs_pal_input) // To do: add support to R_DrawColumnHoriz_rgba + { + R_DrawMaskedColumnBgra(tex, col, unmasked); + return; + } + const FTexture::Span *span; const BYTE *column; - - column = tex->GetColumn(col >> FRACBITS, &span); + if (r_swtruecolor && !drawer_needs_pal_input) + column = (const BYTE *)tex->GetColumnBgra(col >> FRACBITS, &span); + else + column = tex->GetColumn(col >> FRACBITS, &span); FTexture::Span unmaskedSpan[2]; if (unmasked) @@ -273,6 +402,8 @@ void R_DrawMaskedColumn (FTexture *tex, fixed_t col, bool useRt, bool unmasked) unmaskedSpan[1].Length = 0; } + int pixelsize = r_swtruecolor ? 4 : 1; + while (span->Length != 0) { const int length = span->Length; @@ -300,7 +431,8 @@ void R_DrawMaskedColumn (FTexture *tex, fixed_t col, bool useRt, bool unmasked) { dc_texturefrac = FLOAT2FIXED((dc_yl + 0.5 - sprtopscreen) / spryscale); dc_source = column; - dc_dest = (ylookup[dc_yl] + dc_x) + dc_destorg; + dc_source2 = nullptr; + dc_dest = (ylookup[dc_yl] + dc_x) * pixelsize + dc_destorg; dc_count = dc_yh - dc_yl + 1; fixed_t maxfrac = ((top + length) << FRACBITS) - 1; @@ -311,16 +443,10 @@ void R_DrawMaskedColumn (FTexture *tex, fixed_t col, bool useRt, bool unmasked) else if (dc_iscale < 0) dc_count = MIN(dc_count, (dc_texturefrac - dc_iscale) / (-dc_iscale)); - if (useRt) - hcolfunc_pre(); - else - colfunc (); + colfunc (); } span++; } - - if (sprflipvert && useRt) - rt_flip_posts(); } // [ZZ] @@ -394,9 +520,8 @@ void R_DrawVisSprite (vissprite_t *vis) { fixed_t frac; FTexture *tex; - int x2, stop4; + int x2; fixed_t xiscale; - ESPSResult mode; bool ispsprite = (!vis->sector && vis->gpos != FVector3(0, 0, 0)); if (vis->xscale == 0 || fabs(vis->yscale) < (1.0f / 32000.0f)) @@ -405,30 +530,19 @@ void R_DrawVisSprite (vissprite_t *vis) } fixed_t centeryfrac = FLOAT2FIXED(CenterY); - R_SetColorMapLight(vis->Style.colormap, 0.0f, 0); + R_SetColorMapLight(vis->Style.BaseColormap, 0, vis->Style.ColormapNum << FRACBITS); - mode = R_SetPatchStyle (vis->Style.RenderStyle, vis->Style.Alpha, vis->Translation, vis->FillColor); + bool visible = R_SetPatchStyle (vis->Style.RenderStyle, vis->Style.Alpha, vis->Translation, vis->FillColor); if (vis->Style.RenderStyle == LegacyRenderStyles[STYLE_Shaded]) { // For shaded sprites, R_SetPatchStyle sets a dc_colormap to an alpha table, but // it is the brightest one. We need to get back to the proper light level for // this sprite. - R_SetColorMapLight(dc_colormap, 0, vis->ColormapNum << FRACBITS); + R_SetColorMapLight(dc_fcolormap, 0, vis->Style.ColormapNum << FRACBITS); } - if (mode != DontDraw) + if (visible) { - if (mode == DoDraw0) - { - // One column at a time - stop4 = vis->x1; - } - else // DoDraw1 - { - // Up to four columns at a time - stop4 = vis->x2 & ~3; - } - tex = vis->pic; spryscale = vis->yscale; sprflipvert = false; @@ -456,27 +570,6 @@ void R_DrawVisSprite (vissprite_t *vis) if (dc_x < x2) { - while ((dc_x < stop4) && (dc_x & 3)) - { - if (ispsprite || !R_ClipSpriteColumnWithPortals(vis)) - R_DrawMaskedColumn (tex, frac, false); - dc_x++; - frac += xiscale; - } - - while (dc_x < stop4) - { - rt_initcols(nullptr); - for (int zz = 4; zz; --zz) - { - if (ispsprite || !R_ClipSpriteColumnWithPortals(vis)) - R_DrawMaskedColumn (tex, frac, true); - dc_x++; - frac += xiscale; - } - rt_draw4cols (dc_x - 4); - } - while (dc_x < x2) { if (ispsprite || !R_ClipSpriteColumnWithPortals(vis)) @@ -556,9 +649,8 @@ void R_DrawWallSprite(vissprite_t *spr) MaskedScaleY = (float)iyscale; dc_x = x1; - ESPSResult mode; - mode = R_SetPatchStyle (spr->Style.RenderStyle, spr->Style.Alpha, spr->Translation, spr->FillColor); + bool visible = R_SetPatchStyle (spr->Style.RenderStyle, spr->Style.Alpha, spr->Translation, spr->FillColor); // R_SetPatchStyle can modify basecolormap. if (rereadcolormap) @@ -566,50 +658,12 @@ void R_DrawWallSprite(vissprite_t *spr) usecolormap = basecolormap; } - if (mode == DontDraw) + if (!visible) { return; } else { - int stop4; - - if (mode == DoDraw0) - { // 1 column at a time - stop4 = dc_x; - } - else // DoDraw1 - { // up to 4 columns at a time - stop4 = x2 & ~3; - } - - while ((dc_x < stop4) && (dc_x & 3)) - { - if (calclighting) - { // calculate lighting - R_SetColorMapLight(usecolormap, rw_light, shade); - } - if (!R_ClipSpriteColumnWithPortals(spr)) - R_WallSpriteColumn(false); - dc_x++; - } - - while (dc_x < stop4) - { - if (calclighting) - { // calculate lighting - R_SetColorMapLight(usecolormap, rw_light, shade); - } - rt_initcols(nullptr); - for (int zz = 4; zz; --zz) - { - if (!R_ClipSpriteColumnWithPortals(spr)) - R_WallSpriteColumn(true); - dc_x++; - } - rt_draw4cols(dc_x - 4); - } - while (dc_x < x2) { if (calclighting) @@ -617,14 +671,14 @@ void R_DrawWallSprite(vissprite_t *spr) R_SetColorMapLight(usecolormap, rw_light, shade); } if (!R_ClipSpriteColumnWithPortals(spr)) - R_WallSpriteColumn(false); + R_WallSpriteColumn(); dc_x++; } } R_FinishSetPatchStyle(); } -void R_WallSpriteColumn (bool useRt) +void R_WallSpriteColumn () { float iscale = swall[dc_x] * MaskedScaleY; dc_iscale = FLOAT2FIXED(iscale); @@ -635,20 +689,20 @@ void R_WallSpriteColumn (bool useRt) sprtopscreen = CenterY - dc_texturemid * spryscale; dc_texturefrac = 0; - R_DrawMaskedColumn(WallSpriteTile, lwall[dc_x], useRt); + R_DrawMaskedColumn(WallSpriteTile, lwall[dc_x]); rw_light += rw_lightstep; } +#if 0 void R_DrawVisVoxel(vissprite_t *spr, int minslabz, int maxslabz, short *cliptop, short *clipbot) { - ESPSResult mode; int flags = 0; // Do setup for blending. - R_SetColorMapLight(spr->Style.colormap, 0.0f, 0); - mode = R_SetPatchStyle(spr->Style.RenderStyle, spr->Style.Alpha, spr->Translation, spr->FillColor); + R_SetColorMapLight(spr->Style.BaseColormap, 0, spr->Style.ColormapNum << FRACBITS); + bool visible = R_SetPatchStyle(spr->Style.RenderStyle, spr->Style.Alpha, spr->Translation, spr->FillColor); - if (mode == DontDraw) + if (!visible) { return; } @@ -671,12 +725,13 @@ void R_DrawVisVoxel(vissprite_t *spr, int minslabz, int maxslabz, short *cliptop // Render the voxel, either directly to the screen or offscreen. R_DrawVoxel(spr->pa.vpos, spr->pa.vang, spr->gpos, spr->Angle, - spr->xscale, FLOAT2FIXED(spr->yscale), spr->voxel, spr->Style.colormap, cliptop, clipbot, + spr->xscale, FLOAT2FIXED(spr->yscale), spr->voxel, spr->Style.BaseColormap, spr->Style.ColormapNum, cliptop, clipbot, minslabz, maxslabz, flags); // Blend the voxel, if that's what we need to do. if ((flags & ~DVF_MIRRORED) != 0) { + int pixelsize = r_swtruecolor ? 4 : 1; for (int x = 0; x < viewwidth; ++x) { if (!(flags & DVF_SPANSONLY) && (x & 3) == 0) @@ -691,7 +746,7 @@ void R_DrawVisVoxel(vissprite_t *spr, int minslabz, int maxslabz, short *cliptop dc_yl = span->Start; dc_yh = span->Stop - 1; dc_count = span->Stop - span->Start; - dc_dest = ylookup[span->Start] + x + dc_destorg; + dc_dest = (ylookup[span->Start] + x) * pixelsize + dc_destorg; colfunc(); } else @@ -709,6 +764,7 @@ void R_DrawVisVoxel(vissprite_t *spr, int minslabz, int maxslabz, short *cliptop R_FinishSetPatchStyle(); NetUpdate(); } +#endif // // R_ProjectSprite @@ -1057,7 +1113,7 @@ void R_ProjectSprite (AActor *thing, int fakeside, F3DFloor *fakefloor, F3DFloor vis->Style.Alpha = float(thing->Alpha); vis->fakefloor = fakefloor; vis->fakeceiling = fakeceiling; - vis->ColormapNum = 0; + vis->Style.ColormapNum = 0; vis->bInMirror = MirrorFlags & RF_XFLIP; vis->bSplitSprite = false; @@ -1113,7 +1169,8 @@ void R_ProjectSprite (AActor *thing, int fakeside, F3DFloor *fakefloor, F3DFloor // get light level if (fixedcolormap != NULL) { // fixed map - vis->Style.colormap = fixedcolormap; + vis->Style.BaseColormap = fixedcolormap; + vis->Style.ColormapNum = 0; } else { @@ -1123,17 +1180,19 @@ void R_ProjectSprite (AActor *thing, int fakeside, F3DFloor *fakefloor, F3DFloor } if (fixedlightlev >= 0) { - vis->Style.colormap = mybasecolormap->Maps + fixedlightlev; + vis->Style.BaseColormap = mybasecolormap; + vis->Style.ColormapNum = fixedlightlev >> COLORMAPSHIFT; } else if (!foggy && ((renderflags & RF_FULLBRIGHT) || (thing->flags5 & MF5_BRIGHT))) { // full bright - vis->Style.colormap = (r_fullbrightignoresectorcolor) ? FullNormalLight.Maps : mybasecolormap->Maps; + vis->Style.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; + vis->Style.ColormapNum = 0; } else { // diminished light - vis->ColormapNum = GETPALOOKUP( + vis->Style.ColormapNum = GETPALOOKUP( r_SpriteVisibility / MAX(tz, MINZ), spriteshade); - vis->Style.colormap = mybasecolormap->Maps + (vis->ColormapNum << COLORMAPSHIFT); + vis->Style.BaseColormap = mybasecolormap; } } } @@ -1202,14 +1261,13 @@ static void R_ProjectWallSprite(AActor *thing, const DVector3 &pos, FTextureID p vis->Style.Alpha = float(thing->Alpha); vis->fakefloor = NULL; vis->fakeceiling = NULL; - vis->ColormapNum = 0; vis->bInMirror = MirrorFlags & RF_XFLIP; vis->pic = pic; vis->bIsVoxel = false; vis->bWallSprite = true; - vis->ColormapNum = GETPALOOKUP( + vis->Style.ColormapNum = GETPALOOKUP( r_SpriteVisibility / MAX(tz, MINZ), spriteshade); - vis->Style.colormap = basecolormap->Maps + (vis->ColormapNum << COLORMAPSHIFT); + vis->Style.BaseColormap = basecolormap; vis->wallc = wallc; } @@ -1393,7 +1451,7 @@ void R_DrawPSprite(DPSprite *pspr, AActor *owner, float bobx, float boby, double vis->yscale = float(pspriteyscale / tex->Scale.Y); vis->Translation = 0; // [RH] Use default colors vis->pic = tex; - vis->ColormapNum = 0; + vis->Style.ColormapNum = 0; // If flip is used, provided that it's not already flipped (that would just invert itself) // (It's an XOR...) @@ -1549,9 +1607,10 @@ void R_DrawPSprite(DPSprite *pspr, AActor *owner, float bobx, float boby, double } } - if (realfixedcolormap != nullptr) + if (realfixedcolormap != nullptr && (!r_swtruecolor || (r_shadercolormaps && screen->Accel2D))) { // fixed color - vis->Style.colormap = realfixedcolormap->Colormap; + vis->Style.BaseColormap = realfixedcolormap; + vis->Style.ColormapNum = 0; } else { @@ -1561,35 +1620,38 @@ void R_DrawPSprite(DPSprite *pspr, AActor *owner, float bobx, float boby, double } if (fixedlightlev >= 0) { - vis->Style.colormap = (r_fullbrightignoresectorcolor) ? (FullNormalLight.Maps + fixedlightlev) : (mybasecolormap->Maps + fixedlightlev); + vis->Style.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; + vis->Style.ColormapNum = fixedlightlev >> COLORMAPSHIFT; } else if (!foggy && pspr->GetState()->GetFullbright()) { // full bright - vis->Style.colormap = (r_fullbrightignoresectorcolor) ? FullNormalLight.Maps : mybasecolormap->Maps; // [RH] use basecolormap + vis->Style.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; // [RH] use basecolormap + vis->Style.ColormapNum = 0; } else { // local light - vis->Style.colormap = mybasecolormap->Maps + (GETPALOOKUP(0, spriteshade) << COLORMAPSHIFT); + vis->Style.BaseColormap = mybasecolormap; + vis->Style.ColormapNum = GETPALOOKUP(0, spriteshade); } } if (camera->Inventory != nullptr) { - lighttable_t *oldcolormap = vis->Style.colormap; - camera->Inventory->AlterWeaponSprite(&vis->Style); - if (vis->Style.colormap != oldcolormap) + BYTE oldcolormapnum = vis->Style.ColormapNum; + FSWColormap *oldcolormap = vis->Style.BaseColormap; + camera->Inventory->AlterWeaponSprite (&vis->Style); + if (vis->Style.BaseColormap != oldcolormap || vis->Style.ColormapNum != oldcolormapnum) { // The colormap has changed. Is it one we can easily identify? // If not, then don't bother trying to identify it for // hardware accelerated drawing. - if (vis->Style.colormap < SpecialColormaps[0].Colormap || - vis->Style.colormap > SpecialColormaps.Last().Colormap) + if (vis->Style.BaseColormap < &SpecialColormaps[0] || + vis->Style.BaseColormap > &SpecialColormaps.Last()) { noaccel = true; } // Has the basecolormap changed? If so, we can't hardware accelerate it, // since we don't know what it is anymore. - else if (vis->Style.colormap < mybasecolormap->Maps || - vis->Style.colormap >= mybasecolormap->Maps + NUMCOLORMAPS * 256) + else if (vis->Style.BaseColormap != mybasecolormap) { noaccel = true; } @@ -1597,13 +1659,13 @@ void R_DrawPSprite(DPSprite *pspr, AActor *owner, float bobx, float boby, double } // If we're drawing with a special colormap, but shaders for them are disabled, do // not accelerate. - if (!r_shadercolormaps && (vis->Style.colormap >= SpecialColormaps[0].Colormap && - vis->Style.colormap <= SpecialColormaps.Last().Colormap)) + if (!r_shadercolormaps && (vis->Style.BaseColormap >= &SpecialColormaps[0] && + vis->Style.BaseColormap <= &SpecialColormaps.Last())) { noaccel = true; } // If drawing with a BOOM colormap, disable acceleration. - if (mybasecolormap == &NormalLight && NormalLight.Maps != realcolormaps) + if (mybasecolormap == &NormalLight && NormalLight.Maps != realcolormaps.Maps) { noaccel = true; } @@ -1625,7 +1687,9 @@ void R_DrawPSprite(DPSprite *pspr, AActor *owner, float bobx, float boby, double else { colormap_to_use = basecolormap; - vis->Style.colormap = basecolormap->Maps; + + vis->Style.BaseColormap = basecolormap; + vis->Style.ColormapNum = 0; } // Check for hardware-assisted 2D. If it's available, and this sprite is not @@ -1797,18 +1861,16 @@ void R_DrawRemainingPlayerSprites() FColormapStyle colormapstyle; bool usecolormapstyle = false; - if (vis->Style.colormap >= SpecialColormaps[0].Colormap && - vis->Style.colormap < SpecialColormaps[SpecialColormaps.Size()].Colormap) + if (vis->Style.BaseColormap >= &SpecialColormaps[0] && + vis->Style.BaseColormap < &SpecialColormaps[SpecialColormaps.Size()]) { - // Yuck! There needs to be a better way to store colormaps in the vissprite... :( - ptrdiff_t specialmap = (vis->Style.colormap - SpecialColormaps[0].Colormap) / sizeof(FSpecialColormap); - special = &SpecialColormaps[specialmap]; + special = static_cast(vis->Style.BaseColormap); } else if (colormap->Color == PalEntry(255,255,255) && colormap->Desaturate == 0) { overlay = colormap->Fade; - overlay.a = BYTE(((vis->Style.colormap - colormap->Maps) >> 8) * 255 / NUMCOLORMAPS); + overlay.a = BYTE(vis->Style.ColormapNum * 255 / NUMCOLORMAPS); } else { @@ -1816,7 +1878,7 @@ void R_DrawRemainingPlayerSprites() colormapstyle.Color = colormap->Color; colormapstyle.Fade = colormap->Fade; colormapstyle.Desaturate = colormap->Desaturate; - colormapstyle.FadeLevel = ((vis->Style.colormap - colormap->Maps) >> 8) / float(NUMCOLORMAPS); + colormapstyle.FadeLevel = vis->Style.ColormapNum / float(NUMCOLORMAPS); } screen->DrawTexture(vis->pic, viewwindowx + vispsprites[i].x1, @@ -2059,7 +2121,8 @@ void R_DrawSprite (vissprite_t *spr) int r1, r2; short topclip, botclip; short *clip1, *clip2; - lighttable_t *colormap = spr->Style.colormap; + FSWColormap *colormap = spr->Style.BaseColormap; + int colormapnum = spr->Style.ColormapNum; F3DFloor *rover; FDynamicColormap *mybasecolormap; @@ -2156,17 +2219,19 @@ void R_DrawSprite (vissprite_t *spr) } if (fixedlightlev >= 0) { - spr->Style.colormap = mybasecolormap->Maps + fixedlightlev; + spr->Style.BaseColormap = mybasecolormap; + spr->Style.ColormapNum = fixedlightlev >> COLORMAPSHIFT; } else if (!foggy && (spr->renderflags & RF_FULLBRIGHT)) { // full bright - spr->Style.colormap = (r_fullbrightignoresectorcolor) ? FullNormalLight.Maps : mybasecolormap->Maps; + spr->Style.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : mybasecolormap; + spr->Style.ColormapNum = 0; } else { // diminished light spriteshade = LIGHT2SHADE(sec->lightlevel + r_actualextralight); - spr->Style.colormap = mybasecolormap->Maps + (GETPALOOKUP( - r_SpriteVisibility / MAX(MINZ, (double)spr->depth), spriteshade) << COLORMAPSHIFT); + spr->Style.BaseColormap = mybasecolormap; + spr->Style.ColormapNum = GETPALOOKUP(r_SpriteVisibility / MAX(MINZ, (double)spr->depth), spriteshade); } } } @@ -2314,7 +2379,8 @@ void R_DrawSprite (vissprite_t *spr) if (topclip >= botclip) { - spr->Style.colormap = colormap; + spr->Style.BaseColormap = colormap; + spr->Style.ColormapNum = colormapnum; return; } @@ -2444,7 +2510,8 @@ void R_DrawSprite (vissprite_t *spr) } if (i == x2) { - spr->Style.colormap = colormap; + spr->Style.BaseColormap = colormap; + spr->Style.ColormapNum = colormapnum; return; } } @@ -2462,7 +2529,8 @@ void R_DrawSprite (vissprite_t *spr) int maxvoxely = spr->gzb > hzb ? INT_MAX : xs_RoundToInt((spr->gzt - hzb) / spr->yscale); R_DrawVisVoxel(spr, minvoxely, maxvoxely, cliptop, clipbot); } - spr->Style.colormap = colormap; + spr->Style.BaseColormap = colormap; + spr->Style.ColormapNum = colormapnum; } // kg3D: @@ -2579,7 +2647,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, int x1, x2, y1, y2; vissprite_t* vis; sector_t* heightsec = NULL; - BYTE* map; + FSWColormap* map; // [ZZ] Particle not visible through the portal plane if (CurrentPortal && !!P_PointOnLineSide(particle->Pos, CurrentPortal->dst)) @@ -2619,7 +2687,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, if (x1 >= x2) return; - yscale = YaspectMul * xscale; + yscale = xscale; // YaspectMul is not needed for particles as they should always be square ty = particle->Pos.Z - ViewPos.Z; y1 = xs_RoundToInt(CenterY - (ty + psize) * yscale); y2 = xs_RoundToInt(CenterY - (ty - psize) * yscale); @@ -2652,7 +2720,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, botplane = &heightsec->ceilingplane; toppic = sector->GetTexture(sector_t::ceiling); botpic = heightsec->GetTexture(sector_t::ceiling); - map = heightsec->ColorMap->Maps; + map = heightsec->ColorMap; } else if (fakeside == FAKED_BelowFloor) { @@ -2660,7 +2728,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, botplane = §or->floorplane; toppic = heightsec->GetTexture(sector_t::floor); botpic = sector->GetTexture(sector_t::floor); - map = heightsec->ColorMap->Maps; + map = heightsec->ColorMap; } else { @@ -2668,7 +2736,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, botplane = &heightsec->floorplane; toppic = heightsec->GetTexture(sector_t::ceiling); botpic = heightsec->GetTexture(sector_t::floor); - map = sector->ColorMap->Maps; + map = sector->ColorMap; } } else @@ -2677,7 +2745,7 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, botplane = §or->floorplane; toppic = sector->GetTexture(sector_t::ceiling); botpic = sector->GetTexture(sector_t::floor); - map = sector->ColorMap->Maps; + map = sector->ColorMap; } if (botpic != skyflatnum && particle->Pos.Z < botplane->ZatPoint (particle->Pos)) @@ -2706,25 +2774,28 @@ void R_ProjectParticle (particle_t *particle, const sector_t *sector, int shade, vis->renderflags = particle->trans; vis->FakeFlatStat = fakeside; vis->floorclip = 0; - vis->ColormapNum = 0; + vis->Style.ColormapNum = 0; if (fixedlightlev >= 0) { - vis->Style.colormap = map + fixedlightlev; + vis->Style.BaseColormap = map; + vis->Style.ColormapNum = fixedlightlev >> COLORMAPSHIFT; } else if (fixedcolormap) { - vis->Style.colormap = fixedcolormap; + vis->Style.BaseColormap = fixedcolormap; + vis->Style.ColormapNum = 0; } else if (particle->bright) { - vis->Style.colormap = (r_fullbrightignoresectorcolor) ? FullNormalLight.Maps : map; + vis->Style.BaseColormap = (r_fullbrightignoresectorcolor) ? &FullNormalLight : map; + vis->Style.ColormapNum = 0; } else { // Particles are slightly more visible than regular sprites. - vis->ColormapNum = GETPALOOKUP(tiz * r_SpriteVisibility * 0.5, shade); - vis->Style.colormap = map + (vis->ColormapNum << COLORMAPSHIFT); + vis->Style.ColormapNum = GETPALOOKUP(tiz * r_SpriteVisibility * 0.5, shade); + vis->Style.BaseColormap = map; } } @@ -2753,69 +2824,51 @@ static void R_DrawMaskedSegsBehindParticle (const vissprite_t *vis) } } -void R_DrawParticle_C (vissprite_t *vis) +void R_DrawParticle(vissprite_t *vis) { - DWORD *bg2rgb; int spacing; - BYTE *dest; - DWORD fg; - BYTE color = vis->Style.colormap[vis->startfrac]; + BYTE color = vis->Style.BaseColormap->Maps[vis->startfrac]; int yl = vis->y1; int ycount = vis->y2 - yl + 1; int x1 = vis->x1; int countbase = vis->x2 - x1; - R_DrawMaskedSegsBehindParticle (vis); + if (ycount <= 0 || countbase <= 0) + return; - DrawerCommandQueue::WaitForWorkers(); + R_DrawMaskedSegsBehindParticle(vis); + + uint32_t fg = LightBgra::shade_pal_index_simple(color, LightBgra::calc_light_multiplier(LIGHTSCALE(0, vis->Style.ColormapNum << FRACBITS))); // vis->renderflags holds translucency level (0-255) - { - fixed_t fglevel, bglevel; - DWORD *fg2rgb; - - fglevel = ((vis->renderflags + 1) << 8) & ~0x3ff; - bglevel = FRACUNIT-fglevel; - fg2rgb = Col2RGB8[fglevel>>10]; - bg2rgb = Col2RGB8[bglevel>>10]; - fg = fg2rgb[color]; - } - - /* - - spacing = RenderTarget->GetPitch() - countbase; - dest = ylookup[yl] + x1 + dc_destorg; - - do - { - int count = countbase; - do - { - DWORD bg = bg2rgb[*dest]; - bg = (fg+bg) | 0x1f07c1f; - *dest++ = RGB32k.All[bg & (bg>>15)]; - } while (--count); - dest += spacing; - } while (--ycount);*/ - - // original was row-wise - // width = countbase - // height = ycount + fixed_t fglevel = ((vis->renderflags + 1) << 8) & ~0x3ff; + uint32_t alpha = fglevel * 256 / FRACUNIT; spacing = RenderTarget->GetPitch(); - for (int x = x1; x < (x1+countbase); x++) + uint32_t fracstepx = 16 * FRACUNIT / countbase; + uint32_t fracposx = fracstepx / 2; + + if (r_swtruecolor) { - dc_x = x; - if (R_ClipSpriteColumnWithPortals(vis)) - continue; - dest = ylookup[yl] + x + dc_destorg; - for (int y = 0; y < ycount; y++) + for (int x = x1; x < (x1 + countbase); x++, fracposx += fracstepx) { - DWORD bg = bg2rgb[*dest]; - bg = (fg+bg) | 0x1f07c1f; - *dest = RGB32k.All[bg & (bg>>15)]; - dest += spacing; + dc_x = x; + if (R_ClipSpriteColumnWithPortals(vis)) + continue; + uint32_t *dest = ylookup[yl] + x + (uint32_t*)dc_destorg; + DrawerCommandQueue::QueueCommand(dest, yl, spacing, ycount, fg, alpha, fracposx); + } + } + else + { + for (int x = x1; x < (x1 + countbase); x++, fracposx += fracstepx) + { + dc_x = x; + if (R_ClipSpriteColumnWithPortals(vis)) + continue; + uint8_t *dest = ylookup[yl] + x + dc_destorg; + DrawerCommandQueue::QueueCommand(dest, yl, spacing, ycount, fg, alpha, fracposx); } } } @@ -2827,10 +2880,11 @@ inline int sgn(int v) return v < 0 ? -1 : v > 0 ? 1 : 0; } +#if 0 void R_DrawVoxel(const FVector3 &globalpos, FAngle viewangle, const FVector3 &dasprpos, DAngle dasprang, fixed_t daxscale, fixed_t dayscale, FVoxel *voxobj, - lighttable_t *colormap, short *daumost, short *dadmost, int minslabz, int maxslabz, int flags) + FSWColormap *colormap, int colormapnum, short *daumost, short *dadmost, int minslabz, int maxslabz, int flags) { int i, j, k, x, y, syoff, ggxstart, ggystart, nxoff; fixed_t cosang, sinang, sprcosang, sprsinang; @@ -2872,7 +2926,9 @@ void R_DrawVoxel(const FVector3 &globalpos, FAngle viewangle, sprcosang = FLOAT2FIXED(dasprang.Cos()) >> 2; sprsinang = FLOAT2FIXED(-dasprang.Sin()) >> 2; - R_SetupDrawSlab(colormap); + R_SetupDrawSlab(colormap, 0.0f, colormapnum << FRACBITS); + + int pixelsize = r_swtruecolor ? 4 : 1; // Select mip level i = abs(DMulScale6(dasprx - globalposx, cosang, daspry - globalposy, sinang)); @@ -3127,7 +3183,7 @@ void R_DrawVoxel(const FVector3 &globalpos, FAngle viewangle, if (!(flags & DVF_OFFSCREEN)) { // Draw directly to the screen. - R_DrawSlab(xxr - xxl, yplc[xxl], z2 - z1, yinc, col, ylookup[z1] + lxt + xxl + dc_destorg); + R_DrawSlab(xxr - xxl, yplc[xxl], z2 - z1, yinc, col, (ylookup[z1] + lxt + xxl) * pixelsize + dc_destorg); } else { @@ -3144,6 +3200,7 @@ void R_DrawVoxel(const FVector3 &globalpos, FAngle viewangle, dc_x = lxt + x; rt_initcols(OffscreenColorBuffer + (dc_x & ~3) * OffscreenBufferHeight); dc_source = col; + dc_source2 = nullptr; dc_texturefrac = yplc[xxl]; hcolfunc_pre(); } @@ -3157,6 +3214,7 @@ void R_DrawVoxel(const FVector3 &globalpos, FAngle viewangle, } } } +#endif //========================================================================== // @@ -3358,12 +3416,12 @@ void R_CheckOffscreenBuffer(int width, int height, bool spansonly) { if (OffscreenColorBuffer == NULL) { - OffscreenColorBuffer = new BYTE[width * height]; + OffscreenColorBuffer = new BYTE[width * height * 4]; } else if (OffscreenBufferWidth != width || OffscreenBufferHeight != height) { delete[] OffscreenColorBuffer; - OffscreenColorBuffer = new BYTE[width * height]; + OffscreenColorBuffer = new BYTE[width * height * 4]; } } OffscreenBufferWidth = width; diff --git a/src/r_things.h b/src/r_things.h index 6d694b8fd..7f00ce177 100644 --- a/src/r_things.h +++ b/src/r_things.h @@ -92,7 +92,6 @@ struct vissprite_t BYTE bSplitSprite:1; // [RH] Sprite was split by a drawseg BYTE bInMirror:1; // [RH] Sprite is "inside" a mirror BYTE FakeFlatStat; // [RH] which side of fake/floor ceiling sprite is on - BYTE ColormapNum; // Which colormap is rendered (needed for shaded drawer) short renderflags; DWORD Translation; // [RH] for color translation visstyle_t Style; @@ -101,7 +100,8 @@ struct vissprite_t vissprite_t() {} }; -void R_DrawParticle_C (vissprite_t *); +void R_DrawParticle (vissprite_t *); + void R_ProjectParticle (particle_t *, const sector_t *sector, int shade, int fakeside); extern int MaxVisSprites; @@ -128,8 +128,8 @@ extern double pspriteyscale; extern FTexture *WallSpriteTile; -void R_DrawMaskedColumn (FTexture *texture, fixed_t column, bool useRt, bool unmasked = false); -void R_WallSpriteColumn (bool useRt); +void R_DrawMaskedColumn (FTexture *texture, fixed_t column, bool unmasked = false); +void R_WallSpriteColumn (); void R_CacheSprite (spritedef_t *sprite); void R_SortVisSprites (int (*compare)(const void *, const void *), size_t first); @@ -143,11 +143,6 @@ void R_CheckOffscreenBuffer(int width, int height, bool spansonly); enum { DVF_OFFSCREEN = 1, DVF_SPANSONLY = 2, DVF_MIRRORED = 4 }; -void R_DrawVoxel(const FVector3 &viewpos, FAngle viewangle, - const FVector3 &sprpos, DAngle dasprang, - fixed_t daxscale, fixed_t dayscale, struct FVoxel *voxobj, - lighttable_t *colormap, short *daumost, short *dadmost, int minslabz, int maxslabz, int flags); - void R_ClipVisSprite (vissprite_t *vis, int xl, int xh); } diff --git a/src/r_thread.cpp b/src/r_thread.cpp index c96f14e74..bbb3faf3f 100644 --- a/src/r_thread.cpp +++ b/src/r_thread.cpp @@ -291,7 +291,11 @@ void DrawerCommandQueue::ReportDrawerError(DrawerCommand *command, bool worker_t } } +#ifndef WIN32 + void VectoredTryCatch(void *data, void(*tryBlock)(void *data), void(*catchBlock)(void *data, const char *reason, bool fatal)) { tryBlock(data); } + +#endif diff --git a/src/r_thread.h b/src/r_thread.h index e44d872c2..c3e818abb 100644 --- a/src/r_thread.h +++ b/src/r_thread.h @@ -23,6 +23,7 @@ #pragma once #include "r_draw.h" +#include "r_drawers.h" #include #include #include @@ -44,8 +45,8 @@ class DrawerThread public: DrawerThread() { - dc_temp = dc_temp_buff; - dc_temp_rgba = dc_temp_rgbabuff_rgba; + FullSpansBuffer.resize(MAXWIDTH / 8 * (MAXHEIGHT / 8)); + PartialBlocksBuffer.resize(MAXWIDTH / 8 * (MAXHEIGHT / 8)); } std::thread thread; @@ -60,17 +61,13 @@ public: int pass_start_y = 0; int pass_end_y = MAXHEIGHT; - // Working buffer used by Rt drawers - uint8_t dc_temp_buff[MAXHEIGHT * 4]; - uint8_t *dc_temp = nullptr; - - // Working buffer used by Rt drawers, true color edition - uint32_t dc_temp_rgbabuff_rgba[MAXHEIGHT * 4]; - uint32_t *dc_temp_rgba = nullptr; - // Working buffer used by the tilted (sloped) span drawer const uint8_t *tiltlighting[MAXWIDTH]; + // Working buffer used by the triangler drawer + std::vector FullSpansBuffer; + std::vector PartialBlocksBuffer; + // Checks if a line is rendered by this thread bool line_skipped_by_thread(int line) { @@ -141,7 +138,10 @@ protected: public: DrawerCommand() { - _dest_y = static_cast((swrenderer::drawerargs::dc_dest - swrenderer::drawerargs::dc_destorg) / (swrenderer::drawerargs::dc_pitch)); + if (swrenderer::r_swtruecolor) + _dest_y = static_cast((swrenderer::drawerargs::dc_dest - swrenderer::drawerargs::dc_destorg) / (swrenderer::drawerargs::dc_pitch * 4)); + else + _dest_y = static_cast((swrenderer::drawerargs::dc_dest - swrenderer::drawerargs::dc_destorg) / (swrenderer::drawerargs::dc_pitch)); } virtual ~DrawerCommand() { } diff --git a/src/r_utility.cpp b/src/r_utility.cpp index 158834929..da4108df8 100644 --- a/src/r_utility.cpp +++ b/src/r_utility.cpp @@ -896,11 +896,11 @@ void R_SetupFrame (AActor *actor) BaseBlendG = GPART(newblend); BaseBlendB = BPART(newblend); BaseBlendA = APART(newblend) / 255.f; - NormalLight.Maps = realcolormaps; + NormalLight.Maps = realcolormaps.Maps; } else { - NormalLight.Maps = realcolormaps + NUMCOLORMAPS*256*newblend; + NormalLight.Maps = realcolormaps.Maps + NUMCOLORMAPS*256*newblend; BaseBlendR = BaseBlendG = BaseBlendB = 0; BaseBlendA = 0.f; } diff --git a/src/r_voxel.cpp b/src/r_voxel.cpp new file mode 100644 index 000000000..0f81124c7 --- /dev/null +++ b/src/r_voxel.cpp @@ -0,0 +1,217 @@ +/* +** Voxel rendering +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include +#include "templates.h" +#include "doomdef.h" +#include "sbar.h" +#include "r_data/r_translate.h" +#include "r_data/colormaps.h" +#include "r_data/voxels.h" +#include "r_data/sprites.h" +#include "d_net.h" +#include "po_man.h" +#include "r_things.h" +#include "r_draw.h" +#include "r_thread.h" +#include "r_utility.h" +#include "r_main.h" +#include "r_voxel.h" + +namespace swrenderer +{ + void R_DrawVisVoxel(vissprite_t *sprite, int minZ, int maxZ, short *cliptop, short *clipbottom) + { + R_SetColorMapLight(sprite->Style.BaseColormap, 0, sprite->Style.ColormapNum << FRACBITS); + bool visible = R_SetPatchStyle(sprite->Style.RenderStyle, sprite->Style.Alpha, sprite->Translation, sprite->FillColor); + if (!visible) + return; + + DVector3 view_origin = { sprite->pa.vpos.X, sprite->pa.vpos.Y, sprite->pa.vpos.Z }; + FAngle view_angle = sprite->pa.vang; + DVector3 sprite_origin = { sprite->gpos.X, sprite->gpos.Y, sprite->gpos.Z }; + DAngle sprite_angle = sprite->Angle; + double sprite_xscale = FIXED2DBL(sprite->xscale); + double sprite_yscale = sprite->yscale; + FVoxel *voxel = sprite->voxel; + + // Select mipmap level: + + double viewSin = view_angle.Cos(); + double viewCos = view_angle.Sin(); + double logmip = fabs((view_origin.X - sprite_origin.X) * viewCos - (view_origin.Y - sprite_origin.Y) * viewSin); + int miplevel = 0; + while (miplevel < voxel->NumMips - 1 && logmip >= FocalLengthX) + { + logmip *= 0.5; + miplevel++; + } + + const FVoxelMipLevel &mip = voxel->Mips[miplevel]; + if (mip.SlabData == nullptr) + return; + + minZ >>= miplevel; + maxZ >>= miplevel; + sprite_xscale *= (1 << miplevel); + sprite_yscale *= (1 << miplevel); + + // Find voxel cube eigenvectors and origin in world space: + + double spriteSin = sprite_angle.Sin(); + double spriteCos = sprite_angle.Cos(); + + DVector2 dirX(spriteSin * sprite_xscale, -spriteCos * sprite_xscale); + DVector2 dirY(spriteCos * sprite_xscale, spriteSin * sprite_xscale); + float dirZ = -sprite_yscale; + + DVector3 voxel_origin = sprite_origin; + voxel_origin.X -= dirX.X * mip.Pivot.X + dirX.Y * mip.Pivot.Y; + voxel_origin.Y -= dirY.X * mip.Pivot.X + dirY.Y * mip.Pivot.Y; + voxel_origin.Z -= dirZ * mip.Pivot.Z; + + // Voxel cube walking directions: + + int startX[4] = { 0, mip.SizeX - 1, 0, mip.SizeX - 1 }; + int startY[4] = { 0, 0, mip.SizeY - 1, mip.SizeY - 1 }; + int stepX[4] = { 1, -1, 1, -1 }; + int stepY[4] = { 1, 1, -1, -1 }; + + // The point in cube mipmap local space where voxel sides change from front to backfacing: + + double dx = (view_origin.X - sprite_origin.X) / sprite_xscale; + double dy = (view_origin.Y - sprite_origin.Y) / sprite_xscale; + int backX = (int)(dx * spriteCos - dy * spriteSin + mip.Pivot.X); + int backY = (int)(dy * spriteCos + dx * spriteSin + mip.Pivot.Y); + int endX = clamp(backX, 0, mip.SizeX - 1); + int endY = clamp(backY, 0, mip.SizeY - 1); + + // Draw the voxel cube: + + for (int index = 0; index < 4; index++) + { + if ((stepX[index] < 0 && endX >= startX[index]) || + (stepX[index] > 0 && endX <= startX[index]) || + (stepY[index] < 0 && endY >= startY[index]) || + (stepY[index] > 0 && endY <= startY[index])) continue; + + for (int x = startX[index]; x != endX; x += stepX[index]) + { + for (int y = startY[index]; y != endY; y += stepY[index]) + { + kvxslab_t *slab_start = R_GetSlabStart(mip, x, y); + kvxslab_t *slab_end = R_GetSlabEnd(mip, x, y); + + for (kvxslab_t *slab = slab_start; slab != slab_end; slab = R_NextSlab(slab)) + { + // To do: check slab->backfacecull + + int ztop = slab->ztop; + int zbottom = ztop + slab->zleng; + + //ztop = MAX(ztop, minZ); + //zbottom = MIN(zbottom, maxZ); + + for (int z = ztop; z < zbottom; z++) + { + uint8_t color = slab->col[z - slab->ztop]; + + DVector3 voxel_pos = voxel_origin; + voxel_pos.X += dirX.X * x + dirX.Y * y; + voxel_pos.Y += dirY.X * x + dirY.Y * y; + voxel_pos.Z += dirZ * z; + + R_FillBox(voxel_pos, sprite_xscale, sprite_yscale, color, cliptop, clipbottom, false, false); + } + } + } + } + } + } + + kvxslab_t *R_GetSlabStart(const FVoxelMipLevel &mip, int x, int y) + { + return (kvxslab_t *)&mip.SlabData[mip.OffsetX[x] + (int)mip.OffsetXY[x * (mip.SizeY + 1) + y]]; + } + + kvxslab_t *R_GetSlabEnd(const FVoxelMipLevel &mip, int x, int y) + { + return R_GetSlabStart(mip, x, y + 1); + } + + kvxslab_t *R_NextSlab(kvxslab_t *slab) + { + return (kvxslab_t*)(((uint8_t*)slab) + 3 + slab->zleng); + } + + void R_FillBox(DVector3 origin, double extentX, double extentY, int color, short *cliptop, short *clipbottom, bool viewspace, bool pixelstretch) + { + double viewX, viewY, viewZ; + if (viewspace) + { + viewX = origin.X; + viewY = origin.Y; + viewZ = origin.Z; + } + else // world space + { + double translatedX = origin.X - ViewPos.X; + double translatedY = origin.Y - ViewPos.Y; + double translatedZ = origin.Z - ViewPos.Z; + viewX = translatedX * ViewSin - translatedY * ViewCos; + viewY = translatedZ; + viewZ = translatedX * ViewTanCos + translatedY * ViewTanSin; + } + + if (viewZ < 0.01f) + return; + + double screenX = CenterX + viewX / viewZ * CenterX; + double screenY = CenterY - viewY / viewZ * InvZtoScale; + double screenExtentX = extentX / viewZ * CenterX; + double screenExtentY = pixelstretch ? screenExtentX * YaspectMul : screenExtentX; + + int x1 = MAX((int)(screenX - screenExtentX), 0); + int x2 = MIN((int)(screenX + screenExtentX + 0.5f), viewwidth - 1); + int y1 = MAX((int)(screenY - screenExtentY), 0); + int y2 = MIN((int)(screenY + screenExtentY + 0.5f), viewheight - 1); + + int pixelsize = r_swtruecolor ? 4 : 1; + + if (y1 < y2) + { + for (int x = x1; x < x2; x++) + { + int columnY1 = MAX(y1, (int)cliptop[x]); + int columnY2 = MIN(y2, (int)clipbottom[x]); + if (columnY1 < columnY2) + { + using namespace drawerargs; + dc_dest = dc_destorg + (dc_pitch * columnY1 + x) * pixelsize; + dc_color = color; + dc_count = columnY2 - columnY1; + R_FillColumn(); + } + } + } + } +} diff --git a/src/r_voxel.h b/src/r_voxel.h new file mode 100644 index 000000000..4c1e3f0af --- /dev/null +++ b/src/r_voxel.h @@ -0,0 +1,36 @@ +/* +** Voxel rendering +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +struct kvxslab_t; + +namespace swrenderer +{ + struct vissprite_t; + + void R_DrawVisVoxel(vissprite_t *sprite, int minZ, int maxZ, short *cliptop, short *clipbottom); + void R_FillBox(DVector3 origin, double extentX, double extentY, int color, short *cliptop, short *clipbottom, bool viewspace, bool pixelstretch); + kvxslab_t *R_GetSlabStart(const FVoxelMipLevel &mip, int x, int y); + kvxslab_t *R_GetSlabEnd(const FVoxelMipLevel &mip, int x, int y); + kvxslab_t *R_NextSlab(kvxslab_t *slab); +} diff --git a/src/r_walldraw.cpp b/src/r_walldraw.cpp index c13786bba..7e4f3f515 100644 --- a/src/r_walldraw.cpp +++ b/src/r_walldraw.cpp @@ -42,6 +42,8 @@ #include "r_3dfloors.h" #include "v_palette.h" #include "r_data/colormaps.h" +#include "gl/dynlights/gl_dynlight.h" +#include "r_drawers.h" namespace swrenderer { @@ -50,6 +52,8 @@ namespace swrenderer extern FTexture *rw_pic; extern int wallshade; +#if 0 // ZDoom version + struct WallSampler { WallSampler() { } @@ -393,6 +397,605 @@ static void ProcessTranslucentWall(int x1, int x2, short *uwal, short *dwal, flo } } +#else // QZDoom version + +struct WallSampler +{ + WallSampler() { } + WallSampler(int y1, float swal, double yrepeat, fixed_t xoffset, double xmagnitude, FTexture *texture, const BYTE*(*getcol)(FTexture *texture, int x)); + + uint32_t uv_pos; + uint32_t uv_step; + uint32_t uv_max; + + const BYTE *source; + const BYTE *source2; + uint32_t texturefracx; + uint32_t height; +}; + +WallSampler::WallSampler(int y1, float swal, double yrepeat, fixed_t xoffset, double xmagnitude, FTexture *texture, const BYTE*(*getcol)(FTexture *texture, int x)) +{ + xoffset += FLOAT2FIXED(xmagnitude * 0.5); + + if (!r_swtruecolor) + { + height = texture->GetHeight(); + + int uv_fracbits = 32 - texture->HeightBits; + if (uv_fracbits != 32) + { + uv_max = height << uv_fracbits; + + // Find start uv in [0-base_height[ range. + // Not using xs_ToFixed because it rounds the result and we need something that always rounds down to stay within the range. + double uv_stepd = swal * yrepeat; + double v = (dc_texturemid + uv_stepd * (y1 - CenterY + 0.5)) / height; + v = v - floor(v); + v *= height; + v *= (1 << uv_fracbits); + + uv_pos = (uint32_t)v; + uv_step = xs_ToFixed(uv_fracbits, uv_stepd); + if (uv_step == 0) // To prevent divide by zero elsewhere + uv_step = 1; + } + else + { // Hack for one pixel tall textures + uv_pos = 0; + uv_step = 0; + uv_max = 1; + } + + source = getcol(texture, xoffset >> FRACBITS); + source2 = nullptr; + texturefracx = 0; + } + else + { + // Normalize to 0-1 range: + double uv_stepd = swal * yrepeat; + double v = (dc_texturemid + uv_stepd * (y1 - CenterY + 0.5)) / texture->GetHeight(); + v = v - floor(v); + double v_step = uv_stepd / texture->GetHeight(); + + if (isnan(v) || isnan(v_step)) // this should never happen, but it apparently does.. + { + uv_stepd = 0.0; + v = 0.0; + v_step = 0.0; + } + + // Convert to uint32: + uv_pos = (uint32_t)(v * 0x100000000LL); + uv_step = (uint32_t)(v_step * 0x100000000LL); + uv_max = 0; + + // Texture mipmap and filter selection: + if (getcol != R_GetColumn) + { + source = getcol(texture, xoffset >> FRACBITS); + source2 = nullptr; + height = texture->GetHeight(); + texturefracx = 0; + } + else + { + double ymagnitude = fabs(uv_stepd); + double magnitude = MAX(ymagnitude, xmagnitude); + double min_lod = -1000.0; + double lod = MAX(log2(magnitude) + r_lod_bias, min_lod); + bool magnifying = lod < 0.0f; + + int mipmap_offset = 0; + int mip_width = texture->GetWidth(); + int mip_height = texture->GetHeight(); + if (r_mipmap && texture->Mipmapped() && mip_width > 1 && mip_height > 1) + { + uint32_t xpos = (uint32_t)((((uint64_t)xoffset) << FRACBITS) / mip_width); + + int level = (int)lod; + while (level > 0 && mip_width > 1 && mip_height > 1) + { + mipmap_offset += mip_width * mip_height; + level--; + mip_width = MAX(mip_width >> 1, 1); + mip_height = MAX(mip_height >> 1, 1); + } + xoffset = (xpos >> FRACBITS) * mip_width; + } + + const uint32_t *pixels = texture->GetPixelsBgra() + mipmap_offset; + + bool filter_nearest = (magnifying && !r_magfilter) || (!magnifying && !r_minfilter); + if (filter_nearest) + { + int tx = (xoffset >> FRACBITS) % mip_width; + if (tx < 0) + tx += mip_width; + source = (BYTE*)(pixels + tx * mip_height); + source2 = nullptr; + height = mip_height; + texturefracx = 0; + } + else + { + xoffset -= FRACUNIT / 2; + int tx0 = (xoffset >> FRACBITS) % mip_width; + if (tx0 < 0) + tx0 += mip_width; + int tx1 = (tx0 + 1) % mip_width; + source = (BYTE*)(pixels + tx0 * mip_height); + source2 = (BYTE*)(pixels + tx1 * mip_height); + height = mip_height; + texturefracx = (xoffset >> (FRACBITS - 4)) & 15; + } + } + } +} + +// Draw a column with support for non-power-of-two ranges +static void Draw1Column(int x, int y1, int y2, WallSampler &sampler, void(*draw1column)()) +{ + if (r_dynlights) + { + // Find column position in view space + float w1 = 1.0f / WallC.sz1; + float w2 = 1.0f / WallC.sz2; + float t = (x - WallC.sx1 + 0.5f) / (WallC.sx2 - WallC.sx1); + float wcol = w1 * (1.0f - t) + w2 * t; + float zcol = 1.0f / wcol; + dc_viewpos.X = (float)((x + 0.5 - CenterX) / CenterX * zcol); + dc_viewpos.Y = zcol; + dc_viewpos.Z = (float)((CenterY - y1 - 0.5) / InvZtoScale * zcol); + dc_viewpos_step.Z = (float)(-zcol / InvZtoScale); + + static TriLight lightbuffer[64 * 1024]; + static int nextlightindex = 0; + + // Setup lights for column + dc_num_lights = 0; + dc_lights = lightbuffer + nextlightindex; + FLightNode *cur_node = dc_light_list; + while (cur_node && nextlightindex < 64 * 1024) + { + if (!(cur_node->lightsource->flags2&MF2_DORMANT)) + { + double lightX = cur_node->lightsource->X() - ViewPos.X; + double lightY = cur_node->lightsource->Y() - ViewPos.Y; + double lightZ = cur_node->lightsource->Z() - ViewPos.Z; + + float lx = (float)(lightX * ViewSin - lightY * ViewCos) - dc_viewpos.X; + float ly = (float)(lightX * ViewTanCos + lightY * ViewTanSin) - dc_viewpos.Y; + float lz = (float)lightZ; + + // Precalculate the constant part of the dot here so the drawer doesn't have to. + float lconstant = lx * lx + ly * ly; + + // Include light only if it touches this column + float radius = cur_node->lightsource->GetRadius(); + if (radius * radius >= lconstant) + { + uint32_t red = cur_node->lightsource->GetRed(); + uint32_t green = cur_node->lightsource->GetGreen(); + uint32_t blue = cur_node->lightsource->GetBlue(); + + nextlightindex++; + auto &light = dc_lights[dc_num_lights++]; + light.x = lconstant; + light.z = lz; + light.radius = 256.0f / cur_node->lightsource->GetRadius(); + light.color = (red << 16) | (green << 8) | blue; + } + } + + cur_node = cur_node->nextLight; + } + + if (nextlightindex == 64 * 1024) + nextlightindex = 0; + } + else + { + dc_num_lights = 0; + } + + if (r_swtruecolor) + { + int count = y2 - y1; + + dc_source = sampler.source; + dc_source2 = sampler.source2; + dc_texturefracx = sampler.texturefracx; + dc_dest = (ylookup[y1] + x) * 4 + dc_destorg; + dc_count = count; + dc_iscale = sampler.uv_step; + dc_texturefrac = sampler.uv_pos; + dc_textureheight = sampler.height; + draw1column(); + + uint64_t step64 = sampler.uv_step; + uint64_t pos64 = sampler.uv_pos; + sampler.uv_pos = (uint32_t)(pos64 + step64 * count); + } + else + { + if (sampler.uv_max == 0 || sampler.uv_step == 0) // power of two + { + int count = y2 - y1; + + dc_source = sampler.source; + dc_source2 = sampler.source2; + dc_texturefracx = sampler.texturefracx; + dc_dest = (ylookup[y1] + x) + dc_destorg; + dc_count = count; + dc_iscale = sampler.uv_step; + dc_texturefrac = sampler.uv_pos; + draw1column(); + + uint64_t step64 = sampler.uv_step; + uint64_t pos64 = sampler.uv_pos; + sampler.uv_pos = (uint32_t)(pos64 + step64 * count); + } + else + { + uint32_t uv_pos = sampler.uv_pos; + + uint32_t left = y2 - y1; + while (left > 0) + { + uint32_t available = sampler.uv_max - uv_pos; + uint32_t next_uv_wrap = available / sampler.uv_step; + if (available % sampler.uv_step != 0) + next_uv_wrap++; + uint32_t count = MIN(left, next_uv_wrap); + + dc_source = sampler.source; + dc_source2 = sampler.source2; + dc_texturefracx = sampler.texturefracx; + dc_dest = (ylookup[y1] + x) + dc_destorg; + dc_count = count; + dc_iscale = sampler.uv_step; + dc_texturefrac = uv_pos; + draw1column(); + + left -= count; + uv_pos += sampler.uv_step * count; + if (uv_pos >= sampler.uv_max) + uv_pos -= sampler.uv_max; + } + + sampler.uv_pos = uv_pos; + } + } +} + +// Draw four columns with support for non-power-of-two ranges +static void Draw4Columns(int x, int y1, int y2, WallSampler *sampler, void(*draw4columns)()) +{ + if (r_swtruecolor) + { + int count = y2 - y1; + for (int i = 0; i < 4; i++) + { + dc_wall_source[i] = sampler[i].source; + dc_wall_source2[i] = sampler[i].source2; + dc_wall_texturefracx[i] = sampler[i].texturefracx; + dc_wall_sourceheight[i] = sampler[i].height; + dc_wall_texturefrac[i] = sampler[i].uv_pos; + dc_wall_iscale[i] = sampler[i].uv_step; + + uint64_t step64 = sampler[i].uv_step; + uint64_t pos64 = sampler[i].uv_pos; + sampler[i].uv_pos = (uint32_t)(pos64 + step64 * count); + } + dc_dest = (ylookup[y1] + x) * 4 + dc_destorg; + dc_count = count; + draw4columns(); + } + else + { + if (sampler[0].uv_max == 0 || sampler[0].uv_step == 0) // power of two, no wrap handling needed + { + int count = y2 - y1; + for (int i = 0; i < 4; i++) + { + dc_wall_source[i] = sampler[i].source; + dc_wall_source2[i] = sampler[i].source2; + dc_wall_texturefracx[i] = sampler[i].texturefracx; + dc_wall_texturefrac[i] = sampler[i].uv_pos; + dc_wall_iscale[i] = sampler[i].uv_step; + + uint64_t step64 = sampler[i].uv_step; + uint64_t pos64 = sampler[i].uv_pos; + sampler[i].uv_pos = (uint32_t)(pos64 + step64 * count); + } + dc_dest = (ylookup[y1] + x) + dc_destorg; + dc_count = count; + draw4columns(); + } + else + { + dc_dest = (ylookup[y1] + x) + dc_destorg; + for (int i = 0; i < 4; i++) + { + dc_wall_source[i] = sampler[i].source; + dc_wall_source2[i] = sampler[i].source2; + dc_wall_texturefracx[i] = sampler[i].texturefracx; + } + + uint32_t left = y2 - y1; + while (left > 0) + { + // Find which column wraps first + uint32_t count = left; + for (int i = 0; i < 4; i++) + { + uint32_t available = sampler[i].uv_max - sampler[i].uv_pos; + uint32_t next_uv_wrap = available / sampler[i].uv_step; + if (available % sampler[i].uv_step != 0) + next_uv_wrap++; + count = MIN(next_uv_wrap, count); + } + + // Draw until that column wraps + for (int i = 0; i < 4; i++) + { + dc_wall_texturefrac[i] = sampler[i].uv_pos; + dc_wall_iscale[i] = sampler[i].uv_step; + } + dc_count = count; + draw4columns(); + + // Wrap the uv position + for (int i = 0; i < 4; i++) + { + sampler[i].uv_pos += sampler[i].uv_step * count; + if (sampler[i].uv_pos >= sampler[i].uv_max) + sampler[i].uv_pos -= sampler[i].uv_max; + } + + left -= count; + } + } + } +} + +typedef void(*DrawColumnFuncPtr)(); + +static void ProcessWallWorker( + int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat, + const BYTE *(*getcol)(FTexture *tex, int x), DrawColumnFuncPtr draw1column, DrawColumnFuncPtr draw4columns) +{ + if (rw_pic->UseType == FTexture::TEX_Null) + return; + + fixed_t xoffset = rw_offset; + + rw_pic->GetHeight(); // To ensure that rw_pic->HeightBits has been set + int fracbits = 32 - rw_pic->HeightBits; + if (fracbits == 32) + { // Hack for one pixel tall textures + fracbits = 0; + yrepeat = 0; + dc_texturemid = 0; + } + + dc_wall_fracbits = r_swtruecolor ? FRACBITS : fracbits; + + bool fixed = (fixedcolormap != NULL || fixedlightlev >= 0); + if (fixed) + { + dc_wall_colormap[0] = dc_colormap; + dc_wall_colormap[1] = dc_colormap; + dc_wall_colormap[2] = dc_colormap; + dc_wall_colormap[3] = dc_colormap; + dc_wall_light[0] = 0; + dc_wall_light[1] = 0; + dc_wall_light[2] = 0; + dc_wall_light[3] = 0; + } + + if (fixedcolormap) + R_SetColorMapLight(fixedcolormap, 0, 0); + else + R_SetColorMapLight(basecolormap, 0, 0); + + float light = rw_light; + + double xmagnitude = 1.0; + + if (r_dynlights) + { + for (int x = x1; x < x2; x++, light += rw_lightstep) + { + int y1 = uwal[x]; + int y2 = dwal[x]; + if (y2 <= y1) + continue; + + if (!fixed) + R_SetColorMapLight(basecolormap, light, wallshade); + + if (x + 1 < x2) xmagnitude = fabs(FIXED2DBL(lwal[x + 1]) - FIXED2DBL(lwal[x])); + + WallSampler sampler(y1, swal[x], yrepeat, lwal[x] + xoffset, xmagnitude, rw_pic, getcol); + Draw1Column(x, y1, y2, sampler, draw1column); + } + NetUpdate(); + return; + } + + // Calculate where 4 column alignment begins and ends: + int aligned_x1 = clamp((x1 + 3) / 4 * 4, x1, x2); + int aligned_x2 = clamp(x2 / 4 * 4, x1, x2); + + // First unaligned columns: + for (int x = x1; x < aligned_x1; x++, light += rw_lightstep) + { + int y1 = uwal[x]; + int y2 = dwal[x]; + if (y2 <= y1) + continue; + + if (!fixed) + R_SetColorMapLight(basecolormap, light, wallshade); + + if (x + 1 < x2) xmagnitude = fabs(FIXED2DBL(lwal[x + 1]) - FIXED2DBL(lwal[x])); + + WallSampler sampler(y1, swal[x], yrepeat, lwal[x] + xoffset, xmagnitude, rw_pic, getcol); + Draw1Column(x, y1, y2, sampler, draw1column); + } + + // The aligned columns + for (int x = aligned_x1; x < aligned_x2; x += 4) + { + // Find y1, y2, light and uv values for four columns: + int y1[4] = { uwal[x], uwal[x + 1], uwal[x + 2], uwal[x + 3] }; + int y2[4] = { dwal[x], dwal[x + 1], dwal[x + 2], dwal[x + 3] }; + + float lights[4]; + for (int i = 0; i < 4; i++) + { + lights[i] = light; + light += rw_lightstep; + } + + WallSampler sampler[4]; + for (int i = 0; i < 4; i++) + { + if (x + i + 1 < x2) xmagnitude = fabs(FIXED2DBL(lwal[x + i + 1]) - FIXED2DBL(lwal[x + i])); + sampler[i] = WallSampler(y1[i], swal[x + i], yrepeat, lwal[x + i] + xoffset, xmagnitude, rw_pic, getcol); + } + + // Figure out where we vertically can start and stop drawing 4 columns in one go + int middle_y1 = y1[0]; + int middle_y2 = y2[0]; + for (int i = 1; i < 4; i++) + { + middle_y1 = MAX(y1[i], middle_y1); + middle_y2 = MIN(y2[i], middle_y2); + } + + // If we got an empty column in our set we cannot draw 4 columns in one go: + bool empty_column_in_set = false; + int bilinear_count = 0; + for (int i = 0; i < 4; i++) + { + if (y2[i] <= y1[i]) + empty_column_in_set = true; + if (sampler[i].source2) + bilinear_count++; + } + + if (empty_column_in_set || middle_y2 <= middle_y1 || (bilinear_count > 0 && bilinear_count < 4)) + { + for (int i = 0; i < 4; i++) + { + if (y2[i] <= y1[i]) + continue; + + if (!fixed) + R_SetColorMapLight(basecolormap, lights[i], wallshade); + Draw1Column(x + i, y1[i], y2[i], sampler[i], draw1column); + } + continue; + } + + // Draw the first rows where not all 4 columns are active + for (int i = 0; i < 4; i++) + { + if (!fixed) + R_SetColorMapLight(basecolormap, lights[i], wallshade); + + if (y1[i] < middle_y1) + Draw1Column(x + i, y1[i], middle_y1, sampler[i], draw1column); + } + + // Draw the area where all 4 columns are active + if (!fixed) + { + for (int i = 0; i < 4; i++) + { + if (r_swtruecolor) + { + dc_wall_colormap[i] = basecolormap->Maps; + dc_wall_light[i] = LIGHTSCALE(lights[i], wallshade); + } + else + { + dc_wall_colormap[i] = basecolormap->Maps + (GETPALOOKUP(lights[i], wallshade) << COLORMAPSHIFT); + dc_wall_light[i] = 0; + } + } + } + Draw4Columns(x, middle_y1, middle_y2, sampler, draw4columns); + + // Draw the last rows where not all 4 columns are active + for (int i = 0; i < 4; i++) + { + if (!fixed) + R_SetColorMapLight(basecolormap, lights[i], wallshade); + + if (middle_y2 < y2[i]) + Draw1Column(x + i, middle_y2, y2[i], sampler[i], draw1column); + } + } + + // The last unaligned columns: + for (int x = aligned_x2; x < x2; x++, light += rw_lightstep) + { + int y1 = uwal[x]; + int y2 = dwal[x]; + if (y2 <= y1) + continue; + + if (!fixed) + R_SetColorMapLight(basecolormap, light, wallshade); + + if (x + 1 < x2) xmagnitude = fabs(FIXED2DBL(lwal[x + 1]) - FIXED2DBL(lwal[x])); + + WallSampler sampler(y1, swal[x], yrepeat, lwal[x] + xoffset, xmagnitude, rw_pic, getcol); + Draw1Column(x, y1, y2, sampler, draw1column); + } + + NetUpdate(); +} + +static void ProcessNormalWall(int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat, const BYTE *(*getcol)(FTexture *tex, int x) = R_GetColumn) +{ + ProcessWallWorker(x1, x2, uwal, dwal, swal, lwal, yrepeat, getcol, R_DrawWallCol1, R_DrawWallCol4); +} + +static void ProcessMaskedWall(int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat, const BYTE *(*getcol)(FTexture *tex, int x) = R_GetColumn) +{ + if (!rw_pic->bMasked) // Textures that aren't masked can use the faster ProcessNormalWall. + { + ProcessNormalWall(x1, x2, uwal, dwal, swal, lwal, yrepeat, getcol); + } + else + { + ProcessWallWorker(x1, x2, uwal, dwal, swal, lwal, yrepeat, getcol, R_DrawWallMaskedCol1, R_DrawWallMaskedCol4); + } +} + +static void ProcessTranslucentWall(int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat, const BYTE *(*getcol)(FTexture *tex, int x) = R_GetColumn) +{ + static void(*drawcol1)(); + static void(*drawcol4)(); + if (!R_GetTransMaskDrawers(&drawcol1, &drawcol4)) + { + // The current translucency is unsupported, so draw with regular ProcessMaskedWall instead. + ProcessMaskedWall(x1, x2, uwal, dwal, swal, lwal, yrepeat, getcol); + } + else + { + ProcessWallWorker(x1, x2, uwal, dwal, swal, lwal, yrepeat, getcol, drawcol1, drawcol4); + } +} + +#endif + static void ProcessStripedWall(int x1, int x2, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat) { FDynamicColormap *startcolormap = basecolormap; @@ -560,8 +1163,9 @@ void R_DrawDrawSeg(drawseg_t *ds, int x1, int x2, short *uwal, short *dwal, floa } -void R_DrawWallSegment(FTexture *rw_pic, int x1, int x2, short *walltop, short *wallbottom, float *swall, fixed_t *lwall, double yscale, double top, double bottom, bool mask) +void R_DrawWallSegment(FTexture *rw_pic, int x1, int x2, short *walltop, short *wallbottom, float *swall, fixed_t *lwall, double yscale, double top, double bottom, bool mask, FLightNode *light_list) { + dc_light_list = light_list; if (rw_pic->GetHeight() != 1 << rw_pic->HeightBits) { ProcessWallNP2(x1, x2, walltop, wallbottom, swall, lwall, yscale, top, bottom, false); @@ -570,6 +1174,7 @@ void R_DrawWallSegment(FTexture *rw_pic, int x1, int x2, short *walltop, short * { ProcessWall(x1, x2, walltop, wallbottom, swall, lwall, yscale, false); } + dc_light_list = nullptr; } void R_DrawSkySegment(visplane_t *pl, short *uwal, short *dwal, float *swal, fixed_t *lwal, double yrepeat, const BYTE *(*getcol)(FTexture *tex, int x)) diff --git a/src/s_sound.cpp b/src/s_sound.cpp index fd15b9491..be1b572f1 100644 --- a/src/s_sound.cpp +++ b/src/s_sound.cpp @@ -917,6 +917,7 @@ static FSoundChan *S_StartSound(AActor *actor, const sector_t *sec, const FPolyO // the referenced sound so some additional checks are required int near_limit = sfx->NearLimit; float limit_range = sfx->LimitRange; + auto pitchmask = sfx->PitchMask; rolloff = &sfx->Rolloff; // Resolve player sounds, random sounds, and aliases @@ -1081,9 +1082,9 @@ static FSoundChan *S_StartSound(AActor *actor, const sector_t *sec, const FPolyO } // Vary the sfx pitches. - if (sfx->PitchMask != 0) + if (pitchmask != 0) { - pitch = NORM_PITCH - (M_Random() & sfx->PitchMask) + (M_Random() & sfx->PitchMask); + pitch = NORM_PITCH - (M_Random() & pitchmask) + (M_Random() & pitchmask); } else { diff --git a/src/stats.h b/src/stats.h index 612cd2739..d90efa7e4 100644 --- a/src/stats.h +++ b/src/stats.h @@ -267,6 +267,10 @@ public: virtual FString GetStats () = 0; void ToggleStat (); + bool isActive() const + { + return m_Active; + } static void PrintStat (); static FStat *FindStat (const char *name); diff --git a/src/textures/automaptexture.cpp b/src/textures/automaptexture.cpp index 67d68b9fe..9aac379ef 100644 --- a/src/textures/automaptexture.cpp +++ b/src/textures/automaptexture.cpp @@ -122,6 +122,7 @@ void FAutomapTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/bitmap.h b/src/textures/bitmap.h index 27d3c0b4b..a27d1ff98 100644 --- a/src/textures/bitmap.h +++ b/src/textures/bitmap.h @@ -380,7 +380,7 @@ struct bCopyAlpha }; struct bOverlay -{ +{ static __forceinline void OpC(BYTE &d, BYTE s, BYTE a, FCopyInfo *i) { d = (s*a + d*(255-a))/255; } static __forceinline void OpA(BYTE &d, BYTE s, FCopyInfo *i) { d = MAX(s,d); } static __forceinline bool ProcessAlpha0() { return false; } diff --git a/src/textures/buildtexture.cpp b/src/textures/buildtexture.cpp index bfcc6333d..1155dacc4 100644 --- a/src/textures/buildtexture.cpp +++ b/src/textures/buildtexture.cpp @@ -56,7 +56,6 @@ public: const BYTE *GetColumn (unsigned int column, const Span **spans_out); const BYTE *GetPixels (); - void Unload (); protected: const BYTE *Pixels; @@ -103,17 +102,6 @@ FBuildTexture::~FBuildTexture () // //========================================================================== -void FBuildTexture::Unload () -{ - // Nothing to do, since the pixels are accessed from memory-mapped files directly -} - -//========================================================================== -// -// -// -//========================================================================== - const BYTE *FBuildTexture::GetPixels () { return Pixels; diff --git a/src/textures/canvastexture.cpp b/src/textures/canvastexture.cpp index 062c3af1d..109d927ab 100644 --- a/src/textures/canvastexture.cpp +++ b/src/textures/canvastexture.cpp @@ -53,7 +53,6 @@ FCanvasTexture::FCanvasTexture (const char *name, int width, int height) DummySpans[1].TopOffset = 0; DummySpans[1].Length = 0; UseType = TEX_Wall; - Canvas = NULL; bNeedsUpdate = true; bDidUpdate = false; bHasCanvas = true; @@ -101,11 +100,22 @@ const BYTE *FCanvasTexture::GetPixels () return Pixels; } +const uint32_t *FCanvasTexture::GetPixelsBgra() +{ + bNeedsUpdate = true; + if (CanvasBgra == NULL) + { + MakeTextureBgra(); + } + return PixelsBgra; +} + void FCanvasTexture::MakeTexture () { - Canvas = new DSimpleCanvas (Width, Height); + Canvas = new DSimpleCanvas (Width, Height, false); Canvas->Lock (); GC::AddSoftRoot(Canvas); + if (Width != Height || Width != Canvas->GetPitch()) { Pixels = new BYTE[Width*Height]; @@ -113,29 +123,68 @@ void FCanvasTexture::MakeTexture () } else { - Pixels = Canvas->GetBuffer(); + Pixels = (BYTE*)Canvas->GetBuffer(); bPixelsAllocated = false; } + // Draw a special "unrendered" initial texture into the buffer. memset (Pixels, 0, Width*Height/2); memset (Pixels+Width*Height/2, 255, Width*Height/2); } +void FCanvasTexture::MakeTextureBgra() +{ + CanvasBgra = new DSimpleCanvas(Width, Height, true); + CanvasBgra->Lock(); + GC::AddSoftRoot(CanvasBgra); + + if (Width != Height || Width != CanvasBgra->GetPitch()) + { + PixelsBgra = new uint32_t[Width*Height]; + bPixelsAllocatedBgra = true; + } + else + { + PixelsBgra = (uint32_t*)CanvasBgra->GetBuffer(); + bPixelsAllocatedBgra = false; + } + + // Draw a special "unrendered" initial texture into the buffer. + memset(PixelsBgra, 0, Width*Height / 2 * 4); + memset(PixelsBgra + Width*Height / 2, 255, Width*Height / 2 * 4); +} + void FCanvasTexture::Unload () { if (bPixelsAllocated) { - if (Pixels != NULL) delete [] Pixels; + if (Pixels != NULL) delete[] Pixels; bPixelsAllocated = false; Pixels = NULL; } + if (bPixelsAllocatedBgra) + { + if (PixelsBgra != NULL) delete[] PixelsBgra; + bPixelsAllocatedBgra = false; + PixelsBgra = NULL; + } + if (Canvas != NULL) { GC::DelSoftRoot(Canvas); Canvas->Destroy(); Canvas = NULL; } + + if (CanvasBgra != NULL) + { + GC::DelSoftRoot(CanvasBgra); + CanvasBgra->Destroy(); + CanvasBgra = NULL; + } + + FTexture::Unload(); } bool FCanvasTexture::CheckModified () diff --git a/src/textures/ddstexture.cpp b/src/textures/ddstexture.cpp index a2c69b38b..e839c020a 100644 --- a/src/textures/ddstexture.cpp +++ b/src/textures/ddstexture.cpp @@ -401,6 +401,7 @@ void FDDSTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/flattexture.cpp b/src/textures/flattexture.cpp index 840d53aaf..08e0d1221 100644 --- a/src/textures/flattexture.cpp +++ b/src/textures/flattexture.cpp @@ -138,6 +138,7 @@ void FFlatTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/imgztexture.cpp b/src/textures/imgztexture.cpp index 1c262d707..04932d4bf 100644 --- a/src/textures/imgztexture.cpp +++ b/src/textures/imgztexture.cpp @@ -142,6 +142,7 @@ void FIMGZTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/jpegtexture.cpp b/src/textures/jpegtexture.cpp index c138edbfa..684e06fa6 100644 --- a/src/textures/jpegtexture.cpp +++ b/src/textures/jpegtexture.cpp @@ -295,11 +295,9 @@ FJPEGTexture::~FJPEGTexture () void FJPEGTexture::Unload () { - if (Pixels != NULL) - { - delete[] Pixels; - Pixels = NULL; - } + delete[] Pixels; + Pixels = NULL; + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/multipatchtexture.cpp b/src/textures/multipatchtexture.cpp index 991893845..1a704edf2 100644 --- a/src/textures/multipatchtexture.cpp +++ b/src/textures/multipatchtexture.cpp @@ -359,6 +359,7 @@ void FMultiPatchTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== @@ -625,8 +626,9 @@ int FMultiPatchTexture::CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rota { ret = Parts[i].Texture->CopyTrueColorPixels(bmp, x+Parts[i].OriginX, y+Parts[i].OriginY, Parts[i].Rotate, &info); } - - if (ret > retv) retv = ret; + // treat -1 (i.e. unknown) as absolute. We have no idea if this may have overwritten previous info so a real check needs to be done. + if (ret == -1) retv = ret; + else if (retv != -1 && ret > retv) retv = ret; } // Restore previous clipping rectangle. bmp->SetClipRect(saved_cr); diff --git a/src/textures/patchtexture.cpp b/src/textures/patchtexture.cpp index 423ce4deb..8388515c0 100644 --- a/src/textures/patchtexture.cpp +++ b/src/textures/patchtexture.cpp @@ -184,6 +184,7 @@ void FPatchTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/pcxtexture.cpp b/src/textures/pcxtexture.cpp index dda431993..6f7c277e3 100644 --- a/src/textures/pcxtexture.cpp +++ b/src/textures/pcxtexture.cpp @@ -191,6 +191,7 @@ void FPCXTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/pngtexture.cpp b/src/textures/pngtexture.cpp index 414c424b8..30b7c6445 100644 --- a/src/textures/pngtexture.cpp +++ b/src/textures/pngtexture.cpp @@ -373,11 +373,9 @@ FPNGTexture::~FPNGTexture () void FPNGTexture::Unload () { - if (Pixels != NULL) - { - delete[] Pixels; - Pixels = NULL; - } + delete[] Pixels; + Pixels = NULL; + FTexture::Unload(); } //========================================================================== @@ -450,6 +448,7 @@ const BYTE *FPNGTexture::GetPixels () return Pixels; } + //========================================================================== // // diff --git a/src/textures/rawpagetexture.cpp b/src/textures/rawpagetexture.cpp index 1402f8844..69313fd1c 100644 --- a/src/textures/rawpagetexture.cpp +++ b/src/textures/rawpagetexture.cpp @@ -206,6 +206,7 @@ void FRawPageTexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/texture.cpp b/src/textures/texture.cpp index 9c1b5fdb4..01906ac7b 100644 --- a/src/textures/texture.cpp +++ b/src/textures/texture.cpp @@ -176,6 +176,37 @@ FTexture::~FTexture () KillNative(); } +void FTexture::Unload() +{ + PixelsBgra = std::vector(); +} + +const uint32_t *FTexture::GetColumnBgra(unsigned int column, const Span **spans_out) +{ + const uint32_t *pixels = GetPixelsBgra(); + + column %= Width; + + if (spans_out != nullptr) + GetColumn(column, spans_out); + return pixels + column * Height; +} + +const uint32_t *FTexture::GetPixelsBgra() +{ + if (PixelsBgra.empty() || CheckModified()) + { + if (!GetColumn(0, nullptr)) + return nullptr; + + FBitmap bitmap; + bitmap.Create(GetWidth(), GetHeight()); + CopyTrueColorPixels(&bitmap, 0, 0); + GenerateBgraFromBitmap(bitmap); + } + return PixelsBgra.data(); +} + bool FTexture::CheckModified () { return false; @@ -320,6 +351,210 @@ void FTexture::FreeSpans (Span **spans) const M_Free (spans); } +void FTexture::GenerateBgraFromBitmap(const FBitmap &bitmap) +{ + CreatePixelsBgraWithMipmaps(); + + // Transpose + const uint32_t *src = (const uint32_t *)bitmap.GetPixels(); + uint32_t *dest = PixelsBgra.data(); + for (int x = 0; x < Width; x++) + { + for (int y = 0; y < Height; y++) + { + dest[y + x * Height] = src[x + y * Width]; + } + } + + GenerateBgraMipmaps(); +} + +void FTexture::CreatePixelsBgraWithMipmaps() +{ + int levels = MipmapLevels(); + int buffersize = 0; + for (int i = 0; i < levels; i++) + { + int w = MAX(Width >> i, 1); + int h = MAX(Height >> i, 1); + buffersize += w * h; + } + PixelsBgra.resize(buffersize, 0xffff0000); +} + +int FTexture::MipmapLevels() const +{ + int widthbits = 0; + while ((Width >> widthbits) != 0) widthbits++; + + int heightbits = 0; + while ((Height >> heightbits) != 0) heightbits++; + + return MAX(widthbits, heightbits); +} + +void FTexture::GenerateBgraMipmaps() +{ + struct Color4f + { + float a, r, g, b; + Color4f operator*(const Color4f &v) const { return Color4f{ a * v.a, r * v.r, g * v.g, b * v.b }; } + Color4f operator/(const Color4f &v) const { return Color4f{ a / v.a, r / v.r, g / v.g, b / v.b }; } + Color4f operator+(const Color4f &v) const { return Color4f{ a + v.a, r + v.r, g + v.g, b + v.b }; } + Color4f operator-(const Color4f &v) const { return Color4f{ a - v.a, r - v.r, g - v.g, b - v.b }; } + Color4f operator*(float s) const { return Color4f{ a * s, r * s, g * s, b * s }; } + Color4f operator/(float s) const { return Color4f{ a / s, r / s, g / s, b / s }; } + Color4f operator+(float s) const { return Color4f{ a + s, r + s, g + s, b + s }; } + Color4f operator-(float s) const { return Color4f{ a - s, r - s, g - s, b - s }; } + }; + + int levels = MipmapLevels(); + std::vector image(PixelsBgra.size()); + + // Convert to normalized linear colorspace + { + for (int x = 0; x < Width; x++) + { + for (int y = 0; y < Height; y++) + { + uint32_t c8 = PixelsBgra[x * Height + y]; + Color4f c; + c.a = powf(APART(c8) * (1.0f / 255.0f), 2.2f); + c.r = powf(RPART(c8) * (1.0f / 255.0f), 2.2f); + c.g = powf(GPART(c8) * (1.0f / 255.0f), 2.2f); + c.b = powf(BPART(c8) * (1.0f / 255.0f), 2.2f); + image[x * Height + y] = c; + } + } + } + + // Generate mipmaps + { + std::vector smoothed(Width * Height); + Color4f *src = image.data(); + Color4f *dest = src + Width * Height; + for (int i = 1; i < levels; i++) + { + int srcw = MAX(Width >> (i - 1), 1); + int srch = MAX(Height >> (i - 1), 1); + int w = MAX(Width >> i, 1); + int h = MAX(Height >> i, 1); + + // Downscale + for (int x = 0; x < w; x++) + { + int sx0 = x * 2; + int sx1 = MIN((x + 1) * 2, srcw - 1); + for (int y = 0; y < h; y++) + { + int sy0 = y * 2; + int sy1 = MIN((y + 1) * 2, srch - 1); + + Color4f src00 = src[sy0 + sx0 * srch]; + Color4f src01 = src[sy1 + sx0 * srch]; + Color4f src10 = src[sy0 + sx1 * srch]; + Color4f src11 = src[sy1 + sx1 * srch]; + Color4f c = (src00 + src01 + src10 + src11) * 0.25f; + + dest[y + x * h] = c; + } + } + + // Sharpen filter with a 3x3 kernel: + for (int x = 0; x < w; x++) + { + for (int y = 0; y < h; y++) + { + Color4f c = { 0.0f, 0.0f, 0.0f, 0.0f }; + for (int kx = -1; kx < 2; kx++) + { + for (int ky = -1; ky < 2; ky++) + { + int a = y + ky; + int b = x + kx; + if (a < 0) a = h - 1; + if (a == h) a = 0; + if (b < 0) b = w - 1; + if (b == w) b = 0; + c = c + dest[a + b * h]; + } + } + c = c * (1.0f / 9.0f); + smoothed[y + x * h] = c; + } + } + float k = 0.08f; + for (int j = 0; j < w * h; j++) + dest[j] = dest[j] + (dest[j] - smoothed[j]) * k; + + src = dest; + dest += w * h; + } + } + + // Convert to bgra8 sRGB colorspace + { + Color4f *src = image.data() + Width * Height; + uint32_t *dest = PixelsBgra.data() + Width * Height; + for (int i = 1; i < levels; i++) + { + int w = MAX(Width >> i, 1); + int h = MAX(Height >> i, 1); + for (int j = 0; j < w * h; j++) + { + uint32_t a = (uint32_t)clamp(powf(MAX(src[j].a, 0.0f), 1.0f / 2.2f) * 255.0f + 0.5f, 0.0f, 255.0f); + uint32_t r = (uint32_t)clamp(powf(MAX(src[j].r, 0.0f), 1.0f / 2.2f) * 255.0f + 0.5f, 0.0f, 255.0f); + uint32_t g = (uint32_t)clamp(powf(MAX(src[j].g, 0.0f), 1.0f / 2.2f) * 255.0f + 0.5f, 0.0f, 255.0f); + uint32_t b = (uint32_t)clamp(powf(MAX(src[j].b, 0.0f), 1.0f / 2.2f) * 255.0f + 0.5f, 0.0f, 255.0f); + dest[j] = (a << 24) | (r << 16) | (g << 8) | b; + } + src += w * h; + dest += w * h; + } + } +} + +void FTexture::GenerateBgraMipmapsFast() +{ + uint32_t *src = PixelsBgra.data(); + uint32_t *dest = src + Width * Height; + int levels = MipmapLevels(); + for (int i = 1; i < levels; i++) + { + int srcw = MAX(Width >> (i - 1), 1); + int srch = MAX(Height >> (i - 1), 1); + int w = MAX(Width >> i, 1); + int h = MAX(Height >> i, 1); + + for (int x = 0; x < w; x++) + { + int sx0 = x * 2; + int sx1 = MIN((x + 1) * 2, srcw - 1); + + for (int y = 0; y < h; y++) + { + int sy0 = y * 2; + int sy1 = MIN((y + 1) * 2, srch - 1); + + uint32_t src00 = src[sy0 + sx0 * srch]; + uint32_t src01 = src[sy1 + sx0 * srch]; + uint32_t src10 = src[sy0 + sx1 * srch]; + uint32_t src11 = src[sy1 + sx1 * srch]; + + uint32_t alpha = (APART(src00) + APART(src01) + APART(src10) + APART(src11) + 2) / 4; + uint32_t red = (RPART(src00) + RPART(src01) + RPART(src10) + RPART(src11) + 2) / 4; + uint32_t green = (GPART(src00) + GPART(src01) + GPART(src10) + GPART(src11) + 2) / 4; + uint32_t blue = (BPART(src00) + BPART(src01) + BPART(src10) + BPART(src11) + 2) / 4; + + dest[y + x * h] = (alpha << 24) | (red << 16) | (green << 8) | blue; + } + } + + src = dest; + dest += w * h; + } +} + void FTexture::CopyToBlock (BYTE *dest, int dwidth, int dheight, int xpos, int ypos, int rotate, const BYTE *translation) { const BYTE *pixels = GetPixels(); @@ -386,6 +621,29 @@ void FTexture::FlipSquareBlock (BYTE *block, int x, int y) } } +void FTexture::FlipSquareBlockBgra(uint32_t *block, int x, int y) +{ + int i, j; + + if (x != y) return; + + for (i = 0; i < x; ++i) + { + uint32_t *corner = block + x*i + i; + int count = x - i; + if (count & 1) + { + count--; + swapvalues(corner[count], corner[count*x]); + } + for (j = 0; j < count; j += 2) + { + swapvalues(corner[j], corner[j*x]); + swapvalues(corner[j + 1], corner[(j + 1)*x]); + } + } +} + void FTexture::FlipSquareBlockRemap (BYTE *block, int x, int y, const BYTE *remap) { int i, j; @@ -429,6 +687,19 @@ void FTexture::FlipNonSquareBlock (BYTE *dst, const BYTE *src, int x, int y, int } } +void FTexture::FlipNonSquareBlockBgra(uint32_t *dst, const uint32_t *src, int x, int y, int srcpitch) +{ + int i, j; + + for (i = 0; i < x; ++i) + { + for (j = 0; j < y; ++j) + { + dst[i*y + j] = src[i + j*srcpitch]; + } + } +} + void FTexture::FlipNonSquareBlockRemap (BYTE *dst, const BYTE *src, int x, int y, int srcpitch, const BYTE *remap) { int i, j; @@ -652,10 +923,6 @@ FDummyTexture::FDummyTexture () UseType = TEX_Null; } -void FDummyTexture::Unload () -{ -} - void FDummyTexture::SetSize (int width, int height) { Width = width; diff --git a/src/textures/textures.h b/src/textures/textures.h index 064610f50..db58aaf22 100644 --- a/src/textures/textures.h +++ b/src/textures/textures.h @@ -3,6 +3,28 @@ #include "doomtype.h" #include "vectors.h" +#include + +struct FloatRect +{ + float left,top; + float width,height; + + + void Offset(float xofs,float yofs) + { + left+=xofs; + top+=yofs; + } + void Scale(float xfac,float yfac) + { + left*=xfac; + width*=xfac; + top*=yfac; + height*=yfac; + } +}; + class FBitmap; struct FRemapTable; @@ -13,6 +35,8 @@ class PClassInventory; // Texture IDs class FTextureManager; class FTerrainTypeArray; +class FGLTexture; +class FMaterial; class FNullTextureID : public FTextureID { @@ -172,9 +196,18 @@ public: // Returns a single column of the texture virtual const BYTE *GetColumn (unsigned int column, const Span **spans_out) = 0; + // Returns a single column of the texture, in BGRA8 format + virtual const uint32_t *GetColumnBgra(unsigned int column, const Span **spans_out); + // Returns the whole texture, stored in column-major order virtual const BYTE *GetPixels () = 0; - + + // Returns the whole texture, stored in column-major order, in BGRA8 format + virtual const uint32_t *GetPixelsBgra(); + + // Returns true if GetPixelsBgra includes mipmaps + virtual bool Mipmapped() { return true; } + virtual int CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate=0, FCopyInfo *inf = NULL); int CopyTrueColorTranslated(FBitmap *bmp, int x, int y, int rotate, FRemapTable *remap, FCopyInfo *inf = NULL); virtual bool UseBasePalette(); @@ -182,7 +215,7 @@ public: virtual FTexture *GetRedirect(bool wantwarped); virtual FTexture *GetRawTexture(); // for FMultiPatchTexture to override - virtual void Unload () = 0; + virtual void Unload (); // Returns the native pixel format for this image virtual FTextureFormat GetFormat(); @@ -259,8 +292,19 @@ protected: CopySize(other); bNoDecals = other->bNoDecals; Rotations = other->Rotations; + gl_info = other->gl_info; + gl_info.Brightmap = NULL; + gl_info.areas = NULL; } + std::vector PixelsBgra; + + void GenerateBgraFromBitmap(const FBitmap &bitmap); + void CreatePixelsBgraWithMipmaps(); + void GenerateBgraMipmaps(); + void GenerateBgraMipmapsFast(); + int MipmapLevels() const; + private: bool bSWSkyColorDone = false; PalEntry FloorSkyColor; @@ -268,13 +312,52 @@ private: public: static void FlipSquareBlock (BYTE *block, int x, int y); + static void FlipSquareBlockBgra (uint32_t *block, int x, int y); static void FlipSquareBlockRemap (BYTE *block, int x, int y, const BYTE *remap); static void FlipNonSquareBlock (BYTE *blockto, const BYTE *blockfrom, int x, int y, int srcpitch); + static void FlipNonSquareBlockBgra (uint32_t *blockto, const uint32_t *blockfrom, int x, int y, int srcpitch); static void FlipNonSquareBlockRemap (BYTE *blockto, const BYTE *blockfrom, int x, int y, int srcpitch, const BYTE *remap); friend class D3DTex; -}; + friend class OpenGLSWFrameBuffer; +public: + + struct MiscGLInfo + { + FMaterial *Material[2]; + FGLTexture *SystemTexture[2]; + FTexture *Brightmap; + PalEntry GlowColor; + int GlowHeight; + FloatRect *areas; + int areacount; + int shaderindex; + float shaderspeed; + int mIsTransparent:2; + bool bGlowing:1; // Texture glows + bool bFullbright:1; // always draw fullbright + bool bSkybox:1; // This is a skybox + char bBrightmapChecked:1; // Set to 1 if brightmap has been checked + bool bDisableFullbright:1; // This texture will not be displayed as fullbright sprite + bool bNoFilter:1; + bool bNoCompress:1; + bool bNoExpand:1; + + MiscGLInfo() throw (); + ~MiscGLInfo(); + }; + MiscGLInfo gl_info; + + void GetGlowColor(float *data); + bool isGlowing() { return gl_info.bGlowing; } + bool isFullbright() { return gl_info.bFullbright; } + void CreateDefaultBrightmap(); + bool FindHoles(const unsigned char * buffer, int w, int h); + static bool SmoothEdges(unsigned char * buffer,int w, int h); + void CheckTrans(unsigned char * buffer, int size, int trans); + bool ProcessData(unsigned char * buffer, int w, int h, bool ispatch); +}; // Texture manager class FTextureManager @@ -461,7 +544,6 @@ public: FDummyTexture (); const BYTE *GetColumn (unsigned int column, const Span **spans_out); const BYTE *GetPixels (); - void Unload (); void SetSize (int width, int height); }; @@ -475,6 +557,7 @@ public: virtual int CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate=0, FCopyInfo *inf = NULL); const BYTE *GetColumn (unsigned int column, const Span **spans_out); const BYTE *GetPixels (); + const uint32_t *GetPixelsBgra() override; void Unload (); bool CheckModified (); @@ -484,12 +567,12 @@ public: FTexture *GetRedirect(bool wantwarped); DWORD GenTime; + float Speed; + int WidthOffsetMultiplier, HeightOffsetMultiplier; // [mxd] protected: FTexture *SourcePic; BYTE *Pixels; Span **Spans; - float Speed; - int WidthOffsetMultiplier, HeightOffsetMultiplier; // [mxd] virtual void MakeTexture (DWORD time); int NextPo2 (int v); // [mxd] @@ -508,21 +591,28 @@ public: const BYTE *GetColumn (unsigned int column, const Span **spans_out); const BYTE *GetPixels (); + const uint32_t *GetPixelsBgra() override; void Unload (); bool CheckModified (); void NeedUpdate() { bNeedsUpdate=true; } void SetUpdated() { bNeedsUpdate = false; bDidUpdate = true; bFirstUpdate = false; } DSimpleCanvas *GetCanvas() { return Canvas; } + DSimpleCanvas *GetCanvasBgra() { return CanvasBgra; } + bool Mipmapped() override { return false; } void MakeTexture (); + void MakeTextureBgra (); protected: - DSimpleCanvas *Canvas; - BYTE *Pixels; + DSimpleCanvas *Canvas = nullptr; + DSimpleCanvas *CanvasBgra = nullptr; + BYTE *Pixels = nullptr; + uint32_t *PixelsBgra = nullptr; Span DummySpans[2]; - bool bNeedsUpdate; - bool bDidUpdate; - bool bPixelsAllocated; + bool bNeedsUpdate = true; + bool bDidUpdate = false; + bool bPixelsAllocated = false; + bool bPixelsAllocatedBgra = false; public: bool bFirstUpdate; diff --git a/src/textures/tgatexture.cpp b/src/textures/tgatexture.cpp index 331747cfe..878b41084 100644 --- a/src/textures/tgatexture.cpp +++ b/src/textures/tgatexture.cpp @@ -181,6 +181,7 @@ void FTGATexture::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/textures/warptexture.cpp b/src/textures/warptexture.cpp index a8a2ddb9e..91c7b9fc4 100644 --- a/src/textures/warptexture.cpp +++ b/src/textures/warptexture.cpp @@ -39,6 +39,7 @@ #include "r_utility.h" #include "textures/textures.h" #include "warpbuffer.h" +#include "v_palette.h" FWarpTexture::FWarpTexture (FTexture *source, int warptype) @@ -74,6 +75,7 @@ void FWarpTexture::Unload () Spans = NULL; } SourcePic->Unload (); + FTexture::Unload(); } bool FWarpTexture::CheckModified () @@ -92,6 +94,25 @@ const BYTE *FWarpTexture::GetPixels () return Pixels; } +const uint32_t *FWarpTexture::GetPixelsBgra() +{ + DWORD time = r_FrameTime; + if (Pixels == NULL || time != GenTime) + { + MakeTexture(time); + CreatePixelsBgraWithMipmaps(); + for (int i = 0; i < Width * Height; i++) + { + if (Pixels[i] != 0) + PixelsBgra[i] = 0xff000000 | GPalette.BaseColors[Pixels[i]].d; + else + PixelsBgra[i] = 0; + } + GenerateBgraMipmapsFast(); + } + return PixelsBgra.data(); +} + const BYTE *FWarpTexture::GetColumn (unsigned int column, const Span **spans_out) { DWORD time = r_FrameTime; diff --git a/src/v_draw.cpp b/src/v_draw.cpp index 6f8bc5198..1b23d5566 100644 --- a/src/v_draw.cpp +++ b/src/v_draw.cpp @@ -44,6 +44,7 @@ #include "r_utility.h" #ifndef NO_SWRENDER #include "r_draw.h" +#include "r_draw_rgba.h" #include "r_main.h" #include "r_things.h" #endif @@ -69,6 +70,7 @@ CUSTOM_CVAR(Int, uiscale, 2, CVAR_ARCHIVE | CVAR_NOINITCALL) StatusBar->ScreenSizeChanged(); } } +EXTERN_CVAR(Bool, r_blendmethod) // [RH] Stretch values to make a 320x200 image best fit the screen // without using fractional steppings @@ -132,12 +134,18 @@ void DCanvas::DrawTexture (FTexture *img, double x, double y, int tags_first, .. void DCanvas::DrawTextureParms(FTexture *img, DrawParms &parms) { #ifndef NO_SWRENDER - using namespace swrenderer; - using namespace drawerargs; + using namespace swrenderer; + using namespace drawerargs; static short bottomclipper[MAXWIDTH], topclipper[MAXWIDTH]; const BYTE *translation = NULL; + if (r_swtruecolor != IsBgra()) + { + r_swtruecolor = IsBgra(); + R_InitColumnDrawers(); + } + if (APART(parms.colorOverlay) != 0) { // The software renderer cannot invert the source without inverting the overlay @@ -154,29 +162,44 @@ void DCanvas::DrawTextureParms(FTexture *img, DrawParms &parms) parms.colorOverlay = PalEntry(parms.colorOverlay).InverseColor(); } // Note that this overrides DTA_Translation in software, but not in hardware. - FDynamicColormap *colormap = GetSpecialLights(MAKERGB(255,255,255), - parms.colorOverlay & MAKEARGB(0,255,255,255), 0); - translation = &colormap->Maps[(APART(parms.colorOverlay)*NUMCOLORMAPS/255)*256]; + if (!r_swtruecolor) + { + FDynamicColormap *colormap = GetSpecialLights(MAKERGB(255, 255, 255), + parms.colorOverlay & MAKEARGB(0, 255, 255, 255), 0); + translation = &colormap->Maps[(APART(parms.colorOverlay)*NUMCOLORMAPS / 255) * 256]; + } } else if (parms.remap != NULL) { - translation = parms.remap->Remap; + if (r_swtruecolor) + translation = (const BYTE*)parms.remap->Palette; + else + translation = parms.remap->Remap; } if (translation != NULL) { - dc_colormap = (lighttable_t *)translation; + R_SetTranslationMap((lighttable_t *)translation); } else { - dc_colormap = identitymap; + if (r_swtruecolor) + R_SetTranslationMap(nullptr); + else + R_SetTranslationMap(identitymap); } - fixedcolormap = dc_colormap; - ESPSResult mode = R_SetPatchStyle (parms.style, parms.Alpha, 0, parms.fillcolor); + fixedcolormap = dc_fcolormap; + bool visible; + if (r_swtruecolor) + visible = R_SetPatchStyle(parms.style, parms.Alpha, -1, parms.fillcolor); + else + visible = R_SetPatchStyle(parms.style, parms.Alpha, 0, parms.fillcolor); BYTE *destorgsave = dc_destorg; + int destheightsave = dc_destheight; dc_destorg = screen->GetBuffer(); + dc_destheight = screen->GetHeight(); if (dc_destorg == NULL) { I_FatalError("Attempt to write to buffer of hardware canvas"); @@ -185,10 +208,8 @@ void DCanvas::DrawTextureParms(FTexture *img, DrawParms &parms) double x0 = parms.x - parms.left * parms.destwidth / parms.texwidth; double y0 = parms.y - parms.top * parms.destheight / parms.texheight; - if (mode != DontDraw) + if (visible) { - int stop4; - double centeryback = CenterY; CenterY = 0; @@ -254,61 +275,23 @@ void DCanvas::DrawTextureParms(FTexture *img, DrawParms &parms) x2 = parms.rclip; } - // Drawing short output ought to fit in the data cache well enough - // if we draw one column at a time, so do that, since it's simpler. - if (parms.destheight < 32 || (parms.dclip - parms.uclip) < 32) - { - mode = DoDraw0; - } - dc_x = int(x0); int x2_i = int(x2); fixed_t xiscale_i = FLOAT2FIXED(xiscale); - if (mode == DoDraw0) + while (dc_x < x2_i) { - // One column at a time - stop4 = dc_x; - } - else // DoDraw1` - { - // Up to four columns at a time - stop4 = x2_i & ~3; + R_DrawMaskedColumn(img, frac, !parms.masked); + dc_x++; + frac += xiscale_i; } - if (dc_x < x2_i) - { - while ((dc_x < stop4) && (dc_x & 3)) - { - R_DrawMaskedColumn(img, frac, false, !parms.masked); - dc_x++; - frac += xiscale_i; - } - - while (dc_x < stop4) - { - rt_initcols(); - for (int zz = 4; zz; --zz) - { - R_DrawMaskedColumn(img, frac, true, !parms.masked); - dc_x++; - frac += xiscale_i; - } - rt_draw4cols(dc_x - 4); - } - - while (dc_x < x2_i) - { - R_DrawMaskedColumn(img, frac, false, !parms.masked); - dc_x++; - frac += xiscale_i; - } - } CenterY = centeryback; } R_FinishSetPatchStyle (); dc_destorg = destorgsave; + dc_destheight = destheightsave; if (ticdup != 0 && menuactive == MENU_Off) { @@ -965,27 +948,6 @@ void DCanvas::PUTTRANSDOT (int xx, int yy, int basecolor, int level) static int oldyy; static int oldyyshifted; -#if 0 - if(xx < 32) - cc += 7-(xx>>2); - else if(xx > (finit_width - 32)) - cc += 7-((finit_width-xx) >> 2); -// if(cc==oldcc) //make sure that we don't double fade the corners. -// { - if(yy < 32) - cc += 7-(yy>>2); - else if(yy > (finit_height - 32)) - cc += 7-((finit_height-yy) >> 2); -// } - if(cc > cm && cm != NULL) - { - cc = cm; - } - else if(cc > oldcc+6) // don't let the color escape from the fade table... - { - cc=oldcc+6; - } -#endif if (yy == oldyy+1) { oldyy++; @@ -1002,13 +964,45 @@ void DCanvas::PUTTRANSDOT (int xx, int yy, int basecolor, int level) oldyyshifted = yy * GetPitch(); } - BYTE *spot = GetBuffer() + oldyyshifted + xx; - DWORD *bg2rgb = Col2RGB8[1+level]; - DWORD *fg2rgb = Col2RGB8[63-level]; - DWORD fg = fg2rgb[basecolor]; - DWORD bg = bg2rgb[*spot]; - bg = (fg+bg) | 0x1f07c1f; - *spot = RGB32k.All[bg&(bg>>15)]; + if (IsBgra()) + { + uint32_t *spot = (uint32_t*)GetBuffer() + oldyyshifted + xx; + + uint32_t fg = swrenderer::LightBgra::shade_pal_index_simple(basecolor, swrenderer::LightBgra::calc_light_multiplier(0)); + uint32_t fg_red = (((fg >> 16) & 0xff) * (63 - level)) >> 6; + uint32_t fg_green = (((fg >> 8) & 0xff) * (63 - level)) >> 6; + uint32_t fg_blue = ((fg & 0xff) * (63 - level)) >> 6; + + uint32_t bg_red = (((*spot >> 16) & 0xff) * level) >> 6; + uint32_t bg_green = (((*spot >> 8) & 0xff) * level) >> 6; + uint32_t bg_blue = (((*spot) & 0xff) * level) >> 6; + + uint32_t red = fg_red + bg_red; + uint32_t green = fg_green + bg_green; + uint32_t blue = fg_blue + bg_blue; + + *spot = 0xff000000 | (red << 16) | (green << 8) | blue; + } + else if (!r_blendmethod) + { + BYTE *spot = GetBuffer() + oldyyshifted + xx; + DWORD *bg2rgb = Col2RGB8[1+level]; + DWORD *fg2rgb = Col2RGB8[63-level]; + DWORD fg = fg2rgb[basecolor]; + DWORD bg = bg2rgb[*spot]; + bg = (fg+bg) | 0x1f07c1f; + *spot = RGB32k.All[bg&(bg>>15)]; + } + else + { + BYTE *spot = GetBuffer() + oldyyshifted + xx; + + uint32_t r = (GPalette.BaseColors[*spot].r * (64 - level) + GPalette.BaseColors[basecolor].r * level) / 64; + uint32_t g = (GPalette.BaseColors[*spot].g * (64 - level) + GPalette.BaseColors[basecolor].g * level) / 64; + uint32_t b = (GPalette.BaseColors[*spot].b * (64 - level) + GPalette.BaseColors[basecolor].b * level) / 64; + + *spot = (BYTE)RGB256k.RGB[r][g][b]; + } } void DCanvas::DrawLine(int x0, int y0, int x1, int y1, int palColor, uint32 realcolor) @@ -1052,27 +1046,65 @@ void DCanvas::DrawLine(int x0, int y0, int x1, int y1, int palColor, uint32 real { swapvalues (x0, x1); } - memset (GetBuffer() + y0*GetPitch() + x0, palColor, deltaX+1); + if (IsBgra()) + { + uint32_t fillColor = GPalette.BaseColors[palColor].d; + uint32_t *spot = (uint32_t*)GetBuffer() + y0*GetPitch() + x0; + for (int i = 0; i <= deltaX; i++) + spot[i] = fillColor; + } + else + { + memset (GetBuffer() + y0*GetPitch() + x0, palColor, deltaX+1); + } } else if (deltaX == 0) { // vertical line - BYTE *spot = GetBuffer() + y0*GetPitch() + x0; - int pitch = GetPitch (); - do + if (IsBgra()) { - *spot = palColor; - spot += pitch; - } while (--deltaY != 0); + uint32_t fillColor = GPalette.BaseColors[palColor].d; + uint32_t *spot = (uint32_t*)GetBuffer() + y0*GetPitch() + x0; + int pitch = GetPitch(); + do + { + *spot = fillColor; + spot += pitch; + } while (--deltaY != 0); + } + else + { + BYTE *spot = GetBuffer() + y0*GetPitch() + x0; + int pitch = GetPitch(); + do + { + *spot = palColor; + spot += pitch; + } while (--deltaY != 0); + } } else if (deltaX == deltaY) { // diagonal line. - BYTE *spot = GetBuffer() + y0*GetPitch() + x0; - int advance = GetPitch() + xDir; - do + if (IsBgra()) { - *spot = palColor; - spot += advance; - } while (--deltaY != 0); + uint32_t fillColor = GPalette.BaseColors[palColor].d; + uint32_t *spot = (uint32_t*)GetBuffer() + y0*GetPitch() + x0; + int advance = GetPitch() + xDir; + do + { + *spot = fillColor; + spot += advance; + } while (--deltaY != 0); + } + else + { + BYTE *spot = GetBuffer() + y0*GetPitch() + x0; + int advance = GetPitch() + xDir; + do + { + *spot = palColor; + spot += advance; + } while (--deltaY != 0); + } } else { @@ -1192,7 +1224,6 @@ void DCanvas::DrawPixel(int x, int y, int palColor, uint32 realcolor) void DCanvas::Clear (int left, int top, int right, int bottom, int palcolor, uint32 color) { int x, y; - BYTE *dest; if (left == right || top == bottom) { @@ -1222,12 +1253,28 @@ void DCanvas::Clear (int left, int top, int right, int bottom, int palcolor, uin palcolor = PalFromRGB(color); } - dest = Buffer + top * Pitch + left; - x = right - left; - for (y = top; y < bottom; y++) + if (IsBgra()) { - memset(dest, palcolor, x); - dest += Pitch; + uint32_t fill_color = GPalette.BaseColors[palcolor]; + + uint32_t *dest = (uint32_t*)Buffer + top * Pitch + left; + x = right - left; + for (y = top; y < bottom; y++) + { + for (int i = 0; i < x; i++) + dest[i] = fill_color; + dest += Pitch; + } + } + else + { + BYTE *dest = Buffer + top * Pitch + left; + x = right - left; + for (y = top; y < bottom; y++) + { + memset(dest, palcolor, x); + dest += Pitch; + } } } @@ -1264,8 +1311,8 @@ void DCanvas::FillSimplePoly(FTexture *tex, FVector2 *points, int npoints, FDynamicColormap *colormap, int lightlevel, int bottomclip) { #ifndef NO_SWRENDER - using namespace swrenderer; - using namespace drawerargs; + using namespace swrenderer; + using namespace drawerargs; // Use an equation similar to player sprites to determine shade fixed_t shade = LIGHT2SHADE(lightlevel) - 12*FRACUNIT; @@ -1333,7 +1380,10 @@ void DCanvas::FillSimplePoly(FTexture *tex, FVector2 *points, int npoints, // Setup constant texture mapping parameters. R_SetupSpanBits(tex); - R_SetSpanColormap(colormap != NULL ? &colormap->Maps[clamp(shade >> FRACBITS, 0, NUMCOLORMAPS-1) * 256] : identitymap); + if (colormap) + R_SetSpanColormap(colormap, clamp(shade >> FRACBITS, 0, NUMCOLORMAPS - 1)); + else + R_SetSpanColormap(&identitycolormap, 0); R_SetSpanSource(tex); if (ds_xbits != 0) { @@ -1460,6 +1510,9 @@ void DCanvas::FillSimplePoly(FTexture *tex, FVector2 *points, int npoints, // void DCanvas::DrawBlock (int x, int y, int _width, int _height, const BYTE *src) const { + if (IsBgra()) + return; + int srcpitch = _width; int destpitch; BYTE *dest; @@ -1486,6 +1539,9 @@ void DCanvas::DrawBlock (int x, int y, int _width, int _height, const BYTE *src) // void DCanvas::GetBlock (int x, int y, int _width, int _height, BYTE *dest) const { + if (IsBgra()) + return; + const BYTE *src; #ifdef RANGECHECK diff --git a/src/v_font.cpp b/src/v_font.cpp index f024e2d2b..a1794eeb1 100644 --- a/src/v_font.cpp +++ b/src/v_font.cpp @@ -1634,6 +1634,7 @@ void FFontChar1::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== @@ -1695,6 +1696,7 @@ void FFontChar2::Unload () delete[] Pixels; Pixels = NULL; } + FTexture::Unload(); } //========================================================================== diff --git a/src/v_video.cpp b/src/v_video.cpp index 6077f878e..146e2eb02 100644 --- a/src/v_video.cpp +++ b/src/v_video.cpp @@ -66,12 +66,15 @@ #include "menu/menu.h" #include "r_data/voxels.h" +EXTERN_CVAR(Bool, r_blendmethod) + int active_con_scale(); FRenderer *Renderer; IMPLEMENT_CLASS(DCanvas, true, false) IMPLEMENT_CLASS(DFrameBuffer, true, false) +EXTERN_CVAR (Bool, swtruecolor) #if defined(_DEBUG) && defined(_M_IX86) && !defined(__MINGW32__) #define DBGBREAK { __asm int 3 } @@ -84,7 +87,7 @@ class DDummyFrameBuffer : public DFrameBuffer DECLARE_CLASS (DDummyFrameBuffer, DFrameBuffer); public: DDummyFrameBuffer (int width, int height) - : DFrameBuffer (0, 0) + : DFrameBuffer (0, 0, false) { Width = width; Height = height; @@ -120,7 +123,6 @@ public: const BYTE *GetColumn(unsigned int column, const Span **spans_out); const BYTE *GetPixels(); - void Unload(); bool CheckModified(); void SetTranslation(int num); @@ -211,13 +213,14 @@ DCanvas *DCanvas::CanvasChain = NULL; // //========================================================================== -DCanvas::DCanvas (int _width, int _height) +DCanvas::DCanvas (int _width, int _height, bool _bgra) { // Init member vars Buffer = NULL; LockCount = 0; Width = _width; Height = _height; + Bgra = _bgra; // Add to list of active canvases Next = CanvasChain; @@ -347,10 +350,7 @@ void DCanvas::Dim (PalEntry color, float damount, int x1, int y1, int w, int h) if (damount == 0.f) return; - DWORD *bg2rgb; - DWORD fg; int gap; - BYTE *spot; int x, y; if (x1 >= Width || y1 >= Height) @@ -370,31 +370,100 @@ void DCanvas::Dim (PalEntry color, float damount, int x1, int y1, int w, int h) return; } - { - int amount; - - amount = (int)(damount * 64); - bg2rgb = Col2RGB8[64-amount]; - - fg = (((color.r * amount) >> 4) << 20) | - ((color.g * amount) >> 4) | - (((color.b * amount) >> 4) << 10); - } - - spot = Buffer + x1 + y1*Pitch; gap = Pitch - w; - for (y = h; y != 0; y--) - { - for (x = w; x != 0; x--) - { - DWORD bg; - bg = bg2rgb[(*spot)&0xff]; - bg = (fg+bg) | 0x1f07c1f; - *spot = RGB32k.All[bg&(bg>>15)]; - spot++; + if (IsBgra()) + { + uint32_t *spot = (uint32_t*)Buffer + x1 + y1*Pitch; + + uint32_t fg = color.d; + uint32_t fg_red = (fg >> 16) & 0xff; + uint32_t fg_green = (fg >> 8) & 0xff; + uint32_t fg_blue = fg & 0xff; + + uint32_t alpha = (uint32_t)clamp(damount * 256 + 0.5f, 0.0f, 256.0f); + uint32_t inv_alpha = 256 - alpha; + + fg_red *= alpha; + fg_green *= alpha; + fg_blue *= alpha; + + for (y = h; y != 0; y--) + { + for (x = w; x != 0; x--) + { + uint32_t bg_red = (*spot >> 16) & 0xff; + uint32_t bg_green = (*spot >> 8) & 0xff; + uint32_t bg_blue = (*spot) & 0xff; + + uint32_t red = (fg_red + bg_red * inv_alpha) / 256; + uint32_t green = (fg_green + bg_green * inv_alpha) / 256; + uint32_t blue = (fg_blue + bg_blue * inv_alpha) / 256; + + *spot = 0xff000000 | (red << 16) | (green << 8) | blue; + spot++; + } + spot += gap; + } + } + else + { + BYTE *spot = Buffer + x1 + y1*Pitch; + + DWORD *bg2rgb; + DWORD fg; + + spot = Buffer + x1 + y1*Pitch; + gap = Pitch - w; + + int alpha = (int)((float)64 * damount); + int ialpha = 64 - alpha; + int dimmedcolor_r = color.r * alpha; + int dimmedcolor_g = color.g * alpha; + int dimmedcolor_b = color.b * alpha; + + if (!r_blendmethod) + { + { + int amount; + + amount = (int)(damount * 64); + bg2rgb = Col2RGB8[64 - amount]; + + fg = (((color.r * amount) >> 4) << 20) | + ((color.g * amount) >> 4) | + (((color.b * amount) >> 4) << 10); + } + + for (y = h; y != 0; y--) + { + for (x = w; x != 0; x--) + { + DWORD bg; + + bg = bg2rgb[(*spot)&0xff]; + bg = (fg+bg) | 0x1f07c1f; + *spot = RGB32k.All[bg&(bg>>15)]; + spot++; + } + spot += gap; + } + } + else + { + for (y = h; y != 0; y--) + { + for (x = w; x != 0; x--) + { + uint32_t r = (dimmedcolor_r + GPalette.BaseColors[*spot].r * ialpha) >> 8; + uint32_t g = (dimmedcolor_g + GPalette.BaseColors[*spot].g * ialpha) >> 8; + uint32_t b = (dimmedcolor_b + GPalette.BaseColors[*spot].b * ialpha) >> 8; + *spot = (BYTE)RGB256k.RGB[r][g][b]; + spot++; + } + spot += gap; + } } - spot += gap; } } @@ -411,8 +480,8 @@ void DCanvas::GetScreenshotBuffer(const BYTE *&buffer, int &pitch, ESSType &colo { Lock(true); buffer = GetBuffer(); - pitch = GetPitch(); - color_type = SS_PAL; + pitch = IsBgra() ? GetPitch() * 4 : GetPitch(); + color_type = IsBgra() ? SS_BGRA : SS_PAL; } //========================================================================== @@ -720,13 +789,12 @@ void DCanvas::CalcGamma (float gamma, BYTE gammalookup[256]) // I found this formula on the web at // , // but that page no longer exits. - double invgamma = 1.f / gamma; int i; for (i = 0; i < 256; i++) { - gammalookup[i] = (BYTE)(255.0 * pow (i / 255.0, invgamma)); + gammalookup[i] = (BYTE)(255.0 * pow (i / 255.0, invgamma) + 0.5); } } @@ -738,8 +806,8 @@ void DCanvas::CalcGamma (float gamma, BYTE gammalookup[256]) // //========================================================================== -DSimpleCanvas::DSimpleCanvas (int width, int height) - : DCanvas (width, height) +DSimpleCanvas::DSimpleCanvas (int width, int height, bool bgra) + : DCanvas (width, height, bgra) { MemBuffer = nullptr; Resize(width, height); @@ -791,8 +859,9 @@ void DSimpleCanvas::Resize(int width, int height) Pitch = width + MAX(0, CPU.DataL1LineSize - 8); } } - MemBuffer = new BYTE[Pitch * height]; - memset(MemBuffer, 0, Pitch * height); + int bytes_per_pixel = Bgra ? 4 : 1; + MemBuffer = new BYTE[Pitch * height * bytes_per_pixel]; + memset (MemBuffer, 0, Pitch * height * bytes_per_pixel); } //========================================================================== @@ -861,8 +930,8 @@ void DSimpleCanvas::Unlock () // //========================================================================== -DFrameBuffer::DFrameBuffer (int width, int height) - : DSimpleCanvas (width, height) +DFrameBuffer::DFrameBuffer (int width, int height, bool bgra) + : DSimpleCanvas (width, height, bgra) { LastMS = LastSec = FrameCount = LastCount = LastTic = 0; Accel2D = false; @@ -871,6 +940,70 @@ DFrameBuffer::DFrameBuffer (int width, int height) VideoHeight = height; } +//========================================================================== +// +// DFrameBuffer :: PostprocessBgra +// +// Copies data to destination buffer while performing gamma and flash. +// This is only needed if a target cannot do this with shaders. +// +//========================================================================== + +void DFrameBuffer::CopyWithGammaBgra(void *output, int pitch, const BYTE *gammared, const BYTE *gammagreen, const BYTE *gammablue, PalEntry flash, int flash_amount) +{ + const BYTE *gammatables[3] = { gammared, gammagreen, gammablue }; + + if (flash_amount > 0) + { + uint16_t inv_flash_amount = 256 - flash_amount; + uint16_t flash_red = flash.r * flash_amount; + uint16_t flash_green = flash.g * flash_amount; + uint16_t flash_blue = flash.b * flash_amount; + + for (int y = 0; y < Height; y++) + { + BYTE *dest = (BYTE*)output + y * pitch; + BYTE *src = MemBuffer + y * Pitch * 4; + for (int x = 0; x < Width; x++) + { + uint16_t fg_red = src[2]; + uint16_t fg_green = src[1]; + uint16_t fg_blue = src[0]; + uint16_t red = (fg_red * inv_flash_amount + flash_red) >> 8; + uint16_t green = (fg_green * inv_flash_amount + flash_green) >> 8; + uint16_t blue = (fg_blue * inv_flash_amount + flash_blue) >> 8; + + dest[0] = gammatables[2][blue]; + dest[1] = gammatables[1][green]; + dest[2] = gammatables[0][red]; + dest[3] = 0xff; + + dest += 4; + src += 4; + } + } + } + else + { + for (int y = 0; y < Height; y++) + { + BYTE *dest = (BYTE*)output + y * pitch; + BYTE *src = MemBuffer + y * Pitch * 4; + for (int x = 0; x < Width; x++) + { + dest[0] = gammatables[2][src[0]]; + dest[1] = gammatables[1][src[1]]; + dest[2] = gammatables[0][src[2]]; + dest[3] = 0xff; + + dest += 4; + src += 4; + } + } + } +} + + //========================================================================== // // DFrameBuffer :: DrawRateStuff @@ -930,10 +1063,21 @@ void DFrameBuffer::DrawRateStuff () // Buffer can be NULL if we're doing hardware accelerated 2D if (buffer != NULL) { - buffer += (GetHeight()-1) * GetPitch(); - - for (i = 0; i < tics*2; i += 2) buffer[i] = 0xff; - for ( ; i < 20*2; i += 2) buffer[i] = 0x00; + if (IsBgra()) + { + uint32_t *buffer32 = (uint32_t*)buffer; + buffer32 += (GetHeight() - 1) * GetPitch(); + + for (i = 0; i < tics * 2; i += 2) buffer32[i] = 0xffffffff; + for (; i < 20 * 2; i += 2) buffer32[i] = 0xff000000; + } + else + { + buffer += (GetHeight() - 1) * GetPitch(); + + for (i = 0; i < tics * 2; i += 2) buffer[i] = 0xff; + for (; i < 20 * 2; i += 2) buffer[i] = 0x00; + } } else { @@ -1006,16 +1150,6 @@ void FPaletteTester::SetTranslation(int num) } } -//========================================================================== -// -// FPaletteTester :: Unload -// -//========================================================================== - -void FPaletteTester::Unload() -{ -} - //========================================================================== // // FPaletteTester :: GetColumn diff --git a/src/v_video.h b/src/v_video.h index 57d15869c..7d6a69ee4 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -187,7 +187,7 @@ class DCanvas : public DObject { DECLARE_ABSTRACT_CLASS (DCanvas, DObject) public: - DCanvas (int width, int height); + DCanvas (int width, int height, bool bgra); virtual ~DCanvas (); // Member variable access @@ -195,6 +195,7 @@ public: inline int GetWidth () const { return Width; } inline int GetHeight () const { return Height; } inline int GetPitch () const { return Pitch; } + inline bool IsBgra() const { return Bgra; } virtual bool IsValid (); @@ -272,6 +273,7 @@ protected: int Height; int Pitch; int LockCount; + bool Bgra; bool ClipBox (int &left, int &top, int &width, int &height, const BYTE *&src, const int srcpitch) const; void DrawTextureV(FTexture *img, double x, double y, uint32 tag, va_list tags) = delete; @@ -294,7 +296,7 @@ class DSimpleCanvas : public DCanvas { DECLARE_CLASS (DSimpleCanvas, DCanvas) public: - DSimpleCanvas (int width, int height); + DSimpleCanvas (int width, int height, bool bgra); ~DSimpleCanvas (); bool IsValid (); @@ -334,7 +336,7 @@ class DFrameBuffer : public DSimpleCanvas { DECLARE_ABSTRACT_CLASS (DFrameBuffer, DSimpleCanvas) public: - DFrameBuffer (int width, int height); + DFrameBuffer (int width, int height, bool bgra); // Force the surface to use buffered output if true is passed. virtual bool Lock (bool buffered) = 0; @@ -429,6 +431,7 @@ public: protected: void DrawRateStuff (); void CopyFromBuff (BYTE *src, int srcPitch, int width, int height, BYTE *dest); + void CopyWithGammaBgra(void *output, int pitch, const BYTE *gammared, const BYTE *gammagreen, const BYTE *gammablue, PalEntry flash, int flash_amount); DFrameBuffer () {} diff --git a/src/version.h b/src/version.h index ed7c02095..6e2822492 100644 --- a/src/version.h +++ b/src/version.h @@ -41,17 +41,17 @@ const char *GetVersionString(); /** Lots of different version numbers **/ -#define VERSIONSTR "2.9pre" +#define VERSIONSTR "1.2pre" // The version as seen in the Windows resource -#define RC_FILEVERSION 2,8,9999,0 -#define RC_PRODUCTVERSION 2,8,9999,0 -#define RC_PRODUCTVERSION2 "2.9pre" +#define RC_FILEVERSION 1,1,9999,0 +#define RC_PRODUCTVERSION 1,1,9999,0 +#define RC_PRODUCTVERSION2 "1.2pre" // Version identifier for network games. // Bump it every time you do a release unless you're certain you // didn't change anything that will affect sync. -#define NETGAMEVERSION 232 +#define NETGAMEVERSION 235 // Version stored in the ini's [LastRun] section. // Bump it if you made some configuration change that you want to @@ -81,15 +81,17 @@ const char *GetVersionString(); // SVN revision ever got. #define SAVEVER 4550 +#define DYNLIGHT + // This is so that derivates can use the same savegame versions without worrying about engine compatibility -#define GAMESIG "ZDOOM" -#define BASEWAD "zdoom.pk3" +#define GAMESIG "QZDOOM" +#define BASEWAD "qzdoom.pk3" // More stuff that needs to be different for derivatives. -#define GAMENAME "ZDoom" -#define GAMENAMELOWERCASE "zdoom" -#define FORUM_URL "http://forum.zdoom.org" -#define BUGS_FORUM_URL "http://forum.zdoom.org/index.php?c=3" +#define GAMENAME "QZDoom" +#define GAMENAMELOWERCASE "qzdoom" +#define FORUM_URL "http://forum.drdteam.org/viewforum.php?f=196" +#define BUGS_FORUM_URL "http://forum.drdteam.org/viewforum.php?f=197" #if defined(__APPLE__) || defined(_WIN32) #define GAME_DIR GAMENAME diff --git a/src/win32/fb_d3d9.cpp b/src/win32/fb_d3d9.cpp index 026bbc63b..f3a4e426e 100644 --- a/src/win32/fb_d3d9.cpp +++ b/src/win32/fb_d3d9.cpp @@ -242,8 +242,8 @@ CVAR(Bool, vid_hwaalines, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) // //========================================================================== -D3DFB::D3DFB (UINT adapter, int width, int height, bool fullscreen) - : BaseWinFB (width, height) +D3DFB::D3DFB (UINT adapter, int width, int height, bool bgra, bool fullscreen) + : BaseWinFB (width, height, bgra) { D3DPRESENT_PARAMETERS d3dpp; @@ -765,14 +765,16 @@ void D3DFB::KillNativeTexs() bool D3DFB::CreateFBTexture () { - if (FAILED(D3DDevice->CreateTexture(Width, Height, 1, D3DUSAGE_DYNAMIC, D3DFMT_L8, D3DPOOL_DEFAULT, &FBTexture, NULL))) + FBFormat = IsBgra() ? D3DFMT_A8R8G8B8 : D3DFMT_L8; + + if (FAILED(D3DDevice->CreateTexture(Width, Height, 1, D3DUSAGE_DYNAMIC, FBFormat, D3DPOOL_DEFAULT, &FBTexture, NULL))) { int pow2width, pow2height, i; for (i = 1; i < Width; i <<= 1) {} pow2width = i; for (i = 1; i < Height; i <<= 1) {} pow2height = i; - if (FAILED(D3DDevice->CreateTexture(pow2width, pow2height, 1, D3DUSAGE_DYNAMIC, D3DFMT_L8, D3DPOOL_DEFAULT, &FBTexture, NULL))) + if (FAILED(D3DDevice->CreateTexture(pow2width, pow2height, 1, D3DUSAGE_DYNAMIC, FBFormat, D3DPOOL_DEFAULT, &FBTexture, NULL))) { return false; } @@ -1323,20 +1325,45 @@ void D3DFB::Draw3DPart(bool copy3d) SUCCEEDED(FBTexture->LockRect (0, &lockrect, NULL, D3DLOCK_DISCARD))) || SUCCEEDED(FBTexture->LockRect (0, &lockrect, &texrect, 0))) { - if (lockrect.Pitch == Pitch && Pitch == Width) + if (IsBgra() && FBFormat == D3DFMT_A8R8G8B8) { - memcpy (lockrect.pBits, MemBuffer, Width * Height); + if (lockrect.Pitch == Pitch * sizeof(uint32_t) && Pitch == Width) + { + memcpy(lockrect.pBits, MemBuffer, Width * Height * sizeof(uint32_t)); + } + else + { + uint32_t *dest = (uint32_t *)lockrect.pBits; + uint32_t *src = (uint32_t*)MemBuffer; + for (int y = 0; y < Height; y++) + { + memcpy(dest, src, Width * sizeof(uint32_t)); + dest = reinterpret_cast(reinterpret_cast(dest) + lockrect.Pitch); + src += Pitch; + } + } + } + else if (!IsBgra() && FBFormat == D3DFMT_L8) + { + if (lockrect.Pitch == Pitch && Pitch == Width) + { + memcpy(lockrect.pBits, MemBuffer, Width * Height); + } + else + { + BYTE *dest = (BYTE *)lockrect.pBits; + BYTE *src = (BYTE *)MemBuffer; + for (int y = 0; y < Height; y++) + { + memcpy(dest, src, Width); + dest = reinterpret_cast(reinterpret_cast(dest) + lockrect.Pitch); + src += Pitch; + } + } } else { - BYTE *dest = (BYTE *)lockrect.pBits; - BYTE *src = MemBuffer; - for (int y = 0; y < Height; y++) - { - memcpy (dest, src, Width); - dest += lockrect.Pitch; - src += Pitch; - } + memset(lockrect.pBits, 0, lockrect.Pitch * Height); } FBTexture->UnlockRect (0); } @@ -1368,7 +1395,10 @@ void D3DFB::Draw3DPart(bool copy3d) memset(Constant, 0, sizeof(Constant)); SetAlphaBlend(D3DBLENDOP(0)); EnableAlphaTest(FALSE); - SetPixelShader(Shaders[SHADER_NormalColorPal]); + if (IsBgra()) + SetPixelShader(Shaders[SHADER_NormalColor]); + else + SetPixelShader(Shaders[SHADER_NormalColorPal]); if (copy3d) { FBVERTEX verts[4]; @@ -1383,9 +1413,12 @@ void D3DFB::Draw3DPart(bool copy3d) } else { - color0 = D3DCOLOR_COLORVALUE(map->ColorizeStart[0] / 2, map->ColorizeStart[1] / 2, map->ColorizeStart[2] / 2, 0); - color1 = D3DCOLOR_COLORVALUE(map->ColorizeEnd[0] / 2, map->ColorizeEnd[1] / 2, map->ColorizeEnd[2] / 2, 1); - SetPixelShader(Shaders[SHADER_SpecialColormapPal]); + color0 = D3DCOLOR_COLORVALUE(map->ColorizeStart[0]/2, map->ColorizeStart[1]/2, map->ColorizeStart[2]/2, 0); + color1 = D3DCOLOR_COLORVALUE(map->ColorizeEnd[0]/2, map->ColorizeEnd[1]/2, map->ColorizeEnd[2]/2, 1); + if (IsBgra()) + SetPixelShader(Shaders[SHADER_SpecialColormap]); + else + SetPixelShader(Shaders[SHADER_SpecialColormapPal]); } } else @@ -1396,7 +1429,10 @@ void D3DFB::Draw3DPart(bool copy3d) CalcFullscreenCoords(verts, Accel2D, false, color0, color1); D3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, verts, sizeof(FBVERTEX)); } - SetPixelShader(Shaders[SHADER_NormalColorPal]); + if (IsBgra()) + SetPixelShader(Shaders[SHADER_NormalColor]); + else + SetPixelShader(Shaders[SHADER_NormalColorPal]); } //========================================================================== diff --git a/src/win32/fb_ddraw.cpp b/src/win32/fb_ddraw.cpp index 85f0c4768..5b50f146c 100644 --- a/src/win32/fb_ddraw.cpp +++ b/src/win32/fb_ddraw.cpp @@ -32,7 +32,6 @@ ** */ - // HEADER FILES ------------------------------------------------------------ #define DIRECTDRAW_VERSION 0x0300 @@ -120,7 +119,7 @@ cycle_t BlitCycles; // CODE -------------------------------------------------------------------- DDrawFB::DDrawFB (int width, int height, bool fullscreen) - : BaseWinFB (width, height) + : BaseWinFB (width, height, false) { int i; diff --git a/src/win32/hardware.cpp b/src/win32/hardware.cpp index 8cc770556..609f56647 100644 --- a/src/win32/hardware.cpp +++ b/src/win32/hardware.cpp @@ -51,7 +51,9 @@ EXTERN_CVAR (Bool, ticker) EXTERN_CVAR (Bool, fullscreen) +EXTERN_CVAR (Bool, swtruecolor) EXTERN_CVAR (Float, vid_winscale) +EXTERN_CVAR (Bool, vid_forceddraw) CVAR(Int, win_x, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) CVAR(Int, win_y, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG) @@ -62,6 +64,53 @@ bool ForceWindowed; IVideo *Video; +// do not include GL headers here, only declare the necessary functions. +IVideo *gl_CreateVideo(); +FRenderer *gl_CreateInterface(); + +void I_RestartRenderer(); +int currentrenderer = -1; +int currentcanvas = -1; +bool changerenderer; + +// Software OpenGL canvas +CUSTOM_CVAR(Bool, vid_used3d, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + if ((self ? 1 : 0) != currentcanvas) + Printf("You must restart " GAMENAME " for this change to take effect.\n"); +} + +// [ZDoomGL] +CUSTOM_CVAR (Int, vid_renderer, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + // 0: Software renderer + // 1: OpenGL renderer + + if (self != currentrenderer) + { + switch (self) + { + case 0: + Printf("Switching to software renderer...\n"); + break; + case 1: + Printf("Switching to OpenGL renderer...\n"); + break; + default: + Printf("Unknown renderer (%d). Falling back to software renderer...\n", *vid_renderer); + self = 0; // make sure to actually switch to the software renderer + break; + } + //changerenderer = true; + Printf("You must restart " GAMENAME " to switch the renderer\n"); + } +} + +CCMD (vid_restart) +{ +} + + void I_ShutdownGraphics () { if (screen) @@ -94,15 +143,22 @@ void I_InitGraphics () // not receive a WM_ACTIVATEAPP message, so both games think they // are the active app. Huh? } - val.Bool = !!Args->CheckParm ("-devparm"); ticker.SetGenericRepDefault (val, CVAR_Bool); - Video = new Win32Video (0); + + if (currentcanvas == 1) // Software Canvas: 1 = D3D or DirectDraw, 0 = OpenGL + if (currentrenderer == 1) + Video = gl_CreateVideo(); + else + Video = new Win32Video(0); + else + Video = gl_CreateVideo(); + if (Video == NULL) I_FatalError ("Failed to initialize display"); - + atterm (I_ShutdownGraphics); - + Video->SetWindowedScale (vid_winscale); } @@ -113,9 +169,22 @@ static void I_DeleteRenderer() void I_CreateRenderer() { + currentrenderer = vid_renderer; + currentcanvas = vid_used3d; + if (currentrenderer == 1) + Printf("Renderer: OpenGL\n"); + else if (currentcanvas == 0) + Printf("Renderer: Software on OpenGL\n"); + else if (currentcanvas == 1 && vid_forceddraw == false) + Printf("Renderer: Software on Direct3D\n"); + else if (currentcanvas == 1) + Printf("Renderer: Software on DirectDraw\n"); + else + Printf("Renderer: Unknown\n"); if (Renderer == NULL) { - Renderer = new FSoftwareRenderer; + if (currentrenderer==1) Renderer = gl_CreateInterface(); + else Renderer = new FSoftwareRenderer; atterm(I_DeleteRenderer); } } @@ -146,14 +215,14 @@ DFrameBuffer *I_SetMode (int &width, int &height, DFrameBuffer *old) } break; } - DFrameBuffer *res = Video->CreateFrameBuffer (width, height, fs, old); + DFrameBuffer *res = Video->CreateFrameBuffer (width, height, swtruecolor, fs, old); - /* Right now, CreateFrameBuffer cannot return NULL + //* Right now, CreateFrameBuffer cannot return NULL if (res == NULL) { I_FatalError ("Mode %dx%d is unavailable\n", width, height); } - */ + //*/ return res; } @@ -255,7 +324,8 @@ void I_SaveWindowedPos () return; } // Make sure we only save the window position if it's not fullscreen. - if ((GetWindowLong (Window, GWL_STYLE) & WS_OVERLAPPEDWINDOW) == WS_OVERLAPPEDWINDOW) + static const int WINDOW_STYLE = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX; + if ((GetWindowLong (Window, GWL_STYLE) & WINDOW_STYLE) == WINDOW_STYLE) { RECT wrect; @@ -312,7 +382,17 @@ void I_RestoreWindowedPos () extern int NewWidth, NewHeight, NewBits, DisplayBits; -CUSTOM_CVAR (Bool, fullscreen, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +CUSTOM_CVAR(Bool, swtruecolor, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) +{ + // Strictly speaking this doesn't require a mode switch, but it is the easiest + // way to force a CreateFramebuffer call without a lot of refactoring. + NewWidth = screen->GetWidth(); + NewHeight = screen->GetHeight(); + NewBits = DisplayBits; + setmodeneeded = true; +} + +CUSTOM_CVAR (Bool, fullscreen, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG|CVAR_NOINITCALL) { NewWidth = screen->GetWidth(); NewHeight = screen->GetHeight(); @@ -332,7 +412,7 @@ CUSTOM_CVAR (Float, vid_winscale, 1.f, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) NewWidth = screen->GetWidth(); NewHeight = screen->GetHeight(); NewBits = DisplayBits; - setmodeneeded = true; + //setmodeneeded = true; // This CVAR doesn't do anything and only causes problems! } } diff --git a/src/win32/hardware.h b/src/win32/hardware.h index b2bafef32..184eeccf5 100644 --- a/src/win32/hardware.h +++ b/src/win32/hardware.h @@ -45,7 +45,7 @@ class IVideo virtual EDisplayType GetDisplayType () = 0; virtual void SetWindowedScale (float scale) = 0; - virtual DFrameBuffer *CreateFrameBuffer (int width, int height, bool fs, DFrameBuffer *old) = 0; + virtual DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old) = 0; virtual void StartModeIterator (int bits, bool fs) = 0; virtual bool NextMode (int *width, int *height, bool *letterbox) = 0; diff --git a/src/win32/i_crash.cpp b/src/win32/i_crash.cpp index 4a0a1b160..57c93d768 100644 --- a/src/win32/i_crash.cpp +++ b/src/win32/i_crash.cpp @@ -3351,3 +3351,111 @@ void DisplayCrashLog () } CloseTarFiles (); } + +///////////////////////////////////////////////////////////////////////////// + +namespace +{ + bool __declspec(thread) DrawerExceptionSetJumpResult; + CONTEXT __declspec(thread) DrawerExceptionSetJumpContext; + PVOID __declspec(thread) DrawerExceptionHandlerHandle; + char __declspec(thread) *DrawerExceptionReason; + bool __declspec(thread) DrawerExceptionFatal; + + LONG WINAPI DrawerExceptionHandler(_EXCEPTION_POINTERS *exceptionInfo) + { + *exceptionInfo->ContextRecord = DrawerExceptionSetJumpContext; + + DrawerExceptionFatal = false; + switch (exceptionInfo->ExceptionRecord->ExceptionCode) + { + default: DrawerExceptionReason = "Unknown exception code"; break; + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: DrawerExceptionReason = "Array bounds exceeded"; break; + case EXCEPTION_BREAKPOINT: DrawerExceptionReason = "Breakpoint"; break; + case EXCEPTION_DATATYPE_MISALIGNMENT: DrawerExceptionReason = "Datatype misalignment"; break; + case EXCEPTION_FLT_DENORMAL_OPERAND: DrawerExceptionReason = "Float denormal operand"; break; + case EXCEPTION_FLT_DIVIDE_BY_ZERO: DrawerExceptionReason = "Float divide by zero"; break; + case EXCEPTION_FLT_INEXACT_RESULT: DrawerExceptionReason = "Float inexact result"; break; + case EXCEPTION_FLT_INVALID_OPERATION: DrawerExceptionReason = "Float invalid operation"; break; + case EXCEPTION_FLT_OVERFLOW: DrawerExceptionReason = "Float overflow"; break; + case EXCEPTION_FLT_STACK_CHECK: DrawerExceptionReason = "Float stack check"; break; + case EXCEPTION_FLT_UNDERFLOW: DrawerExceptionReason = "Float underflow"; break; + case EXCEPTION_INT_DIVIDE_BY_ZERO: DrawerExceptionReason = "Int divide by zero"; break; + case EXCEPTION_INT_OVERFLOW: DrawerExceptionReason = "Int overflow"; break; + case EXCEPTION_INVALID_DISPOSITION: DrawerExceptionReason = "Invalid disposition"; break; + case EXCEPTION_NONCONTINUABLE_EXCEPTION: DrawerExceptionReason = "Noncontinuable exception"; break; + case EXCEPTION_PRIV_INSTRUCTION: DrawerExceptionReason = "Priv instruction"; break; + case EXCEPTION_SINGLE_STEP: DrawerExceptionReason = "Single step"; break; + case EXCEPTION_STACK_OVERFLOW: DrawerExceptionReason = "Stack overflow"; break; + + case EXCEPTION_ILLEGAL_INSTRUCTION: + DrawerExceptionReason = "Illegal instruction"; + DrawerExceptionFatal = true; + break; + + case EXCEPTION_ACCESS_VIOLATION: + if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 0) + { + DrawerExceptionReason = "Read access violation"; + } + else if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 1) + { + DrawerExceptionReason = "Write access violation"; + DrawerExceptionFatal = true; + } + else if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 8) + { + DrawerExceptionReason = "User-mode data execution prevention (DEP) violation"; + DrawerExceptionFatal = true; + } + else + { + DrawerExceptionReason = "Unknown access violation"; + DrawerExceptionFatal = true; + } + break; + + case EXCEPTION_IN_PAGE_ERROR: + if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 0) + { + DrawerExceptionReason = "In page read error"; + } + else if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 1) + { + DrawerExceptionReason = "In page write error"; + DrawerExceptionFatal = true; + } + else if (exceptionInfo->ExceptionRecord->ExceptionInformation[0] == 8) + { + DrawerExceptionReason = "In page user-mode data execution prevention (DEP) error"; + DrawerExceptionFatal = true; + } + else + { + DrawerExceptionReason = "Unknown in page read error"; + DrawerExceptionFatal = true; + } + break; + } + + return EXCEPTION_CONTINUE_EXECUTION; + } +} + +void VectoredTryCatch(void *data, void(*tryBlock)(void *data), void(*catchBlock)(void *data, const char *reason, bool fatal)) +{ + DrawerExceptionSetJumpResult = false; + RtlCaptureContext(&DrawerExceptionSetJumpContext); + if (DrawerExceptionSetJumpResult) + { + RemoveVectoredExceptionHandler(DrawerExceptionHandlerHandle); + catchBlock(data, DrawerExceptionReason, DrawerExceptionFatal); + } + else + { + DrawerExceptionSetJumpResult = true; + DrawerExceptionHandlerHandle = AddVectoredExceptionHandler(1, DrawerExceptionHandler); + tryBlock(data); + RemoveVectoredExceptionHandler(DrawerExceptionHandlerHandle); + } +} diff --git a/src/win32/i_system.cpp b/src/win32/i_system.cpp index 99ed4fa94..f07fb8f1d 100644 --- a/src/win32/i_system.cpp +++ b/src/win32/i_system.cpp @@ -4,6 +4,8 @@ ** **--------------------------------------------------------------------------- ** Copyright 1998-2009 Randy Heit +** Copyright (C) 2007-2012 Skulltag Development Team +** Copyright (C) 2007-2016 Zandronum Development Team ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without @@ -17,6 +19,15 @@ ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. +** 4. Redistributions in any form must be accompanied by information on how to +** obtain complete source code for the software and any accompanying software +** that uses the software. The source code must either be included in the +** distribution or be available for no more than the cost of distribution plus +** a nominal fee, and must be freely redistributable under reasonable +** conditions. For an executable file, complete source code means the source +** code for all modules it contains. It does not include source code for +** modules or files that typically accompany the major components of the +** operating system on which the executable file runs. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES @@ -127,6 +138,12 @@ static void DestroyCustomCursor(); EXTERN_CVAR(String, language); EXTERN_CVAR (Bool, queryiwad); +// Used on welcome/IWAD screen. +EXTERN_CVAR (Int, vid_renderer) +EXTERN_CVAR (Bool, fullscreen) +EXTERN_CVAR (Bool, disableautoload) +EXTERN_CVAR (Bool, autoloadlights) +EXTERN_CVAR (Bool, autoloadbrightmaps) extern HWND Window, ConWindow, GameTitleWindow; extern HANDLE StdOut; @@ -1159,6 +1176,23 @@ BOOL CALLBACK IWADBoxCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa newlabel.Format(GAMESIG " %s: %s", GetVersionString(), label); SetWindowText(hDlg, newlabel.GetChars()); } + + // [SP] Upstreamed from Zandronum + char szString[256]; + + // Check the current video settings. + SendDlgItemMessage( hDlg, vid_renderer ? IDC_WELCOME_OPENGL : IDC_WELCOME_SOFTWARE, BM_SETCHECK, BST_CHECKED, 0 ); + SendDlgItemMessage( hDlg, IDC_WELCOME_FULLSCREEN, BM_SETCHECK, fullscreen ? BST_CHECKED : BST_UNCHECKED, 0 ); + + // [SP] This is our's + SendDlgItemMessage( hDlg, IDC_WELCOME_NOAUTOLOAD, BM_SETCHECK, disableautoload ? BST_CHECKED : BST_UNCHECKED, 0 ); + SendDlgItemMessage( hDlg, IDC_WELCOME_LIGHTS, BM_SETCHECK, autoloadlights ? BST_CHECKED : BST_UNCHECKED, 0 ); + SendDlgItemMessage( hDlg, IDC_WELCOME_BRIGHTMAPS, BM_SETCHECK, autoloadbrightmaps ? BST_CHECKED : BST_UNCHECKED, 0 ); + + // Set up our version string. + sprintf(szString, "Version %s.", GetVersionString()); + SetDlgItemText (hDlg, IDC_WELCOME_VERSION, szString); + // Populate the list with all the IWADs found ctrl = GetDlgItem(hDlg, IDC_IWADLIST); for (i = 0; i < NumWads; i++) @@ -1192,6 +1226,14 @@ BOOL CALLBACK IWADBoxCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa (LOWORD(wParam) == IDC_IWADLIST && HIWORD(wParam) == LBN_DBLCLK)) { SetQueryIWad(hDlg); + // [SP] Upstreamed from Zandronum + vid_renderer = SendDlgItemMessage( hDlg, IDC_WELCOME_OPENGL, BM_GETCHECK, 0, 0 ) == BST_CHECKED; + fullscreen = SendDlgItemMessage( hDlg, IDC_WELCOME_FULLSCREEN, BM_GETCHECK, 0, 0 ) == BST_CHECKED; + + // [SP] This is our's. + disableautoload = SendDlgItemMessage( hDlg, IDC_WELCOME_NOAUTOLOAD, BM_GETCHECK, 0, 0 ) == BST_CHECKED; + autoloadlights = SendDlgItemMessage( hDlg, IDC_WELCOME_LIGHTS, BM_GETCHECK, 0, 0 ) == BST_CHECKED; + autoloadbrightmaps = SendDlgItemMessage( hDlg, IDC_WELCOME_BRIGHTMAPS, BM_GETCHECK, 0, 0 ) == BST_CHECKED; ctrl = GetDlgItem (hDlg, IDC_IWADLIST); EndDialog(hDlg, SendMessage (ctrl, LB_GETCURSEL, 0, 0)); } @@ -1456,11 +1498,11 @@ static HCURSOR CreateBitmapCursor(int xhot, int yhot, HBITMAP and_mask, HBITMAP { ICONINFO iconinfo = { - FALSE, // fIcon + FALSE, // fIcon (DWORD)xhot, // xHotspot (DWORD)yhot, // yHotspot - and_mask, // hbmMask - color_mask // hbmColor + and_mask, // hbmMask + color_mask // hbmColor }; HCURSOR cursor = CreateIconIndirect(&iconinfo); diff --git a/src/win32/resource.h b/src/win32/resource.h index 6886e83fd..cf41b6f1f 100644 --- a/src/win32/resource.h +++ b/src/win32/resource.h @@ -158,9 +158,20 @@ // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 150 +#define _APS_NEXT_RESOURCE_VALUE 151 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1084 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif + +// [SP] Upstreamed from Zandronum +#define IDC_WELCOME_VERSION 4019 // [RC] "Welcome" screen. +#define IDC_WELCOME_OPENGL 4020 +#define IDC_WELCOME_SOFTWARE 4021 +#define IDC_WELCOME_FULLSCREEN 4022 + +// [SP] This is our's. +#define IDC_WELCOME_NOAUTOLOAD 4023 +#define IDC_WELCOME_LIGHTS 4024 +#define IDC_WELCOME_BRIGHTMAPS 4025 diff --git a/src/win32/wglext.h b/src/win32/wglext.h new file mode 100644 index 000000000..daba41091 --- /dev/null +++ b/src/win32/wglext.h @@ -0,0 +1,840 @@ +#ifndef __wglext_h_ +#define __wglext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright (c) 2013-2014 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ +/* +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** http://www.opengl.org/registry/ +** +** Khronos $Revision: 27684 $ on $Date: 2014-08-11 01:21:35 -0700 (Mon, 11 Aug 2014) $ +*/ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#define WIN32_LEAN_AND_MEAN 1 +#include +#endif + +#define WGL_WGLEXT_VERSION 20140810 + +/* Generated C header for: + * API: wgl + * Versions considered: .* + * Versions emitted: _nomatch_^ + * Default extensions included: wgl + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef WGL_ARB_buffer_region +#define WGL_ARB_buffer_region 1 +#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001 +#define WGL_BACK_COLOR_BUFFER_BIT_ARB 0x00000002 +#define WGL_DEPTH_BUFFER_BIT_ARB 0x00000004 +#define WGL_STENCIL_BUFFER_BIT_ARB 0x00000008 +typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType); +typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion); +typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height); +typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc); +#ifdef WGL_WGLEXT_PROTOTYPES +HANDLE WINAPI wglCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType); +VOID WINAPI wglDeleteBufferRegionARB (HANDLE hRegion); +BOOL WINAPI wglSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height); +BOOL WINAPI wglRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc); +#endif +#endif /* WGL_ARB_buffer_region */ + +#ifndef WGL_ARB_context_flush_control +#define WGL_ARB_context_flush_control 1 +#define WGL_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097 +#define WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0 +#define WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098 +#endif /* WGL_ARB_context_flush_control */ + +#ifndef WGL_ARB_create_context +#define WGL_ARB_create_context 1 +#define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001 +#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 +#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 +#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093 +#define WGL_CONTEXT_FLAGS_ARB 0x2094 +#define ERROR_INVALID_VERSION_ARB 0x2095 +typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList); +#ifdef WGL_WGLEXT_PROTOTYPES +HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList); +#endif +#endif /* WGL_ARB_create_context */ + +#ifndef WGL_ARB_create_context_profile +#define WGL_ARB_create_context_profile 1 +#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 +#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 +#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 +#define ERROR_INVALID_PROFILE_ARB 0x2096 +#endif /* WGL_ARB_create_context_profile */ + +#ifndef WGL_ARB_create_context_robustness +#define WGL_ARB_create_context_robustness 1 +#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 +#define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 +#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 +#define WGL_NO_RESET_NOTIFICATION_ARB 0x8261 +#endif /* WGL_ARB_create_context_robustness */ + +#ifndef WGL_ARB_extensions_string +#define WGL_ARB_extensions_string 1 +typedef const char *(WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc); +#ifdef WGL_WGLEXT_PROTOTYPES +const char *WINAPI wglGetExtensionsStringARB (HDC hdc); +#endif +#endif /* WGL_ARB_extensions_string */ + +#ifndef WGL_ARB_framebuffer_sRGB +#define WGL_ARB_framebuffer_sRGB 1 +#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9 +#endif /* WGL_ARB_framebuffer_sRGB */ + +#ifndef WGL_ARB_make_current_read +#define WGL_ARB_make_current_read 1 +#define ERROR_INVALID_PIXEL_TYPE_ARB 0x2043 +#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054 +typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); +typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); +HDC WINAPI wglGetCurrentReadDCARB (void); +#endif +#endif /* WGL_ARB_make_current_read */ + +#ifndef WGL_ARB_multisample +#define WGL_ARB_multisample 1 +#define WGL_SAMPLE_BUFFERS_ARB 0x2041 +#define WGL_SAMPLES_ARB 0x2042 +#endif /* WGL_ARB_multisample */ + +#ifndef WGL_ARB_pbuffer +#define WGL_ARB_pbuffer 1 +DECLARE_HANDLE(HPBUFFERARB); +#define WGL_DRAW_TO_PBUFFER_ARB 0x202D +#define WGL_MAX_PBUFFER_PIXELS_ARB 0x202E +#define WGL_MAX_PBUFFER_WIDTH_ARB 0x202F +#define WGL_MAX_PBUFFER_HEIGHT_ARB 0x2030 +#define WGL_PBUFFER_LARGEST_ARB 0x2033 +#define WGL_PBUFFER_WIDTH_ARB 0x2034 +#define WGL_PBUFFER_HEIGHT_ARB 0x2035 +#define WGL_PBUFFER_LOST_ARB 0x2036 +typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); +typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer); +typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC); +typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer); +typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue); +#ifdef WGL_WGLEXT_PROTOTYPES +HPBUFFERARB WINAPI wglCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); +HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB hPbuffer); +int WINAPI wglReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC); +BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB hPbuffer); +BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue); +#endif +#endif /* WGL_ARB_pbuffer */ + +#ifndef WGL_ARB_pixel_format +#define WGL_ARB_pixel_format 1 +#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000 +#define WGL_DRAW_TO_WINDOW_ARB 0x2001 +#define WGL_DRAW_TO_BITMAP_ARB 0x2002 +#define WGL_ACCELERATION_ARB 0x2003 +#define WGL_NEED_PALETTE_ARB 0x2004 +#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005 +#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006 +#define WGL_SWAP_METHOD_ARB 0x2007 +#define WGL_NUMBER_OVERLAYS_ARB 0x2008 +#define WGL_NUMBER_UNDERLAYS_ARB 0x2009 +#define WGL_TRANSPARENT_ARB 0x200A +#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037 +#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038 +#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039 +#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A +#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B +#define WGL_SHARE_DEPTH_ARB 0x200C +#define WGL_SHARE_STENCIL_ARB 0x200D +#define WGL_SHARE_ACCUM_ARB 0x200E +#define WGL_SUPPORT_GDI_ARB 0x200F +#define WGL_SUPPORT_OPENGL_ARB 0x2010 +#define WGL_DOUBLE_BUFFER_ARB 0x2011 +#define WGL_STEREO_ARB 0x2012 +#define WGL_PIXEL_TYPE_ARB 0x2013 +#define WGL_COLOR_BITS_ARB 0x2014 +#define WGL_RED_BITS_ARB 0x2015 +#define WGL_RED_SHIFT_ARB 0x2016 +#define WGL_GREEN_BITS_ARB 0x2017 +#define WGL_GREEN_SHIFT_ARB 0x2018 +#define WGL_BLUE_BITS_ARB 0x2019 +#define WGL_BLUE_SHIFT_ARB 0x201A +#define WGL_ALPHA_BITS_ARB 0x201B +#define WGL_ALPHA_SHIFT_ARB 0x201C +#define WGL_ACCUM_BITS_ARB 0x201D +#define WGL_ACCUM_RED_BITS_ARB 0x201E +#define WGL_ACCUM_GREEN_BITS_ARB 0x201F +#define WGL_ACCUM_BLUE_BITS_ARB 0x2020 +#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021 +#define WGL_DEPTH_BITS_ARB 0x2022 +#define WGL_STENCIL_BITS_ARB 0x2023 +#define WGL_AUX_BUFFERS_ARB 0x2024 +#define WGL_NO_ACCELERATION_ARB 0x2025 +#define WGL_GENERIC_ACCELERATION_ARB 0x2026 +#define WGL_FULL_ACCELERATION_ARB 0x2027 +#define WGL_SWAP_EXCHANGE_ARB 0x2028 +#define WGL_SWAP_COPY_ARB 0x2029 +#define WGL_SWAP_UNDEFINED_ARB 0x202A +#define WGL_TYPE_RGBA_ARB 0x202B +#define WGL_TYPE_COLORINDEX_ARB 0x202C +typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues); +typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues); +typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues); +BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues); +BOOL WINAPI wglChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); +#endif +#endif /* WGL_ARB_pixel_format */ + +#ifndef WGL_ARB_pixel_format_float +#define WGL_ARB_pixel_format_float 1 +#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0 +#endif /* WGL_ARB_pixel_format_float */ + +#ifndef WGL_ARB_render_texture +#define WGL_ARB_render_texture 1 +#define WGL_BIND_TO_TEXTURE_RGB_ARB 0x2070 +#define WGL_BIND_TO_TEXTURE_RGBA_ARB 0x2071 +#define WGL_TEXTURE_FORMAT_ARB 0x2072 +#define WGL_TEXTURE_TARGET_ARB 0x2073 +#define WGL_MIPMAP_TEXTURE_ARB 0x2074 +#define WGL_TEXTURE_RGB_ARB 0x2075 +#define WGL_TEXTURE_RGBA_ARB 0x2076 +#define WGL_NO_TEXTURE_ARB 0x2077 +#define WGL_TEXTURE_CUBE_MAP_ARB 0x2078 +#define WGL_TEXTURE_1D_ARB 0x2079 +#define WGL_TEXTURE_2D_ARB 0x207A +#define WGL_MIPMAP_LEVEL_ARB 0x207B +#define WGL_CUBE_MAP_FACE_ARB 0x207C +#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D +#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E +#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F +#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080 +#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081 +#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082 +#define WGL_FRONT_LEFT_ARB 0x2083 +#define WGL_FRONT_RIGHT_ARB 0x2084 +#define WGL_BACK_LEFT_ARB 0x2085 +#define WGL_BACK_RIGHT_ARB 0x2086 +#define WGL_AUX0_ARB 0x2087 +#define WGL_AUX1_ARB 0x2088 +#define WGL_AUX2_ARB 0x2089 +#define WGL_AUX3_ARB 0x208A +#define WGL_AUX4_ARB 0x208B +#define WGL_AUX5_ARB 0x208C +#define WGL_AUX6_ARB 0x208D +#define WGL_AUX7_ARB 0x208E +#define WGL_AUX8_ARB 0x208F +#define WGL_AUX9_ARB 0x2090 +typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer); +typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer); +typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer); +BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer); +BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList); +#endif +#endif /* WGL_ARB_render_texture */ + +#ifndef WGL_ARB_robustness_application_isolation +#define WGL_ARB_robustness_application_isolation 1 +#define WGL_CONTEXT_RESET_ISOLATION_BIT_ARB 0x00000008 +#endif /* WGL_ARB_robustness_application_isolation */ + +#ifndef WGL_ARB_robustness_share_group_isolation +#define WGL_ARB_robustness_share_group_isolation 1 +#endif /* WGL_ARB_robustness_share_group_isolation */ + +#ifndef WGL_3DFX_multisample +#define WGL_3DFX_multisample 1 +#define WGL_SAMPLE_BUFFERS_3DFX 0x2060 +#define WGL_SAMPLES_3DFX 0x2061 +#endif /* WGL_3DFX_multisample */ + +#ifndef WGL_3DL_stereo_control +#define WGL_3DL_stereo_control 1 +#define WGL_STEREO_EMITTER_ENABLE_3DL 0x2055 +#define WGL_STEREO_EMITTER_DISABLE_3DL 0x2056 +#define WGL_STEREO_POLARITY_NORMAL_3DL 0x2057 +#define WGL_STEREO_POLARITY_INVERT_3DL 0x2058 +typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglSetStereoEmitterState3DL (HDC hDC, UINT uState); +#endif +#endif /* WGL_3DL_stereo_control */ + +#ifndef WGL_AMD_gpu_association +#define WGL_AMD_gpu_association 1 +#define WGL_GPU_VENDOR_AMD 0x1F00 +#define WGL_GPU_RENDERER_STRING_AMD 0x1F01 +#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02 +#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2 +#define WGL_GPU_RAM_AMD 0x21A3 +#define WGL_GPU_CLOCK_AMD 0x21A4 +#define WGL_GPU_NUM_PIPES_AMD 0x21A5 +#define WGL_GPU_NUM_SIMD_AMD 0x21A6 +#define WGL_GPU_NUM_RB_AMD 0x21A7 +#define WGL_GPU_NUM_SPI_AMD 0x21A8 +typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids); +typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data); +typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc); +typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id); +typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList); +typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc); +typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc); +typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void); +typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef WGL_WGLEXT_PROTOTYPES +UINT WINAPI wglGetGPUIDsAMD (UINT maxCount, UINT *ids); +INT WINAPI wglGetGPUInfoAMD (UINT id, int property, GLenum dataType, UINT size, void *data); +UINT WINAPI wglGetContextGPUIDAMD (HGLRC hglrc); +HGLRC WINAPI wglCreateAssociatedContextAMD (UINT id); +HGLRC WINAPI wglCreateAssociatedContextAttribsAMD (UINT id, HGLRC hShareContext, const int *attribList); +BOOL WINAPI wglDeleteAssociatedContextAMD (HGLRC hglrc); +BOOL WINAPI wglMakeAssociatedContextCurrentAMD (HGLRC hglrc); +HGLRC WINAPI wglGetCurrentAssociatedContextAMD (void); +VOID WINAPI wglBlitContextFramebufferAMD (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* WGL_AMD_gpu_association */ + +#ifndef WGL_ATI_pixel_format_float +#define WGL_ATI_pixel_format_float 1 +#define WGL_TYPE_RGBA_FLOAT_ATI 0x21A0 +#endif /* WGL_ATI_pixel_format_float */ + +#ifndef WGL_EXT_create_context_es2_profile +#define WGL_EXT_create_context_es2_profile 1 +#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004 +#endif /* WGL_EXT_create_context_es2_profile */ + +#ifndef WGL_EXT_create_context_es_profile +#define WGL_EXT_create_context_es_profile 1 +#define WGL_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004 +#endif /* WGL_EXT_create_context_es_profile */ + +#ifndef WGL_EXT_depth_float +#define WGL_EXT_depth_float 1 +#define WGL_DEPTH_FLOAT_EXT 0x2040 +#endif /* WGL_EXT_depth_float */ + +#ifndef WGL_EXT_display_color_table +#define WGL_EXT_display_color_table 1 +typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id); +typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length); +typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id); +typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id); +#ifdef WGL_WGLEXT_PROTOTYPES +GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort id); +GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *table, GLuint length); +GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort id); +VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort id); +#endif +#endif /* WGL_EXT_display_color_table */ + +#ifndef WGL_EXT_extensions_string +#define WGL_EXT_extensions_string 1 +typedef const char *(WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void); +#ifdef WGL_WGLEXT_PROTOTYPES +const char *WINAPI wglGetExtensionsStringEXT (void); +#endif +#endif /* WGL_EXT_extensions_string */ + +#ifndef WGL_EXT_framebuffer_sRGB +#define WGL_EXT_framebuffer_sRGB 1 +#define WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20A9 +#endif /* WGL_EXT_framebuffer_sRGB */ + +#ifndef WGL_EXT_make_current_read +#define WGL_EXT_make_current_read 1 +#define ERROR_INVALID_PIXEL_TYPE_EXT 0x2043 +typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); +typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); +HDC WINAPI wglGetCurrentReadDCEXT (void); +#endif +#endif /* WGL_EXT_make_current_read */ + +#ifndef WGL_EXT_multisample +#define WGL_EXT_multisample 1 +#define WGL_SAMPLE_BUFFERS_EXT 0x2041 +#define WGL_SAMPLES_EXT 0x2042 +#endif /* WGL_EXT_multisample */ + +#ifndef WGL_EXT_pbuffer +#define WGL_EXT_pbuffer 1 +DECLARE_HANDLE(HPBUFFEREXT); +#define WGL_DRAW_TO_PBUFFER_EXT 0x202D +#define WGL_MAX_PBUFFER_PIXELS_EXT 0x202E +#define WGL_MAX_PBUFFER_WIDTH_EXT 0x202F +#define WGL_MAX_PBUFFER_HEIGHT_EXT 0x2030 +#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT 0x2031 +#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032 +#define WGL_PBUFFER_LARGEST_EXT 0x2033 +#define WGL_PBUFFER_WIDTH_EXT 0x2034 +#define WGL_PBUFFER_HEIGHT_EXT 0x2035 +typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); +typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer); +typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC); +typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer); +typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue); +#ifdef WGL_WGLEXT_PROTOTYPES +HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); +HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT hPbuffer); +int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC); +BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT hPbuffer); +BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue); +#endif +#endif /* WGL_EXT_pbuffer */ + +#ifndef WGL_EXT_pixel_format +#define WGL_EXT_pixel_format 1 +#define WGL_NUMBER_PIXEL_FORMATS_EXT 0x2000 +#define WGL_DRAW_TO_WINDOW_EXT 0x2001 +#define WGL_DRAW_TO_BITMAP_EXT 0x2002 +#define WGL_ACCELERATION_EXT 0x2003 +#define WGL_NEED_PALETTE_EXT 0x2004 +#define WGL_NEED_SYSTEM_PALETTE_EXT 0x2005 +#define WGL_SWAP_LAYER_BUFFERS_EXT 0x2006 +#define WGL_SWAP_METHOD_EXT 0x2007 +#define WGL_NUMBER_OVERLAYS_EXT 0x2008 +#define WGL_NUMBER_UNDERLAYS_EXT 0x2009 +#define WGL_TRANSPARENT_EXT 0x200A +#define WGL_TRANSPARENT_VALUE_EXT 0x200B +#define WGL_SHARE_DEPTH_EXT 0x200C +#define WGL_SHARE_STENCIL_EXT 0x200D +#define WGL_SHARE_ACCUM_EXT 0x200E +#define WGL_SUPPORT_GDI_EXT 0x200F +#define WGL_SUPPORT_OPENGL_EXT 0x2010 +#define WGL_DOUBLE_BUFFER_EXT 0x2011 +#define WGL_STEREO_EXT 0x2012 +#define WGL_PIXEL_TYPE_EXT 0x2013 +#define WGL_COLOR_BITS_EXT 0x2014 +#define WGL_RED_BITS_EXT 0x2015 +#define WGL_RED_SHIFT_EXT 0x2016 +#define WGL_GREEN_BITS_EXT 0x2017 +#define WGL_GREEN_SHIFT_EXT 0x2018 +#define WGL_BLUE_BITS_EXT 0x2019 +#define WGL_BLUE_SHIFT_EXT 0x201A +#define WGL_ALPHA_BITS_EXT 0x201B +#define WGL_ALPHA_SHIFT_EXT 0x201C +#define WGL_ACCUM_BITS_EXT 0x201D +#define WGL_ACCUM_RED_BITS_EXT 0x201E +#define WGL_ACCUM_GREEN_BITS_EXT 0x201F +#define WGL_ACCUM_BLUE_BITS_EXT 0x2020 +#define WGL_ACCUM_ALPHA_BITS_EXT 0x2021 +#define WGL_DEPTH_BITS_EXT 0x2022 +#define WGL_STENCIL_BITS_EXT 0x2023 +#define WGL_AUX_BUFFERS_EXT 0x2024 +#define WGL_NO_ACCELERATION_EXT 0x2025 +#define WGL_GENERIC_ACCELERATION_EXT 0x2026 +#define WGL_FULL_ACCELERATION_EXT 0x2027 +#define WGL_SWAP_EXCHANGE_EXT 0x2028 +#define WGL_SWAP_COPY_EXT 0x2029 +#define WGL_SWAP_UNDEFINED_EXT 0x202A +#define WGL_TYPE_RGBA_EXT 0x202B +#define WGL_TYPE_COLORINDEX_EXT 0x202C +typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues); +typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues); +typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues); +BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues); +BOOL WINAPI wglChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); +#endif +#endif /* WGL_EXT_pixel_format */ + +#ifndef WGL_EXT_pixel_format_packed_float +#define WGL_EXT_pixel_format_packed_float 1 +#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT 0x20A8 +#endif /* WGL_EXT_pixel_format_packed_float */ + +#ifndef WGL_EXT_swap_control +#define WGL_EXT_swap_control 1 +typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval); +typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglSwapIntervalEXT (int interval); +int WINAPI wglGetSwapIntervalEXT (void); +#endif +#endif /* WGL_EXT_swap_control */ + +#ifndef WGL_EXT_swap_control_tear +#define WGL_EXT_swap_control_tear 1 +#endif /* WGL_EXT_swap_control_tear */ + +#ifndef WGL_I3D_digital_video_control +#define WGL_I3D_digital_video_control 1 +#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050 +#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051 +#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052 +#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053 +typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue); +typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue); +BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue); +#endif +#endif /* WGL_I3D_digital_video_control */ + +#ifndef WGL_I3D_gamma +#define WGL_I3D_gamma 1 +#define WGL_GAMMA_TABLE_SIZE_I3D 0x204E +#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D 0x204F +typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue); +typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue); +typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue); +typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue); +BOOL WINAPI wglSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue); +BOOL WINAPI wglGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue); +BOOL WINAPI wglSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue); +#endif +#endif /* WGL_I3D_gamma */ + +#ifndef WGL_I3D_genlock +#define WGL_I3D_genlock 1 +#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044 +#define WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D 0x2045 +#define WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D 0x2046 +#define WGL_GENLOCK_SOURCE_EXTERNAL_TTL_I3D 0x2047 +#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048 +#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049 +#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A +#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B +#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C +typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC); +typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC); +typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag); +typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource); +typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource); +typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge); +typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge); +typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate); +typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate); +typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay); +typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay); +typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglEnableGenlockI3D (HDC hDC); +BOOL WINAPI wglDisableGenlockI3D (HDC hDC); +BOOL WINAPI wglIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag); +BOOL WINAPI wglGenlockSourceI3D (HDC hDC, UINT uSource); +BOOL WINAPI wglGetGenlockSourceI3D (HDC hDC, UINT *uSource); +BOOL WINAPI wglGenlockSourceEdgeI3D (HDC hDC, UINT uEdge); +BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge); +BOOL WINAPI wglGenlockSampleRateI3D (HDC hDC, UINT uRate); +BOOL WINAPI wglGetGenlockSampleRateI3D (HDC hDC, UINT *uRate); +BOOL WINAPI wglGenlockSourceDelayI3D (HDC hDC, UINT uDelay); +BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay); +BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay); +#endif +#endif /* WGL_I3D_genlock */ + +#ifndef WGL_I3D_image_buffer +#define WGL_I3D_image_buffer 1 +#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001 +#define WGL_IMAGE_BUFFER_LOCK_I3D 0x00000002 +typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags); +typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress); +typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count); +typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count); +#ifdef WGL_WGLEXT_PROTOTYPES +LPVOID WINAPI wglCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags); +BOOL WINAPI wglDestroyImageBufferI3D (HDC hDC, LPVOID pAddress); +BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count); +BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count); +#endif +#endif /* WGL_I3D_image_buffer */ + +#ifndef WGL_I3D_swap_frame_lock +#define WGL_I3D_swap_frame_lock 1 +typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void); +typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void); +typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag); +typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglEnableFrameLockI3D (void); +BOOL WINAPI wglDisableFrameLockI3D (void); +BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *pFlag); +BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *pFlag); +#endif +#endif /* WGL_I3D_swap_frame_lock */ + +#ifndef WGL_I3D_swap_frame_usage +#define WGL_I3D_swap_frame_usage 1 +typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage); +typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void); +typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void); +typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetFrameUsageI3D (float *pUsage); +BOOL WINAPI wglBeginFrameTrackingI3D (void); +BOOL WINAPI wglEndFrameTrackingI3D (void); +BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage); +#endif +#endif /* WGL_I3D_swap_frame_usage */ + +#ifndef WGL_NV_DX_interop +#define WGL_NV_DX_interop 1 +#define WGL_ACCESS_READ_ONLY_NV 0x00000000 +#define WGL_ACCESS_READ_WRITE_NV 0x00000001 +#define WGL_ACCESS_WRITE_DISCARD_NV 0x00000002 +typedef BOOL (WINAPI * PFNWGLDXSETRESOURCESHAREHANDLENVPROC) (void *dxObject, HANDLE shareHandle); +typedef HANDLE (WINAPI * PFNWGLDXOPENDEVICENVPROC) (void *dxDevice); +typedef BOOL (WINAPI * PFNWGLDXCLOSEDEVICENVPROC) (HANDLE hDevice); +typedef HANDLE (WINAPI * PFNWGLDXREGISTEROBJECTNVPROC) (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access); +typedef BOOL (WINAPI * PFNWGLDXUNREGISTEROBJECTNVPROC) (HANDLE hDevice, HANDLE hObject); +typedef BOOL (WINAPI * PFNWGLDXOBJECTACCESSNVPROC) (HANDLE hObject, GLenum access); +typedef BOOL (WINAPI * PFNWGLDXLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects); +typedef BOOL (WINAPI * PFNWGLDXUNLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglDXSetResourceShareHandleNV (void *dxObject, HANDLE shareHandle); +HANDLE WINAPI wglDXOpenDeviceNV (void *dxDevice); +BOOL WINAPI wglDXCloseDeviceNV (HANDLE hDevice); +HANDLE WINAPI wglDXRegisterObjectNV (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access); +BOOL WINAPI wglDXUnregisterObjectNV (HANDLE hDevice, HANDLE hObject); +BOOL WINAPI wglDXObjectAccessNV (HANDLE hObject, GLenum access); +BOOL WINAPI wglDXLockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects); +BOOL WINAPI wglDXUnlockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects); +#endif +#endif /* WGL_NV_DX_interop */ + +#ifndef WGL_NV_DX_interop2 +#define WGL_NV_DX_interop2 1 +#endif /* WGL_NV_DX_interop2 */ + +#ifndef WGL_NV_copy_image +#define WGL_NV_copy_image 1 +typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglCopyImageSubDataNV (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* WGL_NV_copy_image */ + +#ifndef WGL_NV_delay_before_swap +#define WGL_NV_delay_before_swap 1 +typedef BOOL (WINAPI * PFNWGLDELAYBEFORESWAPNVPROC) (HDC hDC, GLfloat seconds); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglDelayBeforeSwapNV (HDC hDC, GLfloat seconds); +#endif +#endif /* WGL_NV_delay_before_swap */ + +#ifndef WGL_NV_float_buffer +#define WGL_NV_float_buffer 1 +#define WGL_FLOAT_COMPONENTS_NV 0x20B0 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4 +#define WGL_TEXTURE_FLOAT_R_NV 0x20B5 +#define WGL_TEXTURE_FLOAT_RG_NV 0x20B6 +#define WGL_TEXTURE_FLOAT_RGB_NV 0x20B7 +#define WGL_TEXTURE_FLOAT_RGBA_NV 0x20B8 +#endif /* WGL_NV_float_buffer */ + +#ifndef WGL_NV_gpu_affinity +#define WGL_NV_gpu_affinity 1 +DECLARE_HANDLE(HGPUNV); +struct _GPU_DEVICE { + DWORD cb; + CHAR DeviceName[32]; + CHAR DeviceString[128]; + DWORD Flags; + RECT rcVirtualScreen; +}; +typedef struct _GPU_DEVICE *PGPU_DEVICE; +#define ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV 0x20D0 +#define ERROR_MISSING_AFFINITY_MASK_NV 0x20D1 +typedef BOOL (WINAPI * PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu); +typedef BOOL (WINAPI * PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice); +typedef HDC (WINAPI * PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList); +typedef BOOL (WINAPI * PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu); +typedef BOOL (WINAPI * PFNWGLDELETEDCNVPROC) (HDC hdc); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglEnumGpusNV (UINT iGpuIndex, HGPUNV *phGpu); +BOOL WINAPI wglEnumGpuDevicesNV (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice); +HDC WINAPI wglCreateAffinityDCNV (const HGPUNV *phGpuList); +BOOL WINAPI wglEnumGpusFromAffinityDCNV (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu); +BOOL WINAPI wglDeleteDCNV (HDC hdc); +#endif +#endif /* WGL_NV_gpu_affinity */ + +#ifndef WGL_NV_multisample_coverage +#define WGL_NV_multisample_coverage 1 +#define WGL_COVERAGE_SAMPLES_NV 0x2042 +#define WGL_COLOR_SAMPLES_NV 0x20B9 +#endif /* WGL_NV_multisample_coverage */ + +#ifndef WGL_NV_present_video +#define WGL_NV_present_video 1 +DECLARE_HANDLE(HVIDEOOUTPUTDEVICENV); +#define WGL_NUM_VIDEO_SLOTS_NV 0x20F0 +typedef int (WINAPI * PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList); +typedef BOOL (WINAPI * PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList); +typedef BOOL (WINAPI * PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue); +#ifdef WGL_WGLEXT_PROTOTYPES +int WINAPI wglEnumerateVideoDevicesNV (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList); +BOOL WINAPI wglBindVideoDeviceNV (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList); +BOOL WINAPI wglQueryCurrentContextNV (int iAttribute, int *piValue); +#endif +#endif /* WGL_NV_present_video */ + +#ifndef WGL_NV_render_depth_texture +#define WGL_NV_render_depth_texture 1 +#define WGL_BIND_TO_TEXTURE_DEPTH_NV 0x20A3 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4 +#define WGL_DEPTH_TEXTURE_FORMAT_NV 0x20A5 +#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6 +#define WGL_DEPTH_COMPONENT_NV 0x20A7 +#endif /* WGL_NV_render_depth_texture */ + +#ifndef WGL_NV_render_texture_rectangle +#define WGL_NV_render_texture_rectangle 1 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0 +#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1 +#define WGL_TEXTURE_RECTANGLE_NV 0x20A2 +#endif /* WGL_NV_render_texture_rectangle */ + +#ifndef WGL_NV_swap_group +#define WGL_NV_swap_group 1 +typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group); +typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier); +typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier); +typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers); +typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count); +typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglJoinSwapGroupNV (HDC hDC, GLuint group); +BOOL WINAPI wglBindSwapBarrierNV (GLuint group, GLuint barrier); +BOOL WINAPI wglQuerySwapGroupNV (HDC hDC, GLuint *group, GLuint *barrier); +BOOL WINAPI wglQueryMaxSwapGroupsNV (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers); +BOOL WINAPI wglQueryFrameCountNV (HDC hDC, GLuint *count); +BOOL WINAPI wglResetFrameCountNV (HDC hDC); +#endif +#endif /* WGL_NV_swap_group */ + +#ifndef WGL_NV_vertex_array_range +#define WGL_NV_vertex_array_range 1 +typedef void *(WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority); +typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer); +#ifdef WGL_WGLEXT_PROTOTYPES +void *WINAPI wglAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority); +void WINAPI wglFreeMemoryNV (void *pointer); +#endif +#endif /* WGL_NV_vertex_array_range */ + +#ifndef WGL_NV_video_capture +#define WGL_NV_video_capture 1 +DECLARE_HANDLE(HVIDEOINPUTDEVICENV); +#define WGL_UNIQUE_ID_NV 0x20CE +#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF +typedef BOOL (WINAPI * PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice); +typedef UINT (WINAPI * PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList); +typedef BOOL (WINAPI * PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice); +typedef BOOL (WINAPI * PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue); +typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglBindVideoCaptureDeviceNV (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice); +UINT WINAPI wglEnumerateVideoCaptureDevicesNV (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList); +BOOL WINAPI wglLockVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice); +BOOL WINAPI wglQueryVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue); +BOOL WINAPI wglReleaseVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice); +#endif +#endif /* WGL_NV_video_capture */ + +#ifndef WGL_NV_video_output +#define WGL_NV_video_output 1 +DECLARE_HANDLE(HPVIDEODEV); +#define WGL_BIND_TO_VIDEO_RGB_NV 0x20C0 +#define WGL_BIND_TO_VIDEO_RGBA_NV 0x20C1 +#define WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV 0x20C2 +#define WGL_VIDEO_OUT_COLOR_NV 0x20C3 +#define WGL_VIDEO_OUT_ALPHA_NV 0x20C4 +#define WGL_VIDEO_OUT_DEPTH_NV 0x20C5 +#define WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6 +#define WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7 +#define WGL_VIDEO_OUT_FRAME 0x20C8 +#define WGL_VIDEO_OUT_FIELD_1 0x20C9 +#define WGL_VIDEO_OUT_FIELD_2 0x20CA +#define WGL_VIDEO_OUT_STACKED_FIELDS_1_2 0x20CB +#define WGL_VIDEO_OUT_STACKED_FIELDS_2_1 0x20CC +typedef BOOL (WINAPI * PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice); +typedef BOOL (WINAPI * PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice); +typedef BOOL (WINAPI * PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer); +typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer); +typedef BOOL (WINAPI * PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock); +typedef BOOL (WINAPI * PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetVideoDeviceNV (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice); +BOOL WINAPI wglReleaseVideoDeviceNV (HPVIDEODEV hVideoDevice); +BOOL WINAPI wglBindVideoImageNV (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer); +BOOL WINAPI wglReleaseVideoImageNV (HPBUFFERARB hPbuffer, int iVideoBuffer); +BOOL WINAPI wglSendPbufferToVideoNV (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock); +BOOL WINAPI wglGetVideoInfoNV (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo); +#endif +#endif /* WGL_NV_video_output */ + +#ifndef WGL_OML_sync_control +#define WGL_OML_sync_control 1 +typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc); +typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator); +typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder); +typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder); +typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc); +typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc); +#ifdef WGL_WGLEXT_PROTOTYPES +BOOL WINAPI wglGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc); +BOOL WINAPI wglGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator); +INT64 WINAPI wglSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder); +INT64 WINAPI wglSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder); +BOOL WINAPI wglWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc); +BOOL WINAPI wglWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc); +#endif +#endif /* WGL_OML_sync_control */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/win32/win32gliface.cpp b/src/win32/win32gliface.cpp new file mode 100644 index 000000000..be8b52e04 --- /dev/null +++ b/src/win32/win32gliface.cpp @@ -0,0 +1,1172 @@ +//#include "gl/system/gl_system.h" + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include "wglext.h" + +#define USE_WINDOWS_DWORD +#include "win32iface.h" +#include "win32gliface.h" +//#include "gl/gl_intern.h" +#include "x86.h" +#include "templates.h" +#include "version.h" +#include "c_console.h" +#include "hardware.h" +#include "v_video.h" +#include "i_input.h" +#include "i_system.h" +#include "doomstat.h" +#include "v_text.h" +#include "m_argv.h" +#include "doomerrors.h" +//#include "gl_defs.h" + +#include "gl/renderer/gl_renderer.h" +#include "gl/system/gl_framebuffer.h" +#include "gl/system/gl_swframebuffer.h" + +extern "C" { + _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; + __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +} + +void gl_CalculateCPUSpeed(); +extern int NewWidth, NewHeight, NewBits, DisplayBits; + +// these get used before GLEW is initialized so we have to use separate pointers with different names +PFNWGLCHOOSEPIXELFORMATARBPROC myWglChoosePixelFormatARB; // = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); +PFNWGLCREATECONTEXTATTRIBSARBPROC myWglCreateContextAttribsARB; +PFNWGLSWAPINTERVALEXTPROC myWglSwapIntervalExtProc; + + + + +CUSTOM_CVAR(Bool, gl_debug, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL) +{ + Printf("This won't take effect until " GAMENAME " is restarted.\n"); +} + +EXTERN_CVAR(Bool, vr_enable_quadbuffered) +EXTERN_CVAR(Int, vid_refreshrate) + +//========================================================================== +// +// +// +//========================================================================== + +Win32GLVideo::Win32GLVideo(int parm) : m_Modes(NULL), m_IsFullscreen(false) +{ + #ifdef _WIN32 + if (CPU.bRDTSC) gl_CalculateCPUSpeed(); + #endif + I_SetWndProc(); + m_DisplayWidth = vid_defwidth; + m_DisplayHeight = vid_defheight; + m_DisplayBits = 32; + m_DisplayHz = 60; + + GetDisplayDeviceName(); + MakeModesList(); + SetPixelFormat(); + +} + +//========================================================================== +// +// +// +//========================================================================== + +Win32GLVideo::~Win32GLVideo() +{ + FreeModes(); + if (GLRenderer != NULL) GLRenderer->FlushTextures(); +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::SetWindowedScale(float scale) +{ +} + +//========================================================================== +// +// +// +//========================================================================== + +struct MonitorEnumState +{ + int curIdx; + HMONITOR hFoundMonitor; +}; + +static BOOL CALLBACK GetDisplayDeviceNameMonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) +{ + MonitorEnumState *state = reinterpret_cast(dwData); + + MONITORINFOEX mi; + mi.cbSize = sizeof mi; + GetMonitorInfo(hMonitor, &mi); + + // This assumes the monitors are returned by EnumDisplayMonitors in the + // order they're found in the Direct3D9 adapters list. Fingers crossed... + if (state->curIdx == vid_adapter) + { + state->hFoundMonitor = hMonitor; + + // Don't stop enumeration; this makes EnumDisplayMonitors fail. I like + // proper fails. + } + + ++state->curIdx; + + return TRUE; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::GetDisplayDeviceName() +{ + // If anything goes wrong, anything at all, everything uses the primary + // monitor. + m_DisplayDeviceName = 0; + m_hMonitor = 0; + + MonitorEnumState mes; + + mes.curIdx = 1; + mes.hFoundMonitor = 0; + + // Could also use EnumDisplayDevices, I guess. That might work. + if (EnumDisplayMonitors(0, 0, &GetDisplayDeviceNameMonitorEnumProc, LPARAM(&mes))) + { + if (mes.hFoundMonitor) + { + MONITORINFOEX mi; + + mi.cbSize = sizeof mi; + + if (GetMonitorInfo(mes.hFoundMonitor, &mi)) + { + strcpy(m_DisplayDeviceBuffer, mi.szDevice); + m_DisplayDeviceName = m_DisplayDeviceBuffer; + + m_hMonitor = mes.hFoundMonitor; + } + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::MakeModesList() +{ + ModeInfo *pMode, *nextmode; + DEVMODE dm; + int mode = 0; + + memset(&dm, 0, sizeof(DEVMODE)); + dm.dmSize = sizeof(DEVMODE); + + while (EnumDisplaySettings(m_DisplayDeviceName, mode, &dm)) + { + this->AddMode(dm.dmPelsWidth, dm.dmPelsHeight, dm.dmBitsPerPel, dm.dmPelsHeight, dm.dmDisplayFrequency); + ++mode; + } + + for (pMode = m_Modes; pMode != NULL; pMode = nextmode) + { + nextmode = pMode->next; + if (pMode->realheight == pMode->height && pMode->height * 4/3 == pMode->width) + { + if (pMode->width >= 360) + { + AddMode (pMode->width, pMode->width * 9/16, pMode->bits, pMode->height, pMode->refreshHz); + } + if (pMode->width > 640) + { + AddMode (pMode->width, pMode->width * 10/16, pMode->bits, pMode->height, pMode->refreshHz); + } + } + } +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::StartModeIterator(int bits, bool fs) +{ + m_IteratorMode = m_Modes; + // I think it's better to ignore the game-side settings of bit depth. + // The GL renderer will always default to 32 bits because 16 bit modes cannot have a stencil buffer. + m_IteratorBits = 32; + m_IteratorFS = fs; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::NextMode(int *width, int *height, bool *letterbox) +{ + if (m_IteratorMode) + { + while (m_IteratorMode && m_IteratorMode->bits != m_IteratorBits) + { + m_IteratorMode = m_IteratorMode->next; + } + + if (m_IteratorMode) + { + *width = m_IteratorMode->width; + *height = m_IteratorMode->height; + if (letterbox != NULL) *letterbox = m_IteratorMode->realheight != m_IteratorMode->height; + m_IteratorMode = m_IteratorMode->next; + return true; + } + } + + return false; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::AddMode(int x, int y, int bits, int baseHeight, int refreshHz) +{ + ModeInfo **probep = &m_Modes; + ModeInfo *probe = m_Modes; + + // This mode may have been already added to the list because it is + // enumerated multiple times at different refresh rates. If it's + // not present, add it to the right spot in the list; otherwise, do nothing. + // Modes are sorted first by width, then by height, then by depth. In each + // case the order is ascending. + if (bits < 32) return; + for (; probe != 0; probep = &probe->next, probe = probe->next) + { + if (probe->width != x) continue; + // Width is equal + if (probe->height != y) continue; + // Width is equal + if (probe->realheight != baseHeight) continue; + // Height is equal + if (probe->bits != bits) continue; + // Bits is equal + if (probe->refreshHz > refreshHz) return; + probe->refreshHz = refreshHz; + return; + } + + *probep = new ModeInfo (x, y, bits, baseHeight, refreshHz); + (*probep)->next = probe; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::FreeModes() +{ + ModeInfo *mode = m_Modes; + + while (mode) + { + ModeInfo *tempmode = mode; + mode = mode->next; + delete tempmode; + } + + m_Modes = NULL; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::GoFullscreen(bool yes) +{ + m_IsFullscreen = yes; + + m_trueHeight = m_DisplayHeight; + + if (yes) + { + // If in windowed mode, any height is good. + for (ModeInfo *mode = m_Modes; mode != NULL; mode = mode->next) + { + if (mode->width == m_DisplayWidth && mode->height == m_DisplayHeight) + { + m_trueHeight = mode->realheight; + break; + } + } + } + + if (yes) + { + SetFullscreen(m_DisplayDeviceName, m_DisplayWidth, m_trueHeight, m_DisplayBits, m_DisplayHz); + } + else + { + SetFullscreen(m_DisplayDeviceName, 0,0,0,0); + } + return yes; +} + + +//========================================================================== +// +// +// +//========================================================================== + + +DFrameBuffer *Win32GLVideo::CreateFrameBuffer(int width, int height, bool bgra, bool fs, DFrameBuffer *old) +{ + Win32GLFrameBuffer *fb; + + m_DisplayWidth = width; + m_DisplayHeight = height; + m_DisplayBits = 32; + m_DisplayHz = 60; + + if (vid_refreshrate == 0) + { + for (ModeInfo *mode = m_Modes; mode != NULL; mode = mode->next) + { + if (mode->width == m_DisplayWidth && mode->height == m_DisplayHeight && mode->bits == m_DisplayBits) + { + m_DisplayHz = MAX(m_DisplayHz, mode->refreshHz); + } + } + } + else + { + m_DisplayHz = vid_refreshrate; + } + + if (old != NULL) + { // Reuse the old framebuffer if its attributes are the same + fb = static_cast (old); + if (fb->m_Width == m_DisplayWidth && + fb->m_Height == m_DisplayHeight && + fb->m_Bits == m_DisplayBits && + fb->m_RefreshHz == m_DisplayHz && + fb->m_Fullscreen == fs && + fb->m_Bgra == bgra) + { + return old; + } + //old->GetFlash(flashColor, flashAmount); + delete old; + } + if (vid_renderer == 1) + fb = new OpenGLFrameBuffer(m_hMonitor, m_DisplayWidth, m_DisplayHeight, m_DisplayBits, m_DisplayHz, fs); + else + fb = new OpenGLSWFrameBuffer(m_hMonitor, m_DisplayWidth, m_DisplayHeight, m_DisplayBits, m_DisplayHz, fs, bgra); + return fb; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::SetResolution (int width, int height, int bits) +{ + if (GLRenderer != NULL) GLRenderer->FlushTextures(); + I_ShutdownGraphics(); + + Video = new Win32GLVideo(0); + if (Video == NULL) I_FatalError ("Failed to initialize display"); + + bits=32; + + V_DoModeSetup(width, height, bits); + return true; // We must return true because the old video context no longer exists. +} + +//========================================================================== +// +// +// +//========================================================================== + +struct DumpAdaptersState +{ + unsigned index; + char *displayDeviceName; +}; + +static BOOL CALLBACK DumpAdaptersMonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) +{ + DumpAdaptersState *state = reinterpret_cast(dwData); + + MONITORINFOEX mi; + mi.cbSize=sizeof mi; + + char moreinfo[64] = ""; + + bool active = true; + + if (GetMonitorInfo(hMonitor, &mi)) + { + bool primary = !!(mi.dwFlags & MONITORINFOF_PRIMARY); + + mysnprintf(moreinfo, countof(moreinfo), " [%ldx%ld @ (%ld,%ld)]%s", + mi.rcMonitor.right - mi.rcMonitor.left, + mi.rcMonitor.bottom - mi.rcMonitor.top, + mi.rcMonitor.left, mi.rcMonitor.top, + primary ? " (Primary)" : ""); + + if (!state->displayDeviceName && !primary) + active = false;//primary selected, but this ain't primary + else if (state->displayDeviceName && strcmp(state->displayDeviceName, mi.szDevice) != 0) + active = false;//this isn't the selected one + } + + Printf("%s%u. %s\n", + active ? TEXTCOLOR_BOLD : "", + state->index, + moreinfo); + + ++state->index; + + return TRUE; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::DumpAdapters() +{ + DumpAdaptersState das; + + das.index = 1; + das.displayDeviceName = m_DisplayDeviceName; + + EnumDisplayMonitors(0, 0, DumpAdaptersMonitorEnumProc, LPARAM(&das)); +} + +//========================================================================== +// +// +// +//========================================================================== + +HWND Win32GLVideo::InitDummy() +{ + HMODULE g_hInst = GetModuleHandle(NULL); + HWND dummy; + //Create a rect structure for the size/position of the window + RECT windowRect; + windowRect.left = 0; + windowRect.right = 64; + windowRect.top = 0; + windowRect.bottom = 64; + + //Window class structure + WNDCLASS wc; + + //Fill in window class struct + wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; + wc.lpfnWndProc = (WNDPROC) DefWindowProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = g_hInst; + wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = NULL; + wc.lpszMenuName = NULL; + wc.lpszClassName = "GZDoomOpenGLDummyWindow"; + + //Register window class + if(!RegisterClass(&wc)) + { + return 0; + } + + //Set window style & extended style + DWORD style, exStyle; + exStyle = WS_EX_CLIENTEDGE; + style = WS_SYSMENU | WS_BORDER | WS_CAPTION;// | WS_VISIBLE; + + //Adjust the window size so that client area is the size requested + AdjustWindowRectEx(&windowRect, style, false, exStyle); + + //Create Window + if(!(dummy = CreateWindowEx(exStyle, + "GZDoomOpenGLDummyWindow", + "GZDOOM", + WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style, + 0, 0, + windowRect.right-windowRect.left, + windowRect.bottom-windowRect.top, + NULL, NULL, + g_hInst, + NULL))) + { + UnregisterClass("GZDoomOpenGLDummyWindow", g_hInst); + return 0; + } + ShowWindow(dummy, SW_HIDE); + + return dummy; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::ShutdownDummy(HWND dummy) +{ + DestroyWindow(dummy); + UnregisterClass("GZDoomOpenGLDummyWindow", GetModuleHandle(NULL)); +} + + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::SetPixelFormat() +{ + HDC hDC; + HGLRC hRC; + HWND dummy; + + PIXELFORMATDESCRIPTOR pfd = { + sizeof(PIXELFORMATDESCRIPTOR), + 1, + PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, + PFD_TYPE_RGBA, + 32, // color depth + 0, 0, 0, 0, 0, 0, + 0, + 0, + 0, + 0, 0, 0, 0, + 16, // z depth + 0, // stencil buffer + 0, + PFD_MAIN_PLANE, + 0, + 0, 0, 0 + }; + + int pixelFormat; + + // we have to create a dummy window to init stuff from or the full init stuff fails + dummy = InitDummy(); + + hDC = GetDC(dummy); + pixelFormat = ChoosePixelFormat(hDC, &pfd); + DescribePixelFormat(hDC, pixelFormat, sizeof(pfd), &pfd); + + ::SetPixelFormat(hDC, pixelFormat, &pfd); + + hRC = wglCreateContext(hDC); + wglMakeCurrent(hDC, hRC); + + myWglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); + myWglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); + // any extra stuff here? + + wglMakeCurrent(NULL, NULL); + wglDeleteContext(hRC); + ReleaseDC(dummy, hDC); + ShutdownDummy(dummy); + + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::SetupPixelFormat(int multisample) +{ + int i; + int colorDepth; + HDC deskDC; + int attributes[28]; + int pixelFormat; + unsigned int numFormats; + float attribsFloat[] = {0.0f, 0.0f}; + + deskDC = GetDC(GetDesktopWindow()); + colorDepth = GetDeviceCaps(deskDC, BITSPIXEL); + ReleaseDC(GetDesktopWindow(), deskDC); + + if (myWglChoosePixelFormatARB) + { + attributes[0] = WGL_RED_BITS_ARB; //bits + attributes[1] = 8; + attributes[2] = WGL_GREEN_BITS_ARB; //bits + attributes[3] = 8; + attributes[4] = WGL_BLUE_BITS_ARB; //bits + attributes[5] = 8; + attributes[6] = WGL_ALPHA_BITS_ARB; + attributes[7] = 8; + attributes[8] = WGL_DEPTH_BITS_ARB; + attributes[9] = 24; + attributes[10] = WGL_STENCIL_BITS_ARB; + attributes[11] = 8; + + attributes[12] = WGL_DRAW_TO_WINDOW_ARB; //required to be true + attributes[13] = true; + attributes[14] = WGL_SUPPORT_OPENGL_ARB; + attributes[15] = true; + attributes[16] = WGL_DOUBLE_BUFFER_ARB; + attributes[17] = true; + + if (multisample > 0) + { + attributes[18] = WGL_SAMPLE_BUFFERS_ARB; + attributes[19] = true; + attributes[20] = WGL_SAMPLES_ARB; + attributes[21] = multisample; + i = 22; + } + else + { + i = 18; + } + + attributes[i++] = WGL_ACCELERATION_ARB; //required to be FULL_ACCELERATION_ARB + attributes[i++] = WGL_FULL_ACCELERATION_ARB; + + if (vr_enable_quadbuffered) + { + // [BB] Starting with driver version 314.07, NVIDIA GeForce cards support OpenGL quad buffered + // stereo rendering with 3D Vision hardware. Select the corresponding attribute here. + attributes[i++] = WGL_STEREO_ARB; + attributes[i++] = true; + } + + attributes[i++] = 0; + attributes[i++] = 0; + + if (!myWglChoosePixelFormatARB(m_hDC, attributes, attribsFloat, 1, &pixelFormat, &numFormats)) + { + Printf("R_OPENGL: Couldn't choose pixel format. Retrying in compatibility mode\n"); + goto oldmethod; + } + + if (numFormats == 0) + { + Printf("R_OPENGL: No valid pixel formats found. Retrying in compatibility mode\n"); + goto oldmethod; + } + } + else + { + oldmethod: + // If wglChoosePixelFormatARB is not found we have to do it the old fashioned way. + static PIXELFORMATDESCRIPTOR pfd = { + sizeof(PIXELFORMATDESCRIPTOR), + 1, + PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, + PFD_TYPE_RGBA, + 32, // color depth + 0, 0, 0, 0, 0, 0, + 0, + 0, + 0, + 0, 0, 0, 0, + 32, // z depth + 8, // stencil buffer + 0, + PFD_MAIN_PLANE, + 0, + 0, 0, 0 + }; + + pixelFormat = ChoosePixelFormat(m_hDC, &pfd); + DescribePixelFormat(m_hDC, pixelFormat, sizeof(pfd), &pfd); + + if (pfd.dwFlags & PFD_GENERIC_FORMAT) + { + I_Error("R_OPENGL: OpenGL driver not accelerated!"); + return false; + } + } + + if (!::SetPixelFormat(m_hDC, pixelFormat, NULL)) + { + I_Error("R_OPENGL: Couldn't set pixel format.\n"); + return false; + } + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::InitHardware (HWND Window, int multisample) +{ + m_Window=Window; + m_hDC = GetDC(Window); + + if (!SetupPixelFormat(multisample)) + { + return false; + } + + int prof = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; + const char *version = Args->CheckValue("-glversion"); + + if (version != nullptr && strcmp(version, "3.0") < 0) prof = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; + + for (; prof <= WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; prof++) + { + m_hRC = NULL; + if (myWglCreateContextAttribsARB != NULL) + { + // let's try to get the best version possible. Some drivers only give us the version we request + // which breaks all version checks for feature support. The highest used features we use are from version 4.4, and 3.0 is a requirement. + static int versions[] = { 45, 44, 43, 42, 41, 40, 33, 32, 31, 30, -1 }; + + for (int i = 0; versions[i] > 0; i++) + { + int ctxAttribs[] = { + WGL_CONTEXT_MAJOR_VERSION_ARB, versions[i] / 10, + WGL_CONTEXT_MINOR_VERSION_ARB, versions[i] % 10, + WGL_CONTEXT_FLAGS_ARB, gl_debug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0, + WGL_CONTEXT_PROFILE_MASK_ARB, prof, + 0 + }; + + m_hRC = myWglCreateContextAttribsARB(m_hDC, 0, ctxAttribs); + if (m_hRC != NULL) break; + } + } + + if (m_hRC == NULL && prof == WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB) + { + m_hRC = wglCreateContext(m_hDC); + if (m_hRC == NULL) + { + I_Error("R_OPENGL: Unable to create an OpenGL render context.\n"); + return false; + } + } + + if (m_hRC != NULL) + { + wglMakeCurrent(m_hDC, m_hRC); + return true; + } + } + // We get here if the driver doesn't support the modern context creation API which always means an old driver. + I_Error ("R_OPENGL: Unable to create an OpenGL render context. Insufficient driver support for context creation\n"); + return false; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLVideo::Shutdown() +{ + if (m_hRC) + { + wglMakeCurrent(0, 0); + wglDeleteContext(m_hRC); + } + if (m_hDC) ReleaseDC(m_Window, m_hDC); +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLVideo::SetFullscreen(const char *devicename, int w, int h, int bits, int hz) +{ + DEVMODE dm; + + if (w==0) + { + ChangeDisplaySettingsEx(devicename, 0, 0, 0, 0); + } + else + { + dm.dmSize = sizeof(DEVMODE); + dm.dmSpecVersion = DM_SPECVERSION;//Somebody owes me... + dm.dmDriverExtra = 0;//...1 hour of my life back + dm.dmPelsWidth = w; + dm.dmPelsHeight = h; + dm.dmBitsPerPel = bits; + dm.dmDisplayFrequency = hz; + dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY; + if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettingsEx(devicename, &dm, 0, CDS_FULLSCREEN, 0)) + { + dm.dmFields &= ~DM_DISPLAYFREQUENCY; + return DISP_CHANGE_SUCCESSFUL == ChangeDisplaySettingsEx(devicename, &dm, 0, CDS_FULLSCREEN, 0); + } + } + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +IMPLEMENT_CLASS(Win32GLFrameBuffer, true, false) + +//========================================================================== +// +// +// +//========================================================================== + +Win32GLFrameBuffer::Win32GLFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen, bool bgra) : BaseWinFB(width, height, bgra) +{ + m_Width = width; + m_Height = height; + m_Bits = bits; + m_RefreshHz = refreshHz; + m_Fullscreen = fullscreen; + m_Bgra = bgra; + m_Lock=0; + + RECT r; + LONG style, exStyle; + + static_cast(Video)->GoFullscreen(fullscreen); + + m_displayDeviceName = 0; + int monX = 0, monY = 0; + + if (hMonitor) + { + MONITORINFOEX mi; + mi.cbSize = sizeof mi; + + if (GetMonitorInfo(HMONITOR(hMonitor), &mi)) + { + strcpy(m_displayDeviceNameBuffer, mi.szDevice); + m_displayDeviceName = m_displayDeviceNameBuffer; + + monX = int(mi.rcMonitor.left); + monY = int(mi.rcMonitor.top); + } + } + + ShowWindow (Window, SW_SHOW); + GetWindowRect(Window, &r); + style = WS_VISIBLE | WS_CLIPSIBLINGS; + exStyle = 0; + + if (fullscreen) + style |= WS_POPUP; + else + { + style |= WS_OVERLAPPEDWINDOW; + exStyle |= WS_EX_WINDOWEDGE; + } + + SetWindowLong(Window, GWL_STYLE, style); + SetWindowLong(Window, GWL_EXSTYLE, exStyle); + SetWindowPos(Window, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); + + if (fullscreen) + { + MoveWindow(Window, monX, monY, width, GetTrueHeight(), FALSE); + + // And now, seriously, it IS in the right place. Promise. + } + else + { + RECT windowRect; + windowRect.left = r.left; + windowRect.top = r.top; + windowRect.right = windowRect.left + width; + windowRect.bottom = windowRect.top + height; + AdjustWindowRectEx(&windowRect, style, FALSE, exStyle); + MoveWindow(Window, windowRect.left, windowRect.top, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, FALSE); + + I_RestoreWindowedPos(); + } + + if (!static_cast(Video)->InitHardware(Window, 0)) + { + vid_renderer = 0; + return; + } + HDC hDC = GetDC(Window); + const char *wglext = nullptr; + + myWglSwapIntervalExtProc = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); + auto myWglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); + if (myWglGetExtensionsStringARB) + { + wglext = myWglGetExtensionsStringARB(hDC); + } + else + { + auto myWglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT"); + if (myWglGetExtensionsStringEXT) + { + wglext = myWglGetExtensionsStringEXT(); + } + } + SwapInterval = 1; + if (wglext != nullptr) + { + if (strstr(wglext, "WGL_EXT_swap_control_tear")) + { + SwapInterval = -1; + } + } + + m_supportsGamma = !!GetDeviceGammaRamp(hDC, (void *)m_origGamma); + ReleaseDC(Window, hDC); +} + +//========================================================================== +// +// +// +//========================================================================== + +Win32GLFrameBuffer::~Win32GLFrameBuffer() +{ + ResetGammaTable(); + I_SaveWindowedPos(); + + static_cast(Video)->SetFullscreen(m_displayDeviceName, 0,0,0,0); + + ShowWindow (Window, SW_SHOW); + SetWindowLong(Window, GWL_STYLE, WS_VISIBLE | WS_CLIPSIBLINGS | WS_OVERLAPPEDWINDOW); + SetWindowLong(Window, GWL_EXSTYLE, WS_EX_WINDOWEDGE); + SetWindowPos(Window, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); + I_GetEvent(); + + static_cast(Video)->Shutdown(); +} + + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLFrameBuffer::InitializeState() +{ +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLFrameBuffer::CanUpdate() +{ + if (!AppActive) return false; + return true; +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLFrameBuffer::ResetGammaTable() +{ + if (m_supportsGamma) + { + HDC hDC = GetDC(Window); + SetDeviceGammaRamp(hDC, (void *)m_origGamma); + ReleaseDC(Window, hDC); + } +} + +void Win32GLFrameBuffer::SetGammaTable(WORD *tbl) +{ + if (m_supportsGamma) + { + HDC hDC = GetDC(Window); + SetDeviceGammaRamp(hDC, (void *)tbl); + ReleaseDC(Window, hDC); + } +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLFrameBuffer::Lock(bool buffered) +{ + m_Lock++; + Buffer = MemBuffer; + return true; +} + +bool Win32GLFrameBuffer::Lock () +{ + return Lock(false); +} + +void Win32GLFrameBuffer::Unlock () +{ + m_Lock--; +} + +bool Win32GLFrameBuffer::IsLocked () +{ + return m_Lock>0;// true; +} + +//========================================================================== +// +// +// +//========================================================================== + +bool Win32GLFrameBuffer::IsFullscreen() +{ + return m_Fullscreen; +} + +void Win32GLFrameBuffer::PaletteChanged() +{ +} + +int Win32GLFrameBuffer::QueryNewPalette() +{ + return 0; +} + +HRESULT Win32GLFrameBuffer::GetHR() +{ + return 0; +} + +void Win32GLFrameBuffer::Blank () +{ +} + +bool Win32GLFrameBuffer::PaintToWindow () +{ + return false; +} + +bool Win32GLFrameBuffer::CreateResources () +{ + return false; +} + +void Win32GLFrameBuffer::ReleaseResources () +{ +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLFrameBuffer::SetVSync (bool vsync) +{ + if (myWglSwapIntervalExtProc != NULL) myWglSwapIntervalExtProc(vsync ? SwapInterval : 0); +} + +void Win32GLFrameBuffer::SwapBuffers() +{ + // Limiting the frame rate is as simple as waiting for the timer to signal this event. + if (FPSLimitEvent != NULL) + { + WaitForSingleObject(FPSLimitEvent, 1000); + } + ::SwapBuffers(static_cast(Video)->m_hDC); +} + +//========================================================================== +// +// +// +//========================================================================== + +void Win32GLFrameBuffer::NewRefreshRate () +{ + if (m_Fullscreen) + { + setmodeneeded = true; + NewWidth = screen->GetWidth(); + NewHeight = screen->GetHeight(); + NewBits = DisplayBits; + } +} + +int Win32GLFrameBuffer::GetClientWidth() +{ + RECT rect = { 0 }; + GetClientRect(Window, &rect); + return rect.right - rect.left; +} + +int Win32GLFrameBuffer::GetClientHeight() +{ + RECT rect = { 0 }; + GetClientRect(Window, &rect); + return rect.bottom - rect.top; +} + +IVideo *gl_CreateVideo() +{ + return new Win32GLVideo(0); +} \ No newline at end of file diff --git a/src/win32/win32gliface.h b/src/win32/win32gliface.h new file mode 100644 index 000000000..fbaf34bd5 --- /dev/null +++ b/src/win32/win32gliface.h @@ -0,0 +1,157 @@ +#ifndef __WIN32GLIFACE_H__ +#define __WIN32GLIFACE_H__ + +#include "hardware.h" +#include "win32iface.h" +#include "v_video.h" +#include "tarray.h" + +extern IVideo *Video; + + +extern BOOL AppActive; + +EXTERN_CVAR (Float, dimamount) +EXTERN_CVAR (Color, dimcolor) + +EXTERN_CVAR(Int, vid_defwidth); +EXTERN_CVAR(Int, vid_defheight); +EXTERN_CVAR(Int, vid_renderer); +EXTERN_CVAR(Int, vid_adapter); + +extern HINSTANCE g_hInst; +extern HWND Window; +extern IVideo *Video; + +struct FRenderer; +FRenderer *gl_CreateInterface(); + + +class Win32GLVideo : public IVideo +{ +public: + Win32GLVideo(int parm); + virtual ~Win32GLVideo(); + + EDisplayType GetDisplayType () { return DISPLAY_Both; } + void SetWindowedScale (float scale); + void StartModeIterator (int bits, bool fs); + bool NextMode (int *width, int *height, bool *letterbox); + bool GoFullscreen(bool yes); + DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old); + virtual bool SetResolution (int width, int height, int bits); + void DumpAdapters(); + bool InitHardware (HWND Window, int multisample); + void Shutdown(); + bool SetFullscreen(const char *devicename, int w, int h, int bits, int hz); + + HDC m_hDC; + +protected: + struct ModeInfo + { + ModeInfo (int inX, int inY, int inBits, int inRealY, int inRefresh) + : next (NULL), + width (inX), + height (inY), + bits (inBits), + refreshHz (inRefresh), + realheight (inRealY) + {} + ModeInfo *next; + int width, height, bits, refreshHz, realheight; + } *m_Modes; + + ModeInfo *m_IteratorMode; + int m_IteratorBits; + bool m_IteratorFS; + bool m_IsFullscreen; + int m_trueHeight; + int m_DisplayWidth, m_DisplayHeight, m_DisplayBits, m_DisplayHz; + HMODULE hmRender; + + char m_DisplayDeviceBuffer[CCHDEVICENAME]; + char *m_DisplayDeviceName; + HMONITOR m_hMonitor; + + HWND m_Window; + HGLRC m_hRC; + + HWND InitDummy(); + void ShutdownDummy(HWND dummy); + bool SetPixelFormat(); + bool SetupPixelFormat(int multisample); + + void GetDisplayDeviceName(); + void MakeModesList(); + void AddMode(int x, int y, int bits, int baseHeight, int refreshHz); + void FreeModes(); +public: + int GetTrueHeight() { return m_trueHeight; } + +}; + + + +class Win32GLFrameBuffer : public BaseWinFB +{ + DECLARE_CLASS(Win32GLFrameBuffer, BaseWinFB) + +public: + Win32GLFrameBuffer() {} + // Actually, hMonitor is a HMONITOR, but it's passed as a void * as there + // look to be some cross-platform bits in the way. + Win32GLFrameBuffer(void *hMonitor, int width, int height, int bits, int refreshHz, bool fullscreen, bool bgra); + virtual ~Win32GLFrameBuffer(); + + + // unused but must be defined + virtual void Blank (); + virtual bool PaintToWindow (); + virtual HRESULT GetHR(); + + virtual bool CreateResources (); + virtual void ReleaseResources (); + + void SetVSync (bool vsync); + void SwapBuffers(); + void NewRefreshRate (); + + int GetClientWidth(); + int GetClientHeight(); + + int GetTrueHeight() { return static_cast(Video)->GetTrueHeight(); } + + bool Lock(bool buffered); + bool Lock (); + void Unlock(); + bool IsLocked (); + + + bool IsFullscreen(); + void PaletteChanged(); + int QueryNewPalette(); + + void InitializeState(); + +protected: + + bool CanUpdate(); + void ResetGammaTable(); + void SetGammaTable(WORD * tbl); + + float m_Gamma, m_Brightness, m_Contrast; + WORD m_origGamma[768]; + BOOL m_supportsGamma; + bool m_Fullscreen, m_Bgra; + int m_Width, m_Height, m_Bits, m_RefreshHz; + int m_Lock; + char m_displayDeviceNameBuffer[CCHDEVICENAME]; + char *m_displayDeviceName; + int SwapInterval; + + friend class Win32GLVideo; + +}; + +#endif //__WIN32GLIFACE_H__ diff --git a/src/win32/win32iface.h b/src/win32/win32iface.h index b5262089b..171e0a799 100644 --- a/src/win32/win32iface.h +++ b/src/win32/win32iface.h @@ -70,7 +70,7 @@ class Win32Video : public IVideo EDisplayType GetDisplayType () { return DISPLAY_Both; } void SetWindowedScale (float scale); - DFrameBuffer *CreateFrameBuffer (int width, int height, bool fs, DFrameBuffer *old); + DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old); void StartModeIterator (int bits, bool fs); bool NextMode (int *width, int *height, bool *letterbox); @@ -121,7 +121,7 @@ class BaseWinFB : public DFrameBuffer { DECLARE_ABSTRACT_CLASS(BaseWinFB, DFrameBuffer) public: - BaseWinFB (int width, int height) : DFrameBuffer (width, height), Windowed (true) {} + BaseWinFB (int width, int height, bool bgra) : DFrameBuffer (width, height, bgra), Windowed (true) {} bool IsFullscreen () { return !Windowed; } virtual void Blank () = 0; @@ -228,7 +228,7 @@ class D3DFB : public BaseWinFB { DECLARE_CLASS(D3DFB, BaseWinFB) public: - D3DFB (UINT adapter, int width, int height, bool fullscreen); + D3DFB (UINT adapter, int width, int height, bool bgra, bool fullscreen); ~D3DFB (); bool IsValid (); @@ -422,6 +422,7 @@ private: bool NeedPalUpdate; bool NeedGammaUpdate; int FBWidth, FBHeight; + D3DFORMAT FBFormat; bool VSync; RECT BlendingRect; int In2D; diff --git a/src/win32/win32video.cpp b/src/win32/win32video.cpp index 0d91ed1d0..e07ca3660 100644 --- a/src/win32/win32video.cpp +++ b/src/win32/win32video.cpp @@ -632,7 +632,7 @@ bool Win32Video::NextMode (int *width, int *height, bool *letterbox) return false; } -DFrameBuffer *Win32Video::CreateFrameBuffer (int width, int height, bool fullscreen, DFrameBuffer *old) +DFrameBuffer *Win32Video::CreateFrameBuffer (int width, int height, bool bgra, bool fullscreen, DFrameBuffer *old) { static int retry = 0; static int owidth, oheight; @@ -648,7 +648,8 @@ DFrameBuffer *Win32Video::CreateFrameBuffer (int width, int height, bool fullscr BaseWinFB *fb = static_cast (old); if (fb->Width == width && fb->Height == height && - fb->Windowed == !fullscreen) + fb->Windowed == !fullscreen && + fb->Bgra == bgra) { return old; } @@ -665,12 +666,13 @@ DFrameBuffer *Win32Video::CreateFrameBuffer (int width, int height, bool fullscr if (D3D != NULL) { - fb = new D3DFB (m_Adapter, width, height, fullscreen); + fb = new D3DFB (m_Adapter, width, height, bgra, fullscreen); } else { fb = new DDrawFB (width, height, fullscreen); } + LOG1 ("New fb created @ %p\n", fb); // If we could not create the framebuffer, try again with slightly @@ -729,7 +731,7 @@ DFrameBuffer *Win32Video::CreateFrameBuffer (int width, int height, bool fullscr } ++retry; - fb = static_cast(CreateFrameBuffer (width, height, fullscreen, NULL)); + fb = static_cast(CreateFrameBuffer (width, height, bgra, fullscreen, NULL)); } retry = 0; diff --git a/src/win32/zdoom.rc b/src/win32/zdoom.rc index e28277e3a..99422e4ad 100644 --- a/src/win32/zdoom.rc +++ b/src/win32/zdoom.rc @@ -72,13 +72,13 @@ BEGIN " BEGIN\r\n" " VALUE ""Comments"", ""Thanks to id Software for creating DOOM and then releasing the source code. Thanks also to TeamTNT for creating BOOM, which ZDoom is partially based on. Includes code based on the Cajun Bot 0.97 by Martin Collberg.""\r\n" " VALUE ""CompanyName"", "" ""\r\n" - " VALUE ""FileDescription"", ""ZDoom""\r\n" + " VALUE ""FileDescription"", ""QZDoom""\r\n" " VALUE ""FileVersion"", RC_FILEVERSION2\r\n" - " VALUE ""InternalName"", ""ZDoom""\r\n" + " VALUE ""InternalName"", ""QZDoom""\r\n" " VALUE ""LegalCopyright"", ""Copyright \\u00A9 1993-1996 id Software, 1998-2010 Randy Heit, 2002-2010 Christoph Oelckers, et al.""\r\n" " VALUE ""LegalTrademarks"", ""DoomR is a Registered Trademark of id Software, Inc.""\r\n" - " VALUE ""OriginalFilename"", ""zdoom.exe""\r\n" - " VALUE ""ProductName"", ""ZDoom""\r\n" + " VALUE ""OriginalFilename"", ""qzdoom.exe""\r\n" + " VALUE ""ProductName"", ""QZDoom""\r\n" " VALUE ""ProductVersion"", RC_PRODUCTVERSION2\r\n" " END\r\n" " END\r\n" @@ -86,7 +86,7 @@ BEGIN " BEGIN\r\n" " VALUE ""Translation"", 0x409, 1200\r\n" " END\r\n" - "EN\0" + "END\r\n" END #endif // APSTUDIO_INVOKED @@ -120,9 +120,9 @@ BEGIN IDD_IWADDIALOG, DIALOG BEGIN LEFTMARGIN, 5 - RIGHTMARGIN, 205 + RIGHTMARGIN, 222 TOPMARGIN, 7 - BOTTOMMARGIN, 179 + BOTTOMMARGIN, 242 END IDD_EAXPROPERTYLIST, DIALOG @@ -220,6 +220,7 @@ END // Dialog // +/* IDD_IWADDIALOG DIALOGEX 0, 0, 212, 186 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU EXSTYLE WS_EX_APPWINDOW @@ -233,6 +234,32 @@ BEGIN LTEXT "ZDoom found more than one IWAD present.",IDC_STATIC,5,5,140,8 LTEXT "Select from the list below to determine which one to use:",IDC_STATIC,5,15,200,8 END +*/ +// [SP] Upstreamed from Zandronum +IDD_IWADDIALOG DIALOGEX 0, 0, 224, 246 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +EXSTYLE WS_EX_APPWINDOW +CAPTION "Welcome" +FONT 8, "MS Shell Dlg", 0, 0, 0x1 +BEGIN + ICON IDI_ICON1,IDC_STATIC,7,7,21,20 + LTEXT "Welcome to QZDoom!",IDC_STATIC,42,8,180,8 + LTEXT "",IDC_WELCOME_VERSION,42,18,180,8 + GROUPBOX "IWAD selection",IDC_STATIC,8,32,208,102 + LTEXT "Select which game file (IWAD) to run.",IDC_STATIC,12,44,190,8 + LISTBOX IDC_IWADLIST,12,56,200,72,LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + GROUPBOX "Video settings",IDC_STATIC,8,138,208,48 + LTEXT "Choose how QZDoom will render the game.",IDC_STATIC,12,148,190,8 + CONTROL "Hardware (OpenGL)",IDC_WELCOME_OPENGL,"Button",BS_AUTORADIOBUTTON,12,170,93,10 + CONTROL "Software (Doom)",IDC_WELCOME_SOFTWARE,"Button",BS_AUTORADIOBUTTON,12,160,93,10 + CONTROL "Fullscreen",IDC_WELCOME_FULLSCREEN,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,124,160,48,10 + CONTROL "Disable autoload",IDC_WELCOME_NOAUTOLOAD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,148,39,65,10 + CONTROL "Lights.pk3",IDC_WELCOME_LIGHTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,46,192,51,10 + CONTROL "Brightmaps.pk3",IDC_WELCOME_BRIGHTMAPS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,111,192,65,10 + CONTROL "Don't ask me this again",IDC_DONTASKIWAD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,73,211,87,10 + DEFPUSHBUTTON "Play QZDoom",IDOK,8,228,90,14 + PUSHBUTTON "Exit",IDCANCEL,166,228,50,14 +END IDD_EAXPROPERTYLIST DIALOGEX 0, 0, 265, 404 STYLE DS_SETFONT | DS_3DLOOK | DS_FIXEDSYS | DS_CONTROL | WS_CHILD | WS_VSCROLL @@ -464,7 +491,7 @@ IDB_DEADGUY BITMAP "deadguy.bmp" // Generated from the TEXTINCLUDE 3 resource. // #ifndef NO_MANIFEST - CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "zdoom.exe.manifest" +// CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "zdoom.exe.manifest" #endif ///////////////////////////////////////////////////////////////////////////// @@ -492,13 +519,13 @@ BEGIN BEGIN VALUE "Comments", "Thanks to id Software for creating DOOM and then releasing the source code. Thanks also to TeamTNT for creating BOOM, which ZDoom is partially based on. Includes code based on the Cajun Bot 0.97 by Martin Collberg." VALUE "CompanyName", " " - VALUE "FileDescription", "ZDoom" + VALUE "FileDescription", "QZDoom" VALUE "FileVersion", RC_FILEVERSION2 - VALUE "InternalName", "ZDoom" + VALUE "InternalName", "QZDoom" VALUE "LegalCopyright", "Copyright \u00A9 1993-1996 id Software, 1998-2010 Randy Heit, 2002-2010 Christoph Oelckers, et al." VALUE "LegalTrademarks", "DoomR is a Registered Trademark of id Software, Inc." - VALUE "OriginalFilename", "zdoom.exe" - VALUE "ProductName", "ZDoom" + VALUE "OriginalFilename", "qzdoom.exe" + VALUE "ProductName", "QZDoom" VALUE "ProductVersion", RC_PRODUCTVERSION2 END END diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 8a97243bb..f4fe251e1 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -7,5 +7,6 @@ if( WIN32 AND NOT CMAKE_SIZEOF_VOID_P MATCHES "8" ) endif() add_subdirectory( updaterevision ) add_subdirectory( zipdir ) +add_subdirectory( drawergen ) set( CROSS_EXPORTS ${CROSS_EXPORTS} PARENT_SCOPE ) diff --git a/tools/drawergen/CMakeLists.txt b/tools/drawergen/CMakeLists.txt new file mode 100644 index 000000000..6a5804e8a --- /dev/null +++ b/tools/drawergen/CMakeLists.txt @@ -0,0 +1,185 @@ +cmake_minimum_required( VERSION 2.8.7 ) + +include( CheckCXXCompilerFlag ) + +include(../../precompiled_headers.cmake) + +# Path where it looks for the LLVM compiled files on Windows +set( LLVM_PRECOMPILED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../llvm" ) + +if( CMAKE_SIZEOF_VOID_P MATCHES "8" ) + set( X64 64 ) +endif() + +if( NOT DRAWERGEN_LIBS ) + set( DRAWERGEN_LIBS "" ) +endif() + +include_directories( . ) + +file( GLOB HEADER_FILES + *.h + ssa/*.h + fixedfunction/*.h +) + +if( NOT WIN32 ) + set( LLVM_COMPONENTS core support asmparser asmprinter bitreader bitwriter codegen ipo + irreader transformutils instrumentation profiledata runtimedyld + object instcombine linker analysis selectiondag scalaropts vectorize executionengine + mc mcdisassembler mcparser mcjit target x86asmprinter x86info x86desc x86utils x86codegen ) + + # Example LLVM_DIR folder: C:/Development/Environment/Src/llvm-3.9.0/build/lib/cmake/llvm + find_package(LLVM REQUIRED CONFIG) + message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") + message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") + llvm_map_components_to_libnames( llvm_libs ${LLVM_COMPONENTS} ) + include_directories( ${LLVM_INCLUDE_DIRS} ) + set( DRAWERGEN_LIBS ${DRAWERGEN_LIBS} ${llvm_libs} ) +else() + set( LLVM_COMPONENTS core support asmparser asmprinter bitreader bitwriter codegen passes ipo + irreader transformutils instrumentation profiledata debuginfocodeview runtimedyld + object instcombine linker analysis selectiondag scalaropts vectorize executionengine + mc mcdisassembler mcparser mcjit target x86asmprinter x86info x86desc x86utils x86codegen ) + + include_directories( "${LLVM_PRECOMPILED_DIR}/include" ) + if( X64 ) + include_directories( "${LLVM_PRECOMPILED_DIR}/64bit-include" ) + set( llvm_libs_base "${LLVM_PRECOMPILED_DIR}/64bit-" ) + else() + include_directories( "${LLVM_PRECOMPILED_DIR}/32bit-include" ) + set( llvm_libs_base "${LLVM_PRECOMPILED_DIR}/32bit-" ) + endif() + foreach(buildtype IN ITEMS RELEASE DEBUG) + set( llvm_libs_${buildtype} "${llvm_libs_base}${buildtype}" ) + set( LLVM_${buildtype}_LIBS "" ) + foreach( llvm_module ${LLVM_COMPONENTS} ) + find_library( LLVM_${llvm_module}_LIBRARY_${buildtype} LLVM${llvm_module} PATHS ${llvm_libs_${buildtype}} ) + set( LLVM_${buildtype}_LIBS ${LLVM_${buildtype}_LIBS} ${LLVM_${llvm_module}_LIBRARY_${buildtype}} ) + endforeach( llvm_module ) + endforeach(buildtype) +endif() + +if( ZD_CMAKE_COMPILER_IS_GNUCXX_COMPATIBLE ) + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "4.5") + set( CMAKE_C_FLAGS "-Wno-unused-result ${CMAKE_C_FLAGS}" ) + set( CMAKE_CXX_FLAGS "-Wno-unused-result ${CMAKE_CXX_FLAGS}" ) + endif() + if( CMAKE_CXX_COMPILER_ID STREQUAL "Clang" ) + if( APPLE OR CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "3.6" ) + set( CMAKE_CXX_FLAGS "-Wno-inconsistent-missing-override ${CMAKE_CXX_FLAGS}" ) + endif() + endif() + set( CMAKE_C_FLAGS "-Wall -Wextra -Wno-unused -Wno-unused-parameter -Wno-missing-field-initializers -ffp-contract=off ${CMAKE_C_FLAGS}" ) + set( CMAKE_CXX_FLAGS "-Wall -Wextra -Wno-unused -Wno-unused-parameter -Wno-missing-field-initializers -ffp-contract=off ${CMAKE_CXX_FLAGS}" ) + + # Use the highest C++ standard available since VS2015 compiles with C++14 + # but we only require C++11. The recommended way to do this in CMake is to + # probably to use target_compile_features, but I don't feel like maintaining + # a list of features we use. + CHECK_CXX_COMPILER_FLAG( "-std=gnu++14" CAN_DO_CPP14 ) + if ( CAN_DO_CPP14 ) + set ( CMAKE_CXX_FLAGS "-std=gnu++14 ${CMAKE_CXX_FLAGS}" ) + else () + CHECK_CXX_COMPILER_FLAG( "-std=gnu++1y" CAN_DO_CPP1Y ) + if ( CAN_DO_CPP1Y ) + set ( CMAKE_CXX_FLAGS "-std=gnu++1y ${CMAKE_CXX_FLAGS}" ) + else () + CHECK_CXX_COMPILER_FLAG( "-std=gnu++11" CAN_DO_CPP11 ) + if ( CAN_DO_CPP11 ) + set ( CMAKE_CXX_FLAGS "-std=gnu++11 ${CMAKE_CXX_FLAGS}" ) + else () + CHECK_CXX_COMPILER_FLAG( "-std=gnu++0x" CAN_DO_CPP0X ) + if ( CAN_DO_CPP0X ) + set ( CMAKE_CXX_FLAGS "-std=gnu++0x ${CMAKE_CXX_FLAGS}" ) + endif () + endif () + endif () + endif () + + if ( APPLE AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang" ) + set( CMAKE_CXX_FLAGS "-stdlib=libc++ ${CMAKE_CXX_FLAGS}" ) + set( CMAKE_EXE_LINKER_FLAGS "-stdlib=libc++ ${CMAKE_EXE_LINKER_FLAGS}" ) + endif () +endif() + +if( WIN32 ) + if( MSVC_VERSION GREATER 1399 ) + # VC 8+ adds a manifest automatically to the executable. We need to + # merge ours with it. + set( MT_MERGE ON ) + else() + set( TRUSTINFO trustinfo.rc ) + endif() +else( WIN32 ) + set( TRUSTINFO "" ) +endif() + +set (SOURCES + drawergen.cpp + llvmprogram.cpp + llvmdrawers.cpp + ssa/ssa_bool.cpp + ssa/ssa_float.cpp + ssa/ssa_float_ptr.cpp + ssa/ssa_for_block.cpp + ssa/ssa_function.cpp + ssa/ssa_if_block.cpp + ssa/ssa_int.cpp + ssa/ssa_int_ptr.cpp + ssa/ssa_short.cpp + ssa/ssa_scope.cpp + ssa/ssa_struct_type.cpp + ssa/ssa_ubyte.cpp + ssa/ssa_ubyte_ptr.cpp + ssa/ssa_value.cpp + ssa/ssa_vec4f.cpp + ssa/ssa_vec4f_ptr.cpp + ssa/ssa_vec4i.cpp + ssa/ssa_vec4i_ptr.cpp + ssa/ssa_vec8s.cpp + ssa/ssa_vec16ub.cpp + fixedfunction/drawercodegen.cpp + fixedfunction/drawspancodegen.cpp + fixedfunction/drawwallcodegen.cpp + fixedfunction/drawcolumncodegen.cpp + fixedfunction/drawskycodegen.cpp + fixedfunction/drawtrianglecodegen.cpp + fixedfunction/setuptrianglecodegen.cpp +) +enable_precompiled_headers( precomp.h SOURCES ) + +if( NOT CMAKE_CROSSCOMPILING ) + add_executable( drawergen ${SOURCES} ${TRUSTINFO} ${HEADER_FILES} ) + set( CROSS_EXPORTS ${CROSS_EXPORTS} drawergen PARENT_SCOPE ) +endif() + +if( MT_MERGE ) + add_custom_command(TARGET drawergen POST_BUILD + COMMAND mt -inputresource:$ -manifest ${CMAKE_CURRENT_SOURCE_DIR}/trustinfo.txt -outputresource:$ -nologo + COMMENT "Embedding trustinfo into drawergen" ) +endif() + +# Linux - add these flags for LLVM compatibility to prevent crashing +#if ( UNIX AND NOT APPLE ) +# set( CMAKE_EXE_LINKER_FLAGS "-Wl,--exclude-libs,ALL ${CMAKE_EXE_LINKER_FLAGS}" ) +#endif() + +target_link_libraries( drawergen ${DRAWERGEN_LIBS} ) + +if( WIN32 ) + foreach(debuglib ${LLVM_DEBUG_LIBS}) + target_link_libraries( drawergen debug ${debuglib} ) + endforeach(debuglib) + foreach(releaselib ${LLVM_RELEASE_LIBS}) + target_link_libraries( drawergen optimized ${releaselib} ) + endforeach(releaselib) +endif() + +#source_group("Render Compiler" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_compiler/.+") +#source_group("Render Compiler\\SSA" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_compiler/ssa/.+") +#source_group("Render Compiler\\Fixed Function" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/r_compiler/fixedfunction/.+") + +source_group("Compiler" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/.+\\.(cpp|h)$") +source_group("Compiler\\SSA" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/ssa/.+") +source_group("Compiler\\Fixed Function" REGULAR_EXPRESSION "^${CMAKE_CURRENT_SOURCE_DIR}/fixedfunction/.+") diff --git a/tools/drawergen/drawergen.cpp b/tools/drawergen/drawergen.cpp new file mode 100644 index 000000000..ecf87062e --- /dev/null +++ b/tools/drawergen/drawergen.cpp @@ -0,0 +1,138 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "exception.h" +#include "llvmdrawers.h" + +std::string &AllTimestamps() +{ + static std::string timestamps; + return timestamps; +} + +void AddSourceFileTimestamp(const char *timestamp) +{ + if (!AllTimestamps().empty()) AllTimestamps().push_back(' '); + AllTimestamps() += timestamp; +} + +int main(int argc, char **argv) +{ + try + { + if (argc != 2) + { + std::cerr << "Usage: " << argv[0] << "" << std::endl; + return 1; + } + + std::string timestamp_filename = argv[1] + std::string(".timestamp"); + + FILE *file = fopen(timestamp_filename.c_str(), "rb"); + if (file != nullptr) + { + char buffer[4096]; + int bytes_read = fread(buffer, 1, 4096, file); + fclose(file); + std::string last_timestamp; + if (bytes_read > 0) + last_timestamp = std::string(buffer, bytes_read); + + if (AllTimestamps() == last_timestamp) + { + std::cout << "Not recompiling drawers because the object file is already up to date." << std::endl; + exit(0); + } + } + + llvm::install_fatal_error_handler([](void *user_data, const std::string& reason, bool gen_crash_diag) + { + std::cerr << "LLVM fatal error: " << reason; + exit(1); + }); + + llvm::InitializeNativeTarget(); + llvm::InitializeNativeTargetAsmPrinter(); + + std::string triple = llvm::sys::getDefaultTargetTriple(); + +#ifdef __APPLE__ + // Target triple is x86_64-apple-darwin15.6.0 + auto pos = triple.find("-apple-darwin"); + if (pos != std::string::npos) + { + triple = triple.substr(0, pos) + "-apple-darwin10.11.0"; + } +#endif + + std::cout << "Target triple is " << triple << std::endl; + + std::string cpuName = "pentium4"; + std::string features; + std::cout << "Compiling drawer code for " << cpuName << ".." << std::endl; + + LLVMDrawers drawersSSE2(triple, cpuName, features, "_SSE2"); + + file = fopen(argv[1], "wb"); + if (file == nullptr) + { + std::cerr << "Unable to open " << argv[1] << " for writing." << std::endl; + return 1; + } + + int result = fwrite(drawersSSE2.ObjectFile.data(), drawersSSE2.ObjectFile.size(), 1, file); + fclose(file); + + if (result != 1) + { + std::cerr << "Could not write data to " << argv[1] << std::endl; + return 1; + } + + file = fopen(timestamp_filename.c_str(), "wb"); + if (file == nullptr) + { + std::cerr << "Could not create timestamp file" << std::endl; + return 1; + } + result = fwrite(AllTimestamps().data(), AllTimestamps().length(), 1, file); + fclose(file); + if (result != 1) + { + std::cerr << "Could not write timestamp file" << std::endl; + return 1; + } + + //LLVMDrawers drawersSSE4("core2"); + //LLVMDrawers drawersAVX("sandybridge"); + //LLVMDrawers drawersAVX2("haswell"); + + return 0; + } + catch (const std::exception &e) + { + std::cerr << e.what() << std::endl; + return 1; + } +} diff --git a/tools/drawergen/exception.h b/tools/drawergen/exception.h new file mode 100644 index 000000000..22d3c18fb --- /dev/null +++ b/tools/drawergen/exception.h @@ -0,0 +1,36 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include +#include + +class Exception : public std::exception +{ +public: + Exception(const std::string &message) : message(message) { } + const char *what() const noexcept override { return message.c_str(); } + +private: + std::string message; +}; diff --git a/tools/drawergen/fixedfunction/drawcolumncodegen.cpp b/tools/drawergen/fixedfunction/drawcolumncodegen.cpp new file mode 100644 index 000000000..6e00528ae --- /dev/null +++ b/tools/drawergen/fixedfunction/drawcolumncodegen.cpp @@ -0,0 +1,322 @@ +/* +** DrawColumn code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/drawcolumncodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +void DrawColumnCodegen::Generate(DrawColumnVariant variant, SSAValue args, SSAValue thread_data) +{ + dest = args[0][0].load(true); + source = args[0][1].load(true); + source2 = args[0][2].load(true); + colormap = args[0][3].load(true); + translation = args[0][4].load(true); + basecolors = args[0][5].load(true); + pitch = args[0][6].load(true); + count = args[0][7].load(true); + dest_y = args[0][8].load(true); + iscale = args[0][9].load(true); + texturefracx = args[0][10].load(true); + textureheight = args[0][11].load(true); + texturefrac = args[0][12].load(true); + light = args[0][13].load(true); + color = SSAVec4i::unpack(args[0][14].load(true)); + srccolor = SSAVec4i::unpack(args[0][15].load(true)); + srcalpha = args[0][16].load(true); + destalpha = args[0][17].load(true); + SSAShort light_alpha = args[0][18].load(true); + SSAShort light_red = args[0][19].load(true); + SSAShort light_green = args[0][20].load(true); + SSAShort light_blue = args[0][21].load(true); + SSAShort fade_alpha = args[0][22].load(true); + SSAShort fade_red = args[0][23].load(true); + SSAShort fade_green = args[0][24].load(true); + SSAShort fade_blue = args[0][25].load(true); + SSAShort desaturate = args[0][26].load(true); + SSAInt flags = args[0][27].load(true); + shade_constants.light = SSAVec4i(light_blue.zext_int(), light_green.zext_int(), light_red.zext_int(), light_alpha.zext_int()); + shade_constants.fade = SSAVec4i(fade_blue.zext_int(), fade_green.zext_int(), fade_red.zext_int(), fade_alpha.zext_int()); + shade_constants.desaturate = desaturate.zext_int(); + + thread.core = thread_data[0][0].load(true); + thread.num_cores = thread_data[0][1].load(true); + thread.pass_start_y = thread_data[0][2].load(true); + thread.pass_end_y = thread_data[0][3].load(true); + thread.temp = thread_data[0][4].load(true); + + is_simple_shade = (flags & DrawColumnArgs::simple_shade) == SSAInt(DrawColumnArgs::simple_shade); + is_nearest_filter = (flags & DrawColumnArgs::nearest_filter) == SSAInt(DrawColumnArgs::nearest_filter); + + count = count_for_thread(dest_y, count, thread); + dest = dest_for_thread(dest_y, pitch, dest, thread); + pitch = pitch * thread.num_cores; + + stack_frac.store(texturefrac + iscale * skipped_by_thread(dest_y, thread)); + iscale = iscale * thread.num_cores; + one = (1 << 30) / textureheight; + + SSAIfBlock branch; + branch.if_block(is_simple_shade); + LoopShade(variant, true); + branch.else_block(); + LoopShade(variant, false); + branch.end_block(); +} + +void DrawColumnCodegen::LoopShade(DrawColumnVariant variant, bool isSimpleShade) +{ + SSAIfBlock branch; + branch.if_block(is_nearest_filter); + Loop(variant, isSimpleShade, true); + branch.else_block(); + stack_frac.store(stack_frac.load() - (one >> 1)); + Loop(variant, isSimpleShade, false); + branch.end_block(); +} + +void DrawColumnCodegen::Loop(DrawColumnVariant variant, bool isSimpleShade, bool isNearestFilter) +{ + stack_index.store(SSAInt(0)); + { + SSAForBlock loop; + SSAInt index = stack_index.load(); + loop.loop_block(index < count); + + SSAInt sample_index, frac; + frac = stack_frac.load(); + if (IsPaletteInput(variant)) + sample_index = frac >> FRACBITS; + else + sample_index = frac; + + SSAInt offset = index * pitch * 4; + SSAVec4i bgcolor = dest[offset].load_vec4ub(false); + + SSAVec4i outcolor = ProcessPixel(sample_index, bgcolor, variant, isSimpleShade, isNearestFilter); + + dest[offset].store_vec4ub(outcolor); + + stack_index.store(index.add(SSAInt(1), true, true)); + stack_frac.store(frac + iscale); + loop.end_block(); + } +} + +bool DrawColumnCodegen::IsPaletteInput(DrawColumnVariant variant) +{ + switch (variant) + { + default: + case DrawColumnVariant::DrawCopy: + case DrawColumnVariant::Draw: + case DrawColumnVariant::DrawAdd: + case DrawColumnVariant::DrawAddClamp: + case DrawColumnVariant::DrawSubClamp: + case DrawColumnVariant::DrawRevSubClamp: + case DrawColumnVariant::Fill: + case DrawColumnVariant::FillAdd: + case DrawColumnVariant::FillAddClamp: + case DrawColumnVariant::FillSubClamp: + case DrawColumnVariant::FillRevSubClamp: + return false; + case DrawColumnVariant::DrawShaded: + case DrawColumnVariant::DrawTranslated: + case DrawColumnVariant::DrawTlatedAdd: + case DrawColumnVariant::DrawAddClampTranslated: + case DrawColumnVariant::DrawSubClampTranslated: + case DrawColumnVariant::DrawRevSubClampTranslated: + return true; + } +} + +SSAVec4i DrawColumnCodegen::ProcessPixel(SSAInt sample_index, SSAVec4i bgcolor, DrawColumnVariant variant, bool isSimpleShade, bool isNearestFilter) +{ + SSAInt alpha, inv_alpha; + SSAVec4i fg; + switch (variant) + { + default: + case DrawColumnVariant::DrawCopy: + return blend_copy(Sample(sample_index, isNearestFilter)); + case DrawColumnVariant::Draw: + return blend_copy(Shade(Sample(sample_index, isNearestFilter), isSimpleShade)); + case DrawColumnVariant::DrawAdd: + case DrawColumnVariant::DrawAddClamp: + fg = Shade(Sample(sample_index, isNearestFilter), isSimpleShade); + return blend_add(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::DrawShaded: + alpha = SSAInt::MAX(SSAInt::MIN(ColormapSample(sample_index), SSAInt(64)), SSAInt(0)) * 4; + inv_alpha = 256 - alpha; + return blend_add(color, bgcolor, alpha, inv_alpha); + case DrawColumnVariant::DrawSubClamp: + fg = Shade(Sample(sample_index, isNearestFilter), isSimpleShade); + return blend_sub(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::DrawRevSubClamp: + fg = Shade(Sample(sample_index, isNearestFilter), isSimpleShade); + return blend_revsub(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::DrawTranslated: + return blend_copy(Shade(TranslateSample(sample_index), isSimpleShade)); + case DrawColumnVariant::DrawTlatedAdd: + case DrawColumnVariant::DrawAddClampTranslated: + fg = Shade(TranslateSample(sample_index), isSimpleShade); + return blend_add(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::DrawSubClampTranslated: + fg = Shade(TranslateSample(sample_index), isSimpleShade); + return blend_sub(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::DrawRevSubClampTranslated: + fg = Shade(TranslateSample(sample_index), isSimpleShade); + return blend_revsub(fg, bgcolor, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawColumnVariant::Fill: + return blend_copy(color); + case DrawColumnVariant::FillAdd: + alpha = srccolor[3]; + alpha = alpha + (alpha >> 7); + inv_alpha = 256 - alpha; + return blend_add(srccolor, bgcolor, alpha, inv_alpha); + case DrawColumnVariant::FillAddClamp: + return blend_add(srccolor, bgcolor, srcalpha, destalpha); + case DrawColumnVariant::FillSubClamp: + return blend_sub(srccolor, bgcolor, srcalpha, destalpha); + case DrawColumnVariant::FillRevSubClamp: + return blend_revsub(srccolor, bgcolor, srcalpha, destalpha); + } +} + +SSAVec4i DrawColumnCodegen::ProcessPixelPal(SSAInt sample_index, SSAVec4i bgcolor, DrawColumnVariant variant, bool isSimpleShade) +{ + SSAInt alpha, inv_alpha; + switch (variant) + { + default: + case DrawColumnVariant::DrawCopy: + return blend_copy(basecolors[ColormapSample(sample_index) * 4].load_vec4ub(true)); + case DrawColumnVariant::Draw: + return blend_copy(ShadePal(ColormapSample(sample_index), isSimpleShade)); + case DrawColumnVariant::DrawAdd: + case DrawColumnVariant::DrawAddClamp: + return blend_add(ShadePal(ColormapSample(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::DrawShaded: + alpha = SSAInt::MAX(SSAInt::MIN(ColormapSample(sample_index), SSAInt(64)), SSAInt(0)) * 4; + inv_alpha = 256 - alpha; + return blend_add(color, bgcolor, alpha, inv_alpha); + case DrawColumnVariant::DrawSubClamp: + return blend_sub(ShadePal(ColormapSample(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::DrawRevSubClamp: + return blend_revsub(ShadePal(ColormapSample(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::DrawTranslated: + return blend_copy(ShadePal(TranslateSamplePal(sample_index), isSimpleShade)); + case DrawColumnVariant::DrawTlatedAdd: + case DrawColumnVariant::DrawAddClampTranslated: + return blend_add(ShadePal(TranslateSamplePal(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::DrawSubClampTranslated: + return blend_sub(ShadePal(TranslateSamplePal(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::DrawRevSubClampTranslated: + return blend_revsub(ShadePal(TranslateSamplePal(sample_index), isSimpleShade), bgcolor, srcalpha, destalpha); + case DrawColumnVariant::Fill: + return blend_copy(color); + case DrawColumnVariant::FillAdd: + alpha = srccolor[3]; + alpha = alpha + (alpha >> 7); + inv_alpha = 256 - alpha; + return blend_add(srccolor, bgcolor, alpha, inv_alpha); + case DrawColumnVariant::FillAddClamp: + return blend_add(srccolor, bgcolor, srcalpha, destalpha); + case DrawColumnVariant::FillSubClamp: + return blend_sub(srccolor, bgcolor, srcalpha, destalpha); + case DrawColumnVariant::FillRevSubClamp: + return blend_revsub(srccolor, bgcolor, srcalpha, destalpha); + } +} + +SSAVec4i DrawColumnCodegen::Sample(SSAInt frac, bool isNearestFilter) +{ + if (isNearestFilter) + { + SSAInt sample_index = (((frac << 2) >> FRACBITS) * textureheight) >> FRACBITS; + return source[sample_index * 4].load_vec4ub(false); + } + else + { + return SampleLinear(source, source2, texturefracx, frac, one, textureheight); + } +} + +SSAVec4i DrawColumnCodegen::SampleLinear(SSAUBytePtr col0, SSAUBytePtr col1, SSAInt texturefracx, SSAInt texturefracy, SSAInt one, SSAInt height) +{ + // Clamp to edge + SSAInt frac_y0 = (SSAInt::MAX(SSAInt::MIN(texturefracy, SSAInt((1 << 30) - 1)), SSAInt(0)) >> (FRACBITS - 2)) * height; + SSAInt frac_y1 = (SSAInt::MAX(SSAInt::MIN(texturefracy + one, SSAInt((1 << 30) - 1)), SSAInt(0)) >> (FRACBITS - 2)) * height; + SSAInt y0 = frac_y0 >> FRACBITS; + SSAInt y1 = frac_y1 >> FRACBITS; + + SSAVec4i p00 = col0[y0 * 4].load_vec4ub(true); + SSAVec4i p01 = col0[y1 * 4].load_vec4ub(true); + SSAVec4i p10 = col1[y0 * 4].load_vec4ub(true); + SSAVec4i p11 = col1[y1 * 4].load_vec4ub(true); + + SSAInt inv_b = texturefracx; + SSAInt inv_a = (frac_y1 >> (FRACBITS - 4)) & 15; + SSAInt a = 16 - inv_a; + SSAInt b = 16 - inv_b; + + return (p00 * (a * b) + p01 * (inv_a * b) + p10 * (a * inv_b) + p11 * (inv_a * inv_b) + 127) >> 8; +} + +SSAInt DrawColumnCodegen::ColormapSample(SSAInt sample_index) +{ + return colormap[source[sample_index].load(true).zext_int()].load(true).zext_int(); +} + +SSAVec4i DrawColumnCodegen::TranslateSample(SSAInt sample_index) +{ + return translation[source[sample_index].load(true).zext_int() * 4].load_vec4ub(true); +} + +SSAInt DrawColumnCodegen::TranslateSamplePal(SSAInt sample_index) +{ + return translation[source[sample_index].load(true).zext_int()].load(true).zext_int(); +} + +SSAVec4i DrawColumnCodegen::Shade(SSAVec4i fg, bool isSimpleShade) +{ + if (isSimpleShade) + return shade_bgra_simple(fg, light); + else + return shade_bgra_advanced(fg, light, shade_constants); +} + +SSAVec4i DrawColumnCodegen::ShadePal(SSAInt palIndex, bool isSimpleShade) +{ + if (isSimpleShade) + return shade_pal_index_simple(palIndex, light, basecolors); + else + return shade_pal_index_advanced(palIndex, light, shade_constants, basecolors); +} diff --git a/tools/drawergen/fixedfunction/drawcolumncodegen.h b/tools/drawergen/fixedfunction/drawcolumncodegen.h new file mode 100644 index 000000000..905654911 --- /dev/null +++ b/tools/drawergen/fixedfunction/drawcolumncodegen.h @@ -0,0 +1,92 @@ +/* +** DrawColumn code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +enum class DrawColumnVariant +{ + Fill, + FillAdd, + FillAddClamp, + FillSubClamp, + FillRevSubClamp, + DrawCopy, + Draw, + DrawAdd, + DrawTranslated, + DrawTlatedAdd, + DrawShaded, + DrawAddClamp, + DrawAddClampTranslated, + DrawSubClamp, + DrawSubClampTranslated, + DrawRevSubClamp, + DrawRevSubClampTranslated +}; + +class DrawColumnCodegen : public DrawerCodegen +{ +public: + void Generate(DrawColumnVariant variant, SSAValue args, SSAValue thread_data); + +private: + void LoopShade(DrawColumnVariant variant, bool isSimpleShade); + void Loop(DrawColumnVariant variant, bool isSimpleShade, bool isNearestFilter); + SSAVec4i ProcessPixel(SSAInt sample_index, SSAVec4i bgcolor, DrawColumnVariant variant, bool isSimpleShade, bool isNearestFilter); + SSAVec4i ProcessPixelPal(SSAInt sample_index, SSAVec4i bgcolor, DrawColumnVariant variant, bool isSimpleShade); + SSAVec4i Sample(SSAInt frac, bool isNearestFilter); + SSAVec4i SampleLinear(SSAUBytePtr col0, SSAUBytePtr col1, SSAInt texturefracx, SSAInt texturefracy, SSAInt one, SSAInt height); + SSAInt ColormapSample(SSAInt frac); + SSAVec4i TranslateSample(SSAInt frac); + SSAInt TranslateSamplePal(SSAInt frac); + SSAVec4i Shade(SSAVec4i fgcolor, bool isSimpleShade); + SSAVec4i ShadePal(SSAInt palIndex, bool isSimpleShade); + bool IsPaletteInput(DrawColumnVariant variant); + + SSAStack stack_index, stack_frac; + + SSAUBytePtr dest; + SSAUBytePtr source; + SSAUBytePtr source2; + SSAUBytePtr colormap; + SSAUBytePtr translation; + SSAUBytePtr basecolors; + SSAInt pitch; + SSAInt count; + SSAInt dest_y; + SSAInt iscale; + SSAInt texturefracx; + SSAInt textureheight; + SSAInt one; + SSAInt texturefrac; + SSAInt light; + SSAVec4i color; + SSAVec4i srccolor; + SSAInt srcalpha; + SSAInt destalpha; + SSABool is_simple_shade; + SSABool is_nearest_filter; + SSAShadeConstants shade_constants; + SSAWorkerThread thread; +}; diff --git a/tools/drawergen/fixedfunction/drawercodegen.cpp b/tools/drawergen/fixedfunction/drawercodegen.cpp new file mode 100644 index 000000000..f7a67e5a6 --- /dev/null +++ b/tools/drawergen/fixedfunction/drawercodegen.cpp @@ -0,0 +1,169 @@ +/* +** Drawer code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/drawercodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +SSABool DrawerCodegen::line_skipped_by_thread(SSAInt line, SSAWorkerThread thread) +{ + return line < thread.pass_start_y || line >= thread.pass_end_y || !(line % thread.num_cores == thread.core); +} + +SSAInt DrawerCodegen::skipped_by_thread(SSAInt first_line, SSAWorkerThread thread) +{ + SSAInt pass_skip = SSAInt::MAX(thread.pass_start_y - first_line, SSAInt(0)); + SSAInt core_skip = (thread.num_cores - (first_line + pass_skip - thread.core) % thread.num_cores) % thread.num_cores; + return pass_skip + core_skip; +} + +SSAInt DrawerCodegen::count_for_thread(SSAInt first_line, SSAInt count, SSAWorkerThread thread) +{ + SSAInt lines_until_pass_end = SSAInt::MAX(thread.pass_end_y - first_line, SSAInt(0)); + count = SSAInt::MIN(count, lines_until_pass_end); + SSAInt c = (count - skipped_by_thread(first_line, thread) + thread.num_cores - 1) / thread.num_cores; + return SSAInt::MAX(c, SSAInt(0)); +} + +SSAUBytePtr DrawerCodegen::dest_for_thread(SSAInt first_line, SSAInt pitch, SSAUBytePtr dest, SSAWorkerThread thread) +{ + return dest[skipped_by_thread(first_line, thread) * pitch * 4]; +} + +SSAInt DrawerCodegen::calc_light_multiplier(SSAInt light) +{ + return 256 - (light >> (FRACBITS - 8)); +} + +SSAVec4i DrawerCodegen::shade_pal_index_simple(SSAInt index, SSAInt light, SSAUBytePtr basecolors) +{ + SSAVec4i color = basecolors[index * 4].load_vec4ub(true); // = GPalette.BaseColors[index]; + return shade_bgra_simple(color, light); +} + +SSAVec4i DrawerCodegen::shade_pal_index_advanced(SSAInt index, SSAInt light, const SSAShadeConstants &constants, SSAUBytePtr basecolors) +{ + SSAVec4i color = basecolors[index * 4].load_vec4ub(true); // = GPalette.BaseColors[index]; + return shade_bgra_advanced(color, light, constants); +} + +SSAVec4i DrawerCodegen::shade_bgra_simple(SSAVec4i color, SSAInt light) +{ + SSAInt alpha = color[3]; + color = color * light / 256; + return color.insert(3, alpha); +} + +SSAVec4i DrawerCodegen::shade_bgra_advanced(SSAVec4i color, SSAInt light, const SSAShadeConstants &constants) +{ + SSAInt blue = color[0]; + SSAInt green = color[1]; + SSAInt red = color[2]; + SSAInt alpha = color[3]; + + SSAInt intensity = ((red * 77 + green * 143 + blue * 37) >> 8) * constants.desaturate; + + SSAVec4i inv_light = 256 - light; + SSAVec4i inv_desaturate = 256 - constants.desaturate; + + color = (color * inv_desaturate + intensity) / 256; + color = (constants.fade * inv_light + color * light) / 256; + color = (color * constants.light) / 256; + + return color.insert(3, alpha); +} + +SSAVec4i DrawerCodegen::blend_copy(SSAVec4i fg) +{ + return fg; +} + +SSAVec4i DrawerCodegen::blend_add(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha) +{ + SSAInt alpha = fg[3]; + alpha = alpha + (alpha >> 7); // 255 -> 256 + srcalpha = (alpha * srcalpha + 128) >> 8; + SSAVec4i color = (fg * srcalpha + bg * destalpha) / 256; + return color.insert(3, 255); +} + +SSAVec4i DrawerCodegen::blend_sub(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha) +{ + SSAInt alpha = fg[3]; + alpha = alpha + (alpha >> 7); // 255 -> 256 + srcalpha = (alpha * srcalpha + 128) >> 8; + SSAVec4i color = (fg * srcalpha - bg * destalpha) / 256; + return color.insert(3, 255); +} + +SSAVec4i DrawerCodegen::blend_revsub(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha) +{ + SSAInt alpha = fg[3]; + alpha = alpha + (alpha >> 7); // 255 -> 256 + srcalpha = (alpha * srcalpha + 128) >> 8; + SSAVec4i color = (bg * destalpha - fg * srcalpha) / 256; + return color.insert(3, 255); +} + +SSAVec4i DrawerCodegen::blend_alpha_blend(SSAVec4i fg, SSAVec4i bg) +{ + SSAInt alpha = fg[3]; + alpha = alpha + (alpha >> 7); // 255 -> 256 + SSAInt inv_alpha = 256 - alpha; + SSAVec4i color = (fg * alpha + bg * inv_alpha) / 256; + return color.insert(3, 255); +} + +SSAInt DrawerCodegen::calc_blend_bgalpha(SSAVec4i fg, SSAInt destalpha) +{ + SSAInt alpha = fg[3]; + alpha = alpha + (alpha >> 7); + SSAInt inv_alpha = 256 - alpha; + return (destalpha * alpha + 256 * inv_alpha + 128) >> 8; +} + +SSAVec4i DrawerCodegen::blend_stencil(SSAVec4i stencilcolor, SSAInt fgalpha, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha) +{ + fgalpha = fgalpha + (fgalpha >> 7); // 255 -> 256 + SSAInt inv_fgalpha = 256 - fgalpha; + + srcalpha = (fgalpha * srcalpha + 128) >> 8; + destalpha = (destalpha * fgalpha + 256 * inv_fgalpha + 128) >> 8; + + SSAVec4i color = (stencilcolor * srcalpha + bg * destalpha) / 256; + return color.insert(3, 255); +} + +SSAVec4i DrawerCodegen::blend_add_srccolor_oneminussrccolor(SSAVec4i fg, SSAVec4i bg) +{ + SSAVec4i fgcolor = fg + (fg >> 7); // 255 -> 256 + SSAVec4i inv_fgcolor = SSAVec4i(256) - fgcolor; + return fg + ((bg * inv_fgcolor + 128) >> 8); +} diff --git a/tools/drawergen/fixedfunction/drawercodegen.h b/tools/drawergen/fixedfunction/drawercodegen.h new file mode 100644 index 000000000..d1931e99c --- /dev/null +++ b/tools/drawergen/fixedfunction/drawercodegen.h @@ -0,0 +1,96 @@ +/* +** Drawer code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "precomp.h" +#include "ssa/ssa_value.h" +#include "ssa/ssa_vec4f.h" +#include "ssa/ssa_vec4i.h" +#include "ssa/ssa_vec8s.h" +#include "ssa/ssa_vec16ub.h" +#include "ssa/ssa_int.h" +#include "ssa/ssa_int_ptr.h" +#include "ssa/ssa_short.h" +#include "ssa/ssa_ubyte_ptr.h" +#include "ssa/ssa_vec4f_ptr.h" +#include "ssa/ssa_vec4i_ptr.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_bool.h" +#include "ssa/ssa_barycentric_weight.h" +#include "llvm_include.h" + +class SSAWorkerThread +{ +public: + SSAInt core; + SSAInt num_cores; + SSAInt pass_start_y; + SSAInt pass_end_y; + SSAUBytePtr temp; +}; + +class SSAShadeConstants +{ +public: + SSAVec4i light; + SSAVec4i fade; + SSAInt desaturate; +}; + +class DrawerCodegen +{ +public: + // Checks if a line is rendered by this thread + SSABool line_skipped_by_thread(SSAInt line, SSAWorkerThread thread); + + // The number of lines to skip to reach the first line to be rendered by this thread + SSAInt skipped_by_thread(SSAInt first_line, SSAWorkerThread thread); + + // The number of lines to be rendered by this thread + SSAInt count_for_thread(SSAInt first_line, SSAInt count, SSAWorkerThread thread); + + // Calculate the dest address for the first line to be rendered by this thread + SSAUBytePtr dest_for_thread(SSAInt first_line, SSAInt pitch, SSAUBytePtr dest, SSAWorkerThread thread); + + // LightBgra + SSAInt calc_light_multiplier(SSAInt light); + SSAVec4i shade_pal_index_simple(SSAInt index, SSAInt light, SSAUBytePtr basecolors); + SSAVec4i shade_pal_index_advanced(SSAInt index, SSAInt light, const SSAShadeConstants &constants, SSAUBytePtr basecolors); + SSAVec4i shade_bgra_simple(SSAVec4i color, SSAInt light); + SSAVec4i shade_bgra_advanced(SSAVec4i color, SSAInt light, const SSAShadeConstants &constants); + + // BlendBgra + SSAVec4i blend_copy(SSAVec4i fg); + SSAVec4i blend_add(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha); + SSAVec4i blend_sub(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha); + SSAVec4i blend_revsub(SSAVec4i fg, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha); + SSAVec4i blend_alpha_blend(SSAVec4i fg, SSAVec4i bg); + SSAVec4i blend_stencil(SSAVec4i color, SSAInt fgalpha, SSAVec4i bg, SSAInt srcalpha, SSAInt destalpha); + SSAVec4i blend_add_srccolor_oneminussrccolor(SSAVec4i fg, SSAVec4i bg); + + // Calculates the final alpha values to be used when combined with the source texture alpha channel + SSAInt calc_blend_bgalpha(SSAVec4i fg, SSAInt destalpha); +}; + +#define FRACBITS 16 +#define FRACUNIT (1<> FRACBITS) * textureheight0) >> FRACBITS; + if (variant == DrawSkyVariant::Single) + { + return source0[index][sample_index * 4].load_vec4ub(false); + } + else + { + SSAInt sample_index2 = SSAInt::MIN(sample_index, maxtextureheight1); + SSAVec4i color0 = source0[index][sample_index * 4].load_vec4ub(false); + SSAVec4i color1 = source1[index][sample_index2 * 4].load_vec4ub(false); + return blend_alpha_blend(color0, color1); + } +} + +SSAVec4i DrawSkyCodegen::FadeOut(SSAInt frac, SSAVec4i color) +{ + int start_fade = 2; // How fast it should fade out + + SSAInt alpha_top = SSAInt::MAX(SSAInt::MIN(frac.ashr(16 - start_fade), SSAInt(256)), SSAInt(0)); + SSAInt alpha_bottom = SSAInt::MAX(SSAInt::MIN(((2 << 24) - frac).ashr(16 - start_fade), SSAInt(256)), SSAInt(0)); + SSAInt inv_alpha_top = 256 - alpha_top; + SSAInt inv_alpha_bottom = 256 - alpha_bottom; + + color = (color * alpha_top + top_color * inv_alpha_top) / 256; + color = (color * alpha_bottom + bottom_color * inv_alpha_bottom) / 256; + return color.insert(3, 255); +} diff --git a/tools/drawergen/fixedfunction/drawskycodegen.h b/tools/drawergen/fixedfunction/drawskycodegen.h new file mode 100644 index 000000000..aaf4bdfeb --- /dev/null +++ b/tools/drawergen/fixedfunction/drawskycodegen.h @@ -0,0 +1,60 @@ +/* +** DrawSky code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +enum class DrawSkyVariant +{ + Single, + Double +}; + +class DrawSkyCodegen : public DrawerCodegen +{ +public: + void Generate(DrawSkyVariant variant, bool fourColumns, SSAValue args, SSAValue thread_data); + +private: + void Loop(DrawSkyVariant variant, bool fourColumns); + SSAVec4i Sample(SSAInt frac, int index, DrawSkyVariant variant); + SSAVec4i FadeOut(SSAInt frac, SSAVec4i color); + + SSAStack stack_index, stack_frac[4]; + + SSAUBytePtr dest; + SSAUBytePtr source0[4]; + SSAUBytePtr source1[4]; + SSAInt pitch; + SSAInt count; + SSAInt dest_y; + SSAInt texturefrac[4]; + SSAInt iscale[4]; + SSAInt textureheight0; + SSAInt maxtextureheight1; + SSAVec4i top_color; + SSAVec4i bottom_color; + SSAWorkerThread thread; + + SSAInt fracstep[4]; +}; diff --git a/tools/drawergen/fixedfunction/drawspancodegen.cpp b/tools/drawergen/fixedfunction/drawspancodegen.cpp new file mode 100644 index 000000000..2272acf8d --- /dev/null +++ b/tools/drawergen/fixedfunction/drawspancodegen.cpp @@ -0,0 +1,287 @@ +/* +** DrawSpan code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/drawspancodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +void DrawSpanCodegen::Generate(DrawSpanVariant variant, SSAValue args) +{ + destorg = args[0][0].load(true); + source = args[0][1].load(true); + destpitch = args[0][2].load(true); + stack_xfrac.store(args[0][3].load(true)); + stack_yfrac.store(args[0][4].load(true)); + xstep = args[0][5].load(true); + ystep = args[0][6].load(true); + x1 = args[0][7].load(true); + x2 = args[0][8].load(true); + y = args[0][9].load(true); + xbits = args[0][10].load(true); + ybits = args[0][11].load(true); + light = args[0][12].load(true); + srcalpha = args[0][13].load(true); + destalpha = args[0][14].load(true); + SSAShort light_alpha = args[0][15].load(true); + SSAShort light_red = args[0][16].load(true); + SSAShort light_green = args[0][17].load(true); + SSAShort light_blue = args[0][18].load(true); + SSAShort fade_alpha = args[0][19].load(true); + SSAShort fade_red = args[0][20].load(true); + SSAShort fade_green = args[0][21].load(true); + SSAShort fade_blue = args[0][22].load(true); + SSAShort desaturate = args[0][23].load(true); + SSAInt flags = args[0][24].load(true); + start_viewpos_x = args[0][25].load(true); + step_viewpos_x = args[0][26].load(true); + dynlights = args[0][27].load(true); + num_dynlights = args[0][28].load(true); + shade_constants.light = SSAVec4i(light_blue.zext_int(), light_green.zext_int(), light_red.zext_int(), light_alpha.zext_int()); + shade_constants.fade = SSAVec4i(fade_blue.zext_int(), fade_green.zext_int(), fade_red.zext_int(), fade_alpha.zext_int()); + shade_constants.desaturate = desaturate.zext_int(); + + count = x2 - x1 + 1; + data = destorg[(x1 + y * destpitch) * 4]; + + yshift = 32 - ybits; + xshift = yshift - xbits; + xmask = ((SSAInt(1) << xbits) - 1) << ybits; + + // 64x64 is the most common case by far, so special case it. + is_64x64 = xbits == SSAInt(6) && ybits == SSAInt(6); + is_simple_shade = (flags & DrawSpanArgs::simple_shade) == SSAInt(DrawSpanArgs::simple_shade); + is_nearest_filter = (flags & DrawSpanArgs::nearest_filter) == SSAInt(DrawSpanArgs::nearest_filter); + + SSAIfBlock branch; + branch.if_block(is_simple_shade); + LoopShade(variant, true); + branch.else_block(); + LoopShade(variant, false); + branch.end_block(); +} + +void DrawSpanCodegen::LoopShade(DrawSpanVariant variant, bool isSimpleShade) +{ + SSAIfBlock branch; + branch.if_block(is_nearest_filter); + LoopFilter(variant, isSimpleShade, true); + branch.else_block(); + stack_xfrac.store(stack_xfrac.load() - (SSAInt(1) << (31 - xbits))); + stack_yfrac.store(stack_yfrac.load() - (SSAInt(1) << (31 - ybits))); + LoopFilter(variant, isSimpleShade, false); + branch.end_block(); +} + +void DrawSpanCodegen::LoopFilter(DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter) +{ + SSAIfBlock branch; + branch.if_block(is_64x64); + { + SSAInt sseLength = Loop4x(variant, isSimpleShade, isNearestFilter, true); + Loop(sseLength * 4, variant, isSimpleShade, isNearestFilter, true); + } + branch.else_block(); + { + SSAInt sseLength = Loop4x(variant, isSimpleShade, isNearestFilter, false); + Loop(sseLength * 4, variant, isSimpleShade, isNearestFilter, false); + } + branch.end_block(); +} + +SSAInt DrawSpanCodegen::Loop4x(DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter, bool is64x64) +{ + SSAInt sseLength = count / 4; + stack_index.store(SSAInt(0)); + stack_viewpos_x.store(start_viewpos_x); + { + SSAForBlock loop; + SSAInt index = stack_index.load(); + loop.loop_block(index < sseLength); + + SSAVec16ub bg = data[index * 16].load_unaligned_vec16ub(false); + SSAVec8s bg0 = SSAVec8s::extendlo(bg); + SSAVec8s bg1 = SSAVec8s::extendhi(bg); + SSAVec4i bgcolors[4] = + { + SSAVec4i::extendlo(bg0), + SSAVec4i::extendhi(bg0), + SSAVec4i::extendlo(bg1), + SSAVec4i::extendhi(bg1) + }; + + SSAVec4i colors[4]; + for (int i = 0; i < 4; i++) + { + SSAInt xfrac = stack_xfrac.load(); + SSAInt yfrac = stack_yfrac.load(); + viewpos_x = stack_viewpos_x.load(); + + colors[i] = Blend(Shade(Sample(xfrac, yfrac, isNearestFilter, is64x64), isSimpleShade), bgcolors[i], variant); + + stack_viewpos_x.store(viewpos_x + step_viewpos_x); + stack_xfrac.store(xfrac + xstep); + stack_yfrac.store(yfrac + ystep); + } + + SSAVec16ub color(SSAVec8s(colors[0], colors[1]), SSAVec8s(colors[2], colors[3])); + data[index * 16].store_unaligned_vec16ub(color); + + stack_index.store(index.add(SSAInt(1), true, true)); + loop.end_block(); + } + return sseLength; +} + +void DrawSpanCodegen::Loop(SSAInt start, DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter, bool is64x64) +{ + stack_index.store(start); + { + SSAForBlock loop; + SSAInt index = stack_index.load(); + viewpos_x = stack_viewpos_x.load(); + loop.loop_block(index < count); + + SSAInt xfrac = stack_xfrac.load(); + SSAInt yfrac = stack_yfrac.load(); + + SSAVec4i bgcolor = data[index * 4].load_vec4ub(false); + SSAVec4i color = Blend(Shade(Sample(xfrac, yfrac, isNearestFilter, is64x64), isSimpleShade), bgcolor, variant); + data[index * 4].store_vec4ub(color); + + stack_viewpos_x.store(viewpos_x + step_viewpos_x); + stack_index.store(index.add(SSAInt(1), true, true)); + stack_xfrac.store(xfrac + xstep); + stack_yfrac.store(yfrac + ystep); + loop.end_block(); + } +} + +SSAVec4i DrawSpanCodegen::Sample(SSAInt xfrac, SSAInt yfrac, bool isNearestFilter, bool is64x64) +{ + if (isNearestFilter) + { + SSAInt spot; + if (is64x64) + spot = ((xfrac >> (32 - 6 - 6))&(63 * 64)) + (yfrac >> (32 - 6)); + else + spot = ((xfrac >> xshift) & xmask) + (yfrac >> yshift); + return source[spot * 4].load_vec4ub(true); + } + else + { + if (is64x64) + { + return SampleLinear(source, xfrac, yfrac, SSAInt(26), SSAInt(26)); + } + else + { + return SampleLinear(source, xfrac, yfrac, 32 - xbits, 32 - ybits); + } + } +} + +SSAVec4i DrawSpanCodegen::SampleLinear(SSAUBytePtr texture, SSAInt xfrac, SSAInt yfrac, SSAInt xbits, SSAInt ybits) +{ + SSAInt xshift = (32 - xbits); + SSAInt yshift = (32 - ybits); + SSAInt xmask = (SSAInt(1) << xshift) - 1; + SSAInt ymask = (SSAInt(1) << yshift) - 1; + SSAInt x = xfrac >> xbits; + SSAInt y = yfrac >> ybits; + + SSAVec4i p00 = texture[((y & ymask) + ((x & xmask) << yshift)) * 4].load_vec4ub(true); + SSAVec4i p01 = texture[(((y + 1) & ymask) + ((x & xmask) << yshift)) * 4].load_vec4ub(true); + SSAVec4i p10 = texture[((y & ymask) + (((x + 1) & xmask) << yshift)) * 4].load_vec4ub(true); + SSAVec4i p11 = texture[(((y + 1) & ymask) + (((x + 1) & xmask) << yshift)) * 4].load_vec4ub(true); + + SSAInt inv_b = (xfrac >> (xbits - 4)) & 15; + SSAInt inv_a = (yfrac >> (ybits - 4)) & 15; + SSAInt a = 16 - inv_a; + SSAInt b = 16 - inv_b; + + return (p00 * (a * b) + p01 * (inv_a * b) + p10 * (a * inv_b) + p11 * (inv_a * inv_b) + 127) >> 8; +} + +SSAVec4i DrawSpanCodegen::Shade(SSAVec4i fg, bool isSimpleShade) +{ + SSAVec4i c; + if (isSimpleShade) + c = shade_bgra_simple(fg, light); + else + c = shade_bgra_advanced(fg, light, shade_constants); + + stack_lit_color.store(c); + stack_light_index.store(SSAInt(0)); + + SSAForBlock block; + SSAInt light_index = stack_light_index.load(); + SSAVec4i lit_color = stack_lit_color.load(); + block.loop_block(light_index < num_dynlights); + { + SSAVec4i light_color = SSAUBytePtr(SSAValue(dynlights[light_index][0]).v).load_vec4ub(true); + SSAFloat light_x = dynlights[light_index][1].load(true); + SSAFloat light_y = dynlights[light_index][2].load(true); + //SSAFloat light_z = dynlights[light_index][3].load(true); + SSAFloat light_rcp_radius = dynlights[light_index][4].load(true); + + // L = light-pos + // dist = sqrt(dot(L, L)) + // attenuation = 1 - MIN(dist * (1/radius), 1) + SSAFloat Lyz2 = light_y; // L.y*L.y + L.z*L.z + SSAFloat Lx = light_x - viewpos_x; + SSAFloat dist = SSAFloat::fastsqrt(Lyz2 + Lx * Lx); + SSAInt attenuation = SSAInt(SSAFloat(256.0f) - SSAFloat::MIN(dist * light_rcp_radius, SSAFloat(256.0f)), true); + SSAVec4i contribution = (light_color * fg * attenuation) >> 16; + + stack_lit_color.store(lit_color + contribution); + stack_light_index.store(light_index + 1); + } + block.end_block(); + + return stack_lit_color.load(); +} + +SSAVec4i DrawSpanCodegen::Blend(SSAVec4i fg, SSAVec4i bg, DrawSpanVariant variant) +{ + switch (variant) + { + default: + case DrawSpanVariant::Opaque: + return blend_copy(fg); + case DrawSpanVariant::Masked: + return blend_alpha_blend(fg, bg); + case DrawSpanVariant::Translucent: + case DrawSpanVariant::AddClamp: + return blend_add(fg, bg, srcalpha, destalpha); + case DrawSpanVariant::MaskedTranslucent: + case DrawSpanVariant::MaskedAddClamp: + return blend_add(fg, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + } +} diff --git a/tools/drawergen/fixedfunction/drawspancodegen.h b/tools/drawergen/fixedfunction/drawspancodegen.h new file mode 100644 index 000000000..9e0c67c41 --- /dev/null +++ b/tools/drawergen/fixedfunction/drawspancodegen.h @@ -0,0 +1,83 @@ +/* +** DrawSpan code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +enum class DrawSpanVariant +{ + Opaque, + Masked, + Translucent, + MaskedTranslucent, + AddClamp, + MaskedAddClamp +}; + +class DrawSpanCodegen : public DrawerCodegen +{ +public: + void Generate(DrawSpanVariant variant, SSAValue args); + +private: + void LoopShade(DrawSpanVariant variant, bool isSimpleShade); + void LoopFilter(DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter); + SSAInt Loop4x(DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter, bool is64x64); + void Loop(SSAInt start, DrawSpanVariant variant, bool isSimpleShade, bool isNearestFilter, bool is64x64); + SSAVec4i Sample(SSAInt xfrac, SSAInt yfrac, bool isNearestFilter, bool is64x64); + SSAVec4i SampleLinear(SSAUBytePtr texture, SSAInt xfrac, SSAInt yfrac, SSAInt xbits, SSAInt ybits); + SSAVec4i Shade(SSAVec4i fg, bool isSimpleShade); + SSAVec4i Blend(SSAVec4i fg, SSAVec4i bg, DrawSpanVariant variant); + + SSAStack stack_index, stack_xfrac, stack_yfrac, stack_light_index; + SSAStack stack_lit_color; + SSAStack stack_viewpos_x; + + SSAUBytePtr destorg; + SSAUBytePtr source; + SSAInt destpitch; + SSAInt xstep; + SSAInt ystep; + SSAInt x1; + SSAInt x2; + SSAInt y; + SSAInt xbits; + SSAInt ybits; + SSAInt light; + SSAInt srcalpha; + SSAInt destalpha; + SSAInt count; + SSAUBytePtr data; + SSAInt yshift; + SSAInt xshift; + SSAInt xmask; + SSABool is_64x64; + SSABool is_simple_shade; + SSABool is_nearest_filter; + SSAShadeConstants shade_constants; + + SSAFloat start_viewpos_x, step_viewpos_x; + SSAValue dynlights; // TriLight* + SSAInt num_dynlights; + SSAFloat viewpos_x; +}; diff --git a/tools/drawergen/fixedfunction/drawtrianglecodegen.cpp b/tools/drawergen/fixedfunction/drawtrianglecodegen.cpp new file mode 100644 index 000000000..c5f7405f5 --- /dev/null +++ b/tools/drawergen/fixedfunction/drawtrianglecodegen.cpp @@ -0,0 +1,696 @@ +/* +** DrawTriangle code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/drawtrianglecodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +void DrawTriangleCodegen::Generate(TriBlendMode blendmode, bool truecolor, bool colorfill, SSAValue args, SSAValue thread_data) +{ + this->blendmode = blendmode; + this->truecolor = truecolor; + this->colorfill = colorfill; + pixelsize = truecolor ? 4 : 1; + + LoadArgs(args, thread_data); + CalculateGradients(); + + if (truecolor) + { + SSAIfBlock branch; + branch.if_block(is_simple_shade); + { + DrawFullSpans(true); + DrawPartialBlocks(true); + } + branch.else_block(); + { + DrawFullSpans(false); + DrawPartialBlocks(false); + } + branch.end_block(); + } + else + { + DrawFullSpans(true); + DrawPartialBlocks(true); + } +} + +void DrawTriangleCodegen::DrawFullSpans(bool isSimpleShade) +{ + stack_i.store(SSAInt(0)); + SSAForBlock loop; + SSAInt i = stack_i.load(); + loop.loop_block(i < numSpans, 0); + { + SSAInt spanX = SSAShort(fullSpans[i][0].load(true).v).zext_int(); + SSAInt spanY = SSAShort(fullSpans[i][1].load(true).v).zext_int(); + SSAInt spanLength = fullSpans[i][2].load(true); + + SSAInt width = spanLength; + SSAInt height = SSAInt(8); + + stack_dest.store(destOrg[(spanX + spanY * pitch) * pixelsize]); + stack_posYW.store(start.W + gradientX.W * (spanX - startX) + gradientY.W * (spanY - startY)); + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_posYVarying[j].store(start.Varying[j] + gradientX.Varying[j] * (spanX - startX) + gradientY.Varying[j] * (spanY - startY)); + stack_y.store(SSAInt(0)); + + SSAForBlock loop_y; + SSAInt y = stack_y.load(); + SSAUBytePtr dest = stack_dest.load(); + SSAStepVariables blockPosY; + blockPosY.W = stack_posYW.load(); + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] = stack_posYVarying[j].load(); + loop_y.loop_block(y < height, 0); + { + stack_posXW.store(blockPosY.W); + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_posXVarying[j].store(blockPosY.Varying[j]); + + SSAFloat rcpW = SSAFloat((float)0x01000000) / blockPosY.W; + stack_lightpos.store(FRACUNIT - SSAInt(SSAFloat::clamp(shade - SSAFloat::MIN(SSAFloat(24.0f / 32.0f), globVis * blockPosY.W), SSAFloat(0.0f), SSAFloat(31.0f / 32.0f)) * (float)FRACUNIT, true)); + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_varyingPos[j].store(SSAInt(blockPosY.Varying[j] * rcpW, false)); + stack_x.store(SSAInt(0)); + + SSAForBlock loop_x; + SSAInt x = stack_x.load(); + SSAStepVariables blockPosX; + blockPosX.W = stack_posXW.load(); + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] = stack_posXVarying[j].load(); + SSAInt lightpos = stack_lightpos.load(); + SSAInt varyingPos[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = stack_varyingPos[j].load(); + loop_x.loop_block(x < width, 0); + { + blockPosX.W = blockPosX.W + gradientX.W * 8.0f; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] = blockPosX.Varying[j] + gradientX.Varying[j] * 8.0f; + + rcpW = SSAFloat((float)0x01000000) / blockPosX.W; + SSAInt varyingStep[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + { + SSAInt nextPos = SSAInt(blockPosX.Varying[j] * rcpW, false); + varyingStep[j] = (nextPos - varyingPos[j]) / 8; + } + + SSAInt lightnext = FRACUNIT - SSAInt(SSAFloat::clamp(shade - SSAFloat::MIN(SSAFloat(24.0f / 32.0f), globVis * blockPosX.W), SSAFloat(0.0f), SSAFloat(31.0f / 32.0f)) * (float)FRACUNIT, true); + SSAInt lightstep = (lightnext - lightpos) / 8; + + if (truecolor) + { + for (int ix = 0; ix < 8; ix += 4) + { + SSAUBytePtr destptr = dest[(x * 8 + ix) * 4]; + SSAVec16ub pixels16 = destptr.load_unaligned_vec16ub(false); + SSAVec8s pixels8hi = SSAVec8s::extendhi(pixels16); + SSAVec8s pixels8lo = SSAVec8s::extendlo(pixels16); + SSAVec4i pixels[4] = + { + SSAVec4i::extendlo(pixels8lo), + SSAVec4i::extendhi(pixels8lo), + SSAVec4i::extendlo(pixels8hi), + SSAVec4i::extendhi(pixels8hi) + }; + + for (int sse = 0; sse < 4; sse++) + { + currentlight = is_fixed_light.select(light, lightpos >> 8); + pixels[sse] = ProcessPixel32(pixels[sse], varyingPos, isSimpleShade); + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = varyingPos[j] + varyingStep[j]; + lightpos = lightpos + lightstep; + } + + destptr.store_unaligned_vec16ub(SSAVec16ub(SSAVec8s(pixels[0], pixels[1]), SSAVec8s(pixels[2], pixels[3]))); + } + } + else + { + for (int ix = 0; ix < 8; ix++) + { + currentlight = is_fixed_light.select(light, lightpos >> 8); + SSAInt colormapindex = SSAInt::MIN((256 - currentlight) * 32 / 256, SSAInt(31)); + currentcolormap = Colormaps[colormapindex << 8]; + + SSAUBytePtr destptr = dest[(x * 8 + ix)]; + destptr.store(ProcessPixel8(destptr.load(false).zext_int(), varyingPos).trunc_ubyte()); + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = varyingPos[j] + varyingStep[j]; + lightpos = lightpos + lightstep; + } + } + + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_varyingPos[j].store(varyingPos[j]); + stack_lightpos.store(lightpos); + stack_posXW.store(blockPosX.W); + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_posXVarying[j].store(blockPosX.Varying[j]); + stack_x.store(x + 1); + } + loop_x.end_block(); + + stack_posYW.store(blockPosY.W + gradientY.W); + for (int j = 0; j < TriVertex::NumVarying; j++) + stack_posYVarying[j].store(blockPosY.Varying[j] + gradientY.Varying[j]); + stack_dest.store(dest[pitch * pixelsize]); + stack_y.store(y + 1); + } + loop_y.end_block(); + + stack_i.store(i + 1); + } + loop.end_block(); +} + +void DrawTriangleCodegen::DrawPartialBlocks(bool isSimpleShade) +{ + stack_i.store(SSAInt(0)); + SSAForBlock loop; + SSAInt i = stack_i.load(); + loop.loop_block(i < numBlocks, 0); + { + SSAInt blockX = SSAShort(partialBlocks[i][0].load(true).v).zext_int(); + SSAInt blockY = SSAShort(partialBlocks[i][1].load(true).v).zext_int(); + SSAInt mask0 = partialBlocks[i][2].load(true); + SSAInt mask1 = partialBlocks[i][3].load(true); + + SSAUBytePtr dest = destOrg[(blockX + blockY * pitch) * pixelsize]; + + SSAStepVariables blockPosY; + blockPosY.W = start.W + gradientX.W * (blockX - startX) + gradientY.W * (blockY - startY); + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] = start.Varying[j] + gradientX.Varying[j] * (blockX - startX) + gradientY.Varying[j] * (blockY - startY); + + for (int maskNum = 0; maskNum < 2; maskNum++) + { + SSAInt mask = (maskNum == 0) ? mask0 : mask1; + + for (int y = 0; y < 4; y++) + { + SSAStepVariables blockPosX = blockPosY; + + SSAFloat rcpW = SSAFloat((float)0x01000000) / blockPosX.W; + SSAInt varyingPos[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = SSAInt(blockPosX.Varying[j] * rcpW, false); + + SSAInt lightpos = FRACUNIT - SSAInt(SSAFloat::clamp(shade - SSAFloat::MIN(SSAFloat(24.0f / 32.0f), globVis * blockPosX.W), SSAFloat(0.0f), SSAFloat(31.0f / 32.0f)) * (float)FRACUNIT, true); + + blockPosX.W = blockPosX.W + gradientX.W * 8.0f; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosX.Varying[j] = blockPosX.Varying[j] + gradientX.Varying[j] * 8.0f; + + rcpW = SSAFloat((float)0x01000000) / blockPosX.W; + SSAInt varyingStep[TriVertex::NumVarying]; + for (int j = 0; j < TriVertex::NumVarying; j++) + { + SSAInt nextPos = SSAInt(blockPosX.Varying[j] * rcpW, false); + varyingStep[j] = (nextPos - varyingPos[j]) / 8; + } + + SSAInt lightnext = FRACUNIT - SSAInt(SSAFloat::clamp(shade - SSAFloat::MIN(SSAFloat(24.0f / 32.0f), globVis * blockPosX.W), SSAFloat(0.0f), SSAFloat(31.0f / 32.0f)) * (float)FRACUNIT, true); + SSAInt lightstep = (lightnext - lightpos) / 8; + + for (int x = 0; x < 8; x++) + { + SSABool covered = !((mask & (1 << (31 - y * 8 - x))) == SSAInt(0)); + SSAIfBlock branch; + branch.if_block(covered); + { + if (truecolor) + { + currentlight = is_fixed_light.select(light, lightpos >> 8); + + SSAUBytePtr destptr = dest[x * 4]; + destptr.store_vec4ub(ProcessPixel32(destptr.load_vec4ub(false), varyingPos, isSimpleShade)); + } + else + { + currentlight = is_fixed_light.select(light, lightpos >> 8); + SSAInt colormapindex = SSAInt::MIN((256 - currentlight) * 32 / 256, SSAInt(31)); + currentcolormap = Colormaps[colormapindex << 8]; + + SSAUBytePtr destptr = dest[x]; + destptr.store(ProcessPixel8(destptr.load(false).zext_int(), varyingPos).trunc_ubyte()); + } + } + branch.end_block(); + + for (int j = 0; j < TriVertex::NumVarying; j++) + varyingPos[j] = varyingPos[j] + varyingStep[j]; + lightpos = lightpos + lightstep; + } + + blockPosY.W = blockPosY.W + gradientY.W; + for (int j = 0; j < TriVertex::NumVarying; j++) + blockPosY.Varying[j] = blockPosY.Varying[j] + gradientY.Varying[j]; + + dest = dest[pitch * pixelsize]; + } + } + + stack_i.store(i + 1); + } + loop.end_block(); +} + +SSAVec4i DrawTriangleCodegen::TranslateSample32(SSAInt *varying) +{ + SSAInt ufrac = varying[0] << 8; + SSAInt vfrac = varying[1] << 8; + + SSAInt upos = ((ufrac >> 16) * textureWidth) >> 16; + SSAInt vpos = ((vfrac >> 16) * textureHeight) >> 16; + SSAInt uvoffset = upos * textureHeight + vpos; + + if (colorfill) + return translation[color * 4].load_vec4ub(true); + else + return translation[texturePixels[uvoffset].load(true).zext_int() * 4].load_vec4ub(true); +} + +SSAInt DrawTriangleCodegen::TranslateSample8(SSAInt *varying) +{ + SSAInt ufrac = varying[0] << 8; + SSAInt vfrac = varying[1] << 8; + + SSAInt upos = ((ufrac >> 16) * textureWidth) >> 16; + SSAInt vpos = ((vfrac >> 16) * textureHeight) >> 16; + SSAInt uvoffset = upos * textureHeight + vpos; + + if (colorfill) + return translation[color].load(true).zext_int(); + else + return translation[texturePixels[uvoffset].load(true).zext_int()].load(true).zext_int(); +} + +SSAVec4i DrawTriangleCodegen::Sample32(SSAInt *varying) +{ + if (colorfill) + return SSAVec4i::unpack(color); + + SSAInt ufrac = varying[0] << 8; + SSAInt vfrac = varying[1] << 8; + + SSAVec4i nearest; + SSAVec4i linear; + + { + SSAInt upos = ((ufrac >> 16) * textureWidth) >> 16; + SSAInt vpos = ((vfrac >> 16) * textureHeight) >> 16; + SSAInt uvoffset = upos * textureHeight + vpos; + + nearest = texturePixels[uvoffset * 4].load_vec4ub(true); + } + + return nearest; + + /* + { + SSAInt uone = (SSAInt(0x01000000) / textureWidth) << 8; + SSAInt vone = (SSAInt(0x01000000) / textureHeight) << 8; + + ufrac = ufrac - (uone >> 1); + vfrac = vfrac - (vone >> 1); + + SSAInt frac_x0 = (ufrac >> FRACBITS) * textureWidth; + SSAInt frac_x1 = ((ufrac + uone) >> FRACBITS) * textureWidth; + SSAInt frac_y0 = (vfrac >> FRACBITS) * textureHeight; + SSAInt frac_y1 = ((vfrac + vone) >> FRACBITS) * textureHeight; + + SSAInt x0 = frac_x0 >> FRACBITS; + SSAInt x1 = frac_x1 >> FRACBITS; + SSAInt y0 = frac_y0 >> FRACBITS; + SSAInt y1 = frac_y1 >> FRACBITS; + + SSAVec4i p00 = texturePixels[(x0 * textureHeight + y0) * 4].load_vec4ub(true); + SSAVec4i p01 = texturePixels[(x0 * textureHeight + y1) * 4].load_vec4ub(true); + SSAVec4i p10 = texturePixels[(x1 * textureHeight + y0) * 4].load_vec4ub(true); + SSAVec4i p11 = texturePixels[(x1 * textureHeight + y1) * 4].load_vec4ub(true); + + SSAInt inv_b = (frac_x1 >> (FRACBITS - 4)) & 15; + SSAInt inv_a = (frac_y1 >> (FRACBITS - 4)) & 15; + SSAInt a = 16 - inv_a; + SSAInt b = 16 - inv_b; + + linear = (p00 * (a * b) + p01 * (inv_a * b) + p10 * (a * inv_b) + p11 * (inv_a * inv_b) + 127) >> 8; + } + + // // Min filter = linear, Mag filter = nearest: + // AffineLinear = (gradVaryingX[0] / AffineW) > SSAFloat(1.0f) || (gradVaryingX[0] / AffineW) < SSAFloat(-1.0f); + + return AffineLinear.select(linear, nearest); + */ +} + +SSAInt DrawTriangleCodegen::Sample8(SSAInt *varying) +{ + SSAInt ufrac = varying[0] << 8; + SSAInt vfrac = varying[1] << 8; + + SSAInt upos = ((ufrac >> 16) * textureWidth) >> 16; + SSAInt vpos = ((vfrac >> 16) * textureHeight) >> 16; + SSAInt uvoffset = upos * textureHeight + vpos; + + if (colorfill) + return color; + else + return texturePixels[uvoffset].load(true).zext_int(); +} + +SSAInt DrawTriangleCodegen::Shade8(SSAInt c) +{ + return currentcolormap[c].load(true).zext_int(); +} + +SSAVec4i DrawTriangleCodegen::Shade32(SSAVec4i fg, SSAInt light, bool isSimpleShade) +{ + if (isSimpleShade) + return shade_bgra_simple(fg, currentlight); + else + return shade_bgra_advanced(fg, currentlight, shade_constants); +} + +SSAVec4i DrawTriangleCodegen::ProcessPixel32(SSAVec4i bg, SSAInt *varying, bool isSimpleShade) +{ + SSAVec4i fg; + SSAVec4i output; + + switch (blendmode) + { + default: + case TriBlendMode::Copy: + fg = Sample32(varying); + output = blend_copy(Shade32(fg, currentlight, isSimpleShade)); + break; + case TriBlendMode::AlphaBlend: + fg = Sample32(varying); + output = blend_alpha_blend(Shade32(fg, currentlight, isSimpleShade), bg); + break; + case TriBlendMode::AddSolid: + fg = Sample32(varying); + output = blend_add(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, destalpha); + break; + case TriBlendMode::Add: + fg = Sample32(varying); + output = blend_add(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::Sub: + fg = Sample32(varying); + output = blend_sub(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::RevSub: + fg = Sample32(varying); + output = blend_revsub(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::Stencil: + fg = Sample32(varying); + output = blend_stencil(Shade32(SSAVec4i::unpack(color), currentlight, isSimpleShade), fg[3], bg, srcalpha, destalpha); + break; + case TriBlendMode::Shaded: + output = blend_stencil(Shade32(SSAVec4i::unpack(color), currentlight, isSimpleShade), Sample8(varying), bg, srcalpha, destalpha); + break; + case TriBlendMode::TranslateCopy: + fg = TranslateSample32(varying); + output = blend_copy(Shade32(fg, currentlight, isSimpleShade)); + break; + case TriBlendMode::TranslateAlphaBlend: + fg = TranslateSample32(varying); + output = blend_alpha_blend(Shade32(fg, currentlight, isSimpleShade), bg); + break; + case TriBlendMode::TranslateAdd: + fg = TranslateSample32(varying); + output = blend_add(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::TranslateSub: + fg = TranslateSample32(varying); + output = blend_sub(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::TranslateRevSub: + fg = TranslateSample32(varying); + output = blend_revsub(Shade32(fg, currentlight, isSimpleShade), bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + break; + case TriBlendMode::AddSrcColorOneMinusSrcColor: + fg = Sample32(varying); + output = blend_add_srccolor_oneminussrccolor(Shade32(fg, currentlight, isSimpleShade), bg); + break; + case TriBlendMode::Skycap: + fg = Sample32(varying); + output = FadeOut(varying[1], fg); + break; + } + + return output; +} + +SSAVec4i DrawTriangleCodegen::ToBgra(SSAInt index) +{ + SSAVec4i c = BaseColors[index * 4].load_vec4ub(true); + c = c.insert(3, 255); + return c; +} + +SSAInt DrawTriangleCodegen::ToPal8(SSAVec4i c) +{ + SSAInt red = SSAInt::clamp(c[0], SSAInt(0), SSAInt(255)); + SSAInt green = SSAInt::clamp(c[1], SSAInt(0), SSAInt(255)); + SSAInt blue = SSAInt::clamp(c[2], SSAInt(0), SSAInt(255)); + return RGB256k[((blue >> 2) * 64 + (green >> 2)) * 64 + (red >> 2)].load(true).zext_int(); +} + +SSAInt DrawTriangleCodegen::ProcessPixel8(SSAInt bg, SSAInt *varying) +{ + SSAVec4i fg; + SSAInt alpha, inv_alpha; + SSAInt output; + SSAInt palindex; + + switch (blendmode) + { + default: + case TriBlendMode::Copy: + output = Shade8(Sample8(varying)); + break; + case TriBlendMode::AlphaBlend: + palindex = Sample8(varying); + output = Shade8(palindex); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::AddSolid: + palindex = Sample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_add(fg, ToBgra(bg), srcalpha, destalpha)); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::Add: + palindex = Sample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_add(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::Sub: + palindex = Sample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_sub(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::RevSub: + palindex = Sample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_revsub(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::Stencil: + output = ToPal8(blend_stencil(ToBgra(Shade8(color)), (Sample8(varying) == SSAInt(0)).select(SSAInt(0), SSAInt(256)), ToBgra(bg), srcalpha, destalpha)); + break; + case TriBlendMode::Shaded: + palindex = Sample8(varying); + output = ToPal8(blend_stencil(ToBgra(Shade8(color)), palindex, ToBgra(bg), srcalpha, destalpha)); + break; + case TriBlendMode::TranslateCopy: + palindex = TranslateSample8(varying); + output = Shade8(palindex); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::TranslateAlphaBlend: + palindex = TranslateSample8(varying); + output = Shade8(palindex); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::TranslateAdd: + palindex = TranslateSample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_add(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::TranslateSub: + palindex = TranslateSample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_sub(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::TranslateRevSub: + palindex = TranslateSample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_revsub(fg, ToBgra(bg), srcalpha, calc_blend_bgalpha(fg, destalpha))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::AddSrcColorOneMinusSrcColor: + palindex = Sample8(varying); + fg = ToBgra(Shade8(palindex)); + output = ToPal8(blend_add_srccolor_oneminussrccolor(fg, ToBgra(bg))); + output = (palindex == SSAInt(0)).select(bg, output); + break; + case TriBlendMode::Skycap: + fg = ToBgra(Sample8(varying)); + output = ToPal8(FadeOut(varying[1], fg)); + break; + } + + return output; +} + +SSAVec4i DrawTriangleCodegen::FadeOut(SSAInt frac, SSAVec4i fg) +{ + int start_fade = 2; // How fast it should fade out + + SSAInt alpha_top = SSAInt::MAX(SSAInt::MIN(frac.ashr(16 - start_fade), SSAInt(256)), SSAInt(0)); + SSAInt alpha_bottom = SSAInt::MAX(SSAInt::MIN(((2 << 24) - frac).ashr(16 - start_fade), SSAInt(256)), SSAInt(0)); + SSAInt alpha = SSAInt::MIN(alpha_top, alpha_bottom); + SSAInt inv_alpha = 256 - alpha; + + fg = (fg * alpha + SSAVec4i::unpack(color) * inv_alpha) / 256; + return fg.insert(3, 255); +} + +void DrawTriangleCodegen::CalculateGradients() +{ + gradientX.W = FindGradientX(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.w, v2.w, v3.w); + gradientY.W = FindGradientY(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.w, v2.w, v3.w); + start.W = v1.w + gradientX.W * (SSAFloat(startX) - v1.x) + gradientY.W * (SSAFloat(startY) - v1.y); + for (int i = 0; i < TriVertex::NumVarying; i++) + { + gradientX.Varying[i] = FindGradientX(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.varying[i] * v1.w, v2.varying[i] * v2.w, v3.varying[i] * v3.w); + gradientY.Varying[i] = FindGradientY(v1.x, v1.y, v2.x, v2.y, v3.x, v3.y, v1.varying[i] * v1.w, v2.varying[i] * v2.w, v3.varying[i] * v3.w); + start.Varying[i] = v1.varying[i] * v1.w + gradientX.Varying[i] * (SSAFloat(startX) - v1.x) + gradientY.Varying[i] * (SSAFloat(startY) - v1.y); + } + + shade = (64.0f - (SSAFloat(light * 255 / 256) + 12.0f) * 32.0f / 128.0f) / 32.0f; + globVis = SSAFloat(1706.0f / 32.0f); +} + +void DrawTriangleCodegen::LoadArgs(SSAValue args, SSAValue thread_data) +{ + destOrg = args[0][0].load(true); + pitch = args[0][1].load(true); + v1 = LoadTriVertex(args[0][2].load(true)); + v2 = LoadTriVertex(args[0][3].load(true)); + v3 = LoadTriVertex(args[0][4].load(true)); + texturePixels = args[0][9].load(true); + textureWidth = args[0][10].load(true); + textureHeight = args[0][11].load(true); + translation = args[0][12].load(true); + LoadUniforms(args[0][13].load(true)); + if (!truecolor) + { + Colormaps = args[0][20].load(true); + RGB256k = args[0][21].load(true); + BaseColors = args[0][22].load(true); + } + + fullSpans = thread_data[0][5].load(true); + partialBlocks = thread_data[0][6].load(true); + numSpans = thread_data[0][7].load(true); + numBlocks = thread_data[0][8].load(true); + startX = thread_data[0][9].load(true); + startY = thread_data[0][10].load(true); +} + +SSATriVertex DrawTriangleCodegen::LoadTriVertex(SSAValue ptr) +{ + SSATriVertex v; + v.x = ptr[0][0].load(true); + v.y = ptr[0][1].load(true); + v.z = ptr[0][2].load(true); + v.w = ptr[0][3].load(true); + for (int i = 0; i < TriVertex::NumVarying; i++) + v.varying[i] = ptr[0][4 + i].load(true); + return v; +} + +void DrawTriangleCodegen::LoadUniforms(SSAValue uniforms) +{ + light = uniforms[0][0].load(true); + color = uniforms[0][2].load(true); + srcalpha = uniforms[0][3].load(true); + destalpha = uniforms[0][4].load(true); + + SSAShort light_alpha = uniforms[0][5].load(true); + SSAShort light_red = uniforms[0][6].load(true); + SSAShort light_green = uniforms[0][7].load(true); + SSAShort light_blue = uniforms[0][8].load(true); + SSAShort fade_alpha = uniforms[0][9].load(true); + SSAShort fade_red = uniforms[0][10].load(true); + SSAShort fade_green = uniforms[0][11].load(true); + SSAShort fade_blue = uniforms[0][12].load(true); + SSAShort desaturate = uniforms[0][13].load(true); + SSAInt flags = uniforms[0][14].load(true); + shade_constants.light = SSAVec4i(light_blue.zext_int(), light_green.zext_int(), light_red.zext_int(), light_alpha.zext_int()); + shade_constants.fade = SSAVec4i(fade_blue.zext_int(), fade_green.zext_int(), fade_red.zext_int(), fade_alpha.zext_int()); + shade_constants.desaturate = desaturate.zext_int(); + + is_simple_shade = (flags & TriUniforms::simple_shade) == SSAInt(TriUniforms::simple_shade); + is_nearest_filter = (flags & TriUniforms::nearest_filter) == SSAInt(TriUniforms::nearest_filter); + is_fixed_light = (flags & TriUniforms::fixed_light) == SSAInt(TriUniforms::fixed_light); +} + +SSAFloat DrawTriangleCodegen::FindGradientX(SSAFloat x0, SSAFloat y0, SSAFloat x1, SSAFloat y1, SSAFloat x2, SSAFloat y2, SSAFloat c0, SSAFloat c1, SSAFloat c2) +{ + SSAFloat top = (c1 - c2) * (y0 - y2) - (c0 - c2) * (y1 - y2); + SSAFloat bottom = (x1 - x2) * (y0 - y2) - (x0 - x2) * (y1 - y2); + return top / bottom; +} + +SSAFloat DrawTriangleCodegen::FindGradientY(SSAFloat x0, SSAFloat y0, SSAFloat x1, SSAFloat y1, SSAFloat x2, SSAFloat y2, SSAFloat c0, SSAFloat c1, SSAFloat c2) +{ + SSAFloat top = (c1 - c2) * (x0 - x2) - (c0 - c2) * (x1 - x2); + SSAFloat bottom = (x0 - x2) * (y1 - y2) - (x1 - x2) * (y0 - y2); + return top / bottom; +} diff --git a/tools/drawergen/fixedfunction/drawtrianglecodegen.h b/tools/drawergen/fixedfunction/drawtrianglecodegen.h new file mode 100644 index 000000000..71d6ebd58 --- /dev/null +++ b/tools/drawergen/fixedfunction/drawtrianglecodegen.h @@ -0,0 +1,112 @@ +/* +** DrawTriangle code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +struct SSATriVertex +{ + SSAFloat x, y, z, w; + SSAFloat varying[TriVertex::NumVarying]; +}; + +struct SSAStepVariables +{ + SSAFloat W; + SSAFloat Varying[TriVertex::NumVarying]; +}; + +class DrawTriangleCodegen : public DrawerCodegen +{ +public: + void Generate(TriBlendMode blendmode, bool truecolor, bool colorfill, SSAValue args, SSAValue thread_data); + +private: + void LoadArgs(SSAValue args, SSAValue thread_data); + SSATriVertex LoadTriVertex(SSAValue v); + void LoadUniforms(SSAValue uniforms); + void CalculateGradients(); + SSAFloat FindGradientX(SSAFloat x0, SSAFloat y0, SSAFloat x1, SSAFloat y1, SSAFloat x2, SSAFloat y2, SSAFloat c0, SSAFloat c1, SSAFloat c2); + SSAFloat FindGradientY(SSAFloat x0, SSAFloat y0, SSAFloat x1, SSAFloat y1, SSAFloat x2, SSAFloat y2, SSAFloat c0, SSAFloat c1, SSAFloat c2); + void DrawFullSpans(bool isSimpleShade); + void DrawPartialBlocks(bool isSimpleShade); + + SSAVec4i ProcessPixel32(SSAVec4i bg, SSAInt *varying, bool isSimpleShade); + SSAInt ProcessPixel8(SSAInt bg, SSAInt *varying); + SSAVec4i TranslateSample32(SSAInt *varying); + SSAInt TranslateSample8(SSAInt *varying); + SSAVec4i Sample32(SSAInt *varying); + SSAInt Sample8(SSAInt *varying); + SSAVec4i Shade32(SSAVec4i fg, SSAInt light, bool isSimpleShade); + SSAInt Shade8(SSAInt c); + SSAVec4i ToBgra(SSAInt index); + SSAInt ToPal8(SSAVec4i c); + SSAVec4i FadeOut(SSAInt frac, SSAVec4i color); + + SSAStack stack_i, stack_y, stack_x; + SSAStack stack_posYW, stack_posXW; + SSAStack stack_posYVarying[TriVertex::NumVarying]; + SSAStack stack_posXVarying[TriVertex::NumVarying]; + SSAStack stack_varyingPos[TriVertex::NumVarying]; + SSAStack stack_lightpos; + SSAStack stack_dest; + + SSAStepVariables gradientX, gradientY, start; + SSAFloat shade, globVis; + + SSAInt currentlight; + SSAUBytePtr currentcolormap; + + SSAUBytePtr destOrg; + SSAInt pitch; + SSATriVertex v1; + SSATriVertex v2; + SSATriVertex v3; + SSAUBytePtr texturePixels; + SSAInt textureWidth; + SSAInt textureHeight; + SSAUBytePtr translation; + SSAInt color, srcalpha, destalpha; + + SSAInt light; + SSAShadeConstants shade_constants; + SSABool is_simple_shade; + SSABool is_nearest_filter; + SSABool is_fixed_light; + + SSAUBytePtr Colormaps; + SSAUBytePtr RGB256k; + SSAUBytePtr BaseColors; + + SSAInt numSpans; + SSAInt numBlocks; + SSAInt startX; + SSAInt startY; + SSAValue fullSpans; // TriFullSpan[] + SSAValue partialBlocks; // TriPartialBlock[] + + TriBlendMode blendmode; + bool truecolor; + bool colorfill; + int pixelsize; +}; diff --git a/tools/drawergen/fixedfunction/drawwallcodegen.cpp b/tools/drawergen/fixedfunction/drawwallcodegen.cpp new file mode 100644 index 000000000..898aebdbb --- /dev/null +++ b/tools/drawergen/fixedfunction/drawwallcodegen.cpp @@ -0,0 +1,276 @@ +/* +** DrawWall code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/drawwallcodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +void DrawWallCodegen::Generate(DrawWallVariant variant, bool fourColumns, SSAValue args, SSAValue thread_data) +{ + dest = args[0][0].load(true); + source[0] = args[0][1].load(true); + source[1] = args[0][2].load(true); + source[2] = args[0][3].load(true); + source[3] = args[0][4].load(true); + source2[0] = args[0][5].load(true); + source2[1] = args[0][6].load(true); + source2[2] = args[0][7].load(true); + source2[3] = args[0][8].load(true); + pitch = args[0][9].load(true); + count = args[0][10].load(true); + dest_y = args[0][11].load(true); + texturefrac[0] = args[0][12].load(true); + texturefrac[1] = args[0][13].load(true); + texturefrac[2] = args[0][14].load(true); + texturefrac[3] = args[0][15].load(true); + texturefracx[0] = args[0][16].load(true); + texturefracx[1] = args[0][17].load(true); + texturefracx[2] = args[0][18].load(true); + texturefracx[3] = args[0][19].load(true); + iscale[0] = args[0][20].load(true); + iscale[1] = args[0][21].load(true); + iscale[2] = args[0][22].load(true); + iscale[3] = args[0][23].load(true); + textureheight[0] = args[0][24].load(true); + textureheight[1] = args[0][25].load(true); + textureheight[2] = args[0][26].load(true); + textureheight[3] = args[0][27].load(true); + light[0] = args[0][28].load(true); + light[1] = args[0][29].load(true); + light[2] = args[0][30].load(true); + light[3] = args[0][31].load(true); + srcalpha = args[0][32].load(true); + destalpha = args[0][33].load(true); + SSAShort light_alpha = args[0][34].load(true); + SSAShort light_red = args[0][35].load(true); + SSAShort light_green = args[0][36].load(true); + SSAShort light_blue = args[0][37].load(true); + SSAShort fade_alpha = args[0][38].load(true); + SSAShort fade_red = args[0][39].load(true); + SSAShort fade_green = args[0][40].load(true); + SSAShort fade_blue = args[0][41].load(true); + SSAShort desaturate = args[0][42].load(true); + SSAInt flags = args[0][43].load(true); + start_z = args[0][44].load(true); + step_z = args[0][45].load(true); + dynlights = args[0][46].load(true); + num_dynlights = args[0][47].load(true); + shade_constants.light = SSAVec4i(light_blue.zext_int(), light_green.zext_int(), light_red.zext_int(), light_alpha.zext_int()); + shade_constants.fade = SSAVec4i(fade_blue.zext_int(), fade_green.zext_int(), fade_red.zext_int(), fade_alpha.zext_int()); + shade_constants.desaturate = desaturate.zext_int(); + + thread.core = thread_data[0][0].load(true); + thread.num_cores = thread_data[0][1].load(true); + thread.pass_start_y = thread_data[0][2].load(true); + thread.pass_end_y = thread_data[0][3].load(true); + + is_simple_shade = (flags & DrawWallArgs::simple_shade) == SSAInt(DrawWallArgs::simple_shade); + is_nearest_filter = (flags & DrawWallArgs::nearest_filter) == SSAInt(DrawWallArgs::nearest_filter); + + count = count_for_thread(dest_y, count, thread); + dest = dest_for_thread(dest_y, pitch, dest, thread); + + pitch = pitch * thread.num_cores; + + int numColumns = fourColumns ? 4 : 1; + for (int i = 0; i < numColumns; i++) + { + stack_frac[i].store(texturefrac[i] + iscale[i] * skipped_by_thread(dest_y, thread)); + fracstep[i] = iscale[i] * thread.num_cores; + one[i] = ((0x80000000 + textureheight[i] - 1) / textureheight[i]) * 2 + 1; + } + + start_z = start_z + step_z * SSAFloat(skipped_by_thread(dest_y, thread)); + step_z = step_z * SSAFloat(thread.num_cores); + + SSAIfBlock branch; + branch.if_block(is_simple_shade); + LoopShade(variant, fourColumns, true); + branch.else_block(); + LoopShade(variant, fourColumns, false); + branch.end_block(); +} + +void DrawWallCodegen::LoopShade(DrawWallVariant variant, bool fourColumns, bool isSimpleShade) +{ + SSAIfBlock branch; + branch.if_block(is_nearest_filter); + Loop(variant, fourColumns, isSimpleShade, true); + branch.else_block(); + int numColumns = fourColumns ? 4 : 1; + for (int i = 0; i < numColumns; i++) + stack_frac[i].store(stack_frac[i].load() - (one[i] / 2)); + Loop(variant, fourColumns, isSimpleShade, false); + branch.end_block(); +} + +void DrawWallCodegen::Loop(DrawWallVariant variant, bool fourColumns, bool isSimpleShade, bool isNearestFilter) +{ + int numColumns = fourColumns ? 4 : 1; + + stack_index.store(SSAInt(0)); + stack_z.store(start_z); + { + SSAForBlock loop; + SSAInt index = stack_index.load(); + z = stack_z.load(); + loop.loop_block(index < count); + + SSAInt frac[4]; + for (int i = 0; i < numColumns; i++) + frac[i] = stack_frac[i].load(); + + SSAInt offset = index * pitch * 4; + + if (fourColumns) + { + SSAVec16ub bg = dest[offset].load_unaligned_vec16ub(false); + SSAVec8s bg0 = SSAVec8s::extendlo(bg); + SSAVec8s bg1 = SSAVec8s::extendhi(bg); + SSAVec4i bgcolors[4] = + { + SSAVec4i::extendlo(bg0), + SSAVec4i::extendhi(bg0), + SSAVec4i::extendlo(bg1), + SSAVec4i::extendhi(bg1) + }; + + SSAVec4i colors[4]; + for (int i = 0; i < 4; i++) + colors[i] = Blend(Shade(Sample(frac[i], i, isNearestFilter), i, isSimpleShade), bgcolors[i], variant); + + SSAVec16ub color(SSAVec8s(colors[0], colors[1]), SSAVec8s(colors[2], colors[3])); + dest[offset].store_unaligned_vec16ub(color); + } + else + { + SSAVec4i bgcolor = dest[offset].load_vec4ub(false); + SSAVec4i color = Blend(Shade(Sample(frac[0], 0, isNearestFilter), 0, isSimpleShade), bgcolor, variant); + dest[offset].store_vec4ub(color); + } + + stack_z.store(z + step_z); + stack_index.store(index.add(SSAInt(1), true, true)); + for (int i = 0; i < numColumns; i++) + stack_frac[i].store(frac[i] + fracstep[i]); + loop.end_block(); + } +} + +SSAVec4i DrawWallCodegen::Sample(SSAInt frac, int index, bool isNearestFilter) +{ + if (isNearestFilter) + { + SSAInt sample_index = ((frac >> FRACBITS) * textureheight[index]) >> FRACBITS; + return source[index][sample_index * 4].load_vec4ub(false); + } + else + { + return SampleLinear(source[index], source2[index], texturefracx[index], frac, one[index], textureheight[index]); + } +} + +SSAVec4i DrawWallCodegen::SampleLinear(SSAUBytePtr col0, SSAUBytePtr col1, SSAInt texturefracx, SSAInt texturefracy, SSAInt one, SSAInt height) +{ + SSAInt frac_y0 = (texturefracy >> FRACBITS) * height; + SSAInt frac_y1 = ((texturefracy + one) >> FRACBITS) * height; + SSAInt y0 = frac_y0 >> FRACBITS; + SSAInt y1 = frac_y1 >> FRACBITS; + + SSAVec4i p00 = col0[y0 * 4].load_vec4ub(true); + SSAVec4i p01 = col0[y1 * 4].load_vec4ub(true); + SSAVec4i p10 = col1[y0 * 4].load_vec4ub(true); + SSAVec4i p11 = col1[y1 * 4].load_vec4ub(true); + + SSAInt inv_b = texturefracx; + SSAInt a = (frac_y1 >> (FRACBITS - 4)) & 15; + SSAInt inv_a = 16 - a; + SSAInt b = 16 - inv_b; + + return (p00 * (a * b) + p01 * (inv_a * b) + p10 * (a * inv_b) + p11 * (inv_a * inv_b) + 127) >> 8; +} + +SSAVec4i DrawWallCodegen::Shade(SSAVec4i fg, int index, bool isSimpleShade) +{ + SSAVec4i c; + if (isSimpleShade) + c = shade_bgra_simple(fg, light[index]); + else + c = shade_bgra_advanced(fg, light[index], shade_constants); + + stack_lit_color.store(c); + stack_light_index.store(SSAInt(0)); + + SSAForBlock block; + SSAInt light_index = stack_light_index.load(); + SSAVec4i lit_color = stack_lit_color.load(); + block.loop_block(light_index < num_dynlights); + { + SSAVec4i light_color = SSAUBytePtr(SSAValue(dynlights[light_index][0]).v).load_vec4ub(true); + SSAFloat light_x = dynlights[light_index][1].load(true); + //SSAFloat light_y = dynlights[light_index][2].load(true); + SSAFloat light_z = dynlights[light_index][3].load(true); + SSAFloat light_rcp_radius = dynlights[light_index][4].load(true); + + // L = light-pos + // dist = sqrt(dot(L, L)) + // attenuation = 1 - MIN(dist * (1/radius), 1) + SSAFloat Lxy2 = light_x; // L.x*L.x + L.y*L.y + SSAFloat Lz = light_z - z; + SSAFloat dist = SSAFloat::fastsqrt(Lxy2 + Lz * Lz); + SSAInt attenuation = SSAInt(SSAFloat(256.0f) - SSAFloat::MIN(dist * light_rcp_radius, SSAFloat(256.0f)), true); + SSAVec4i contribution = (light_color * fg * attenuation) >> 16; + + stack_lit_color.store(lit_color + contribution); + stack_light_index.store(light_index + 1); + } + block.end_block(); + + return stack_lit_color.load(); +} + +SSAVec4i DrawWallCodegen::Blend(SSAVec4i fg, SSAVec4i bg, DrawWallVariant variant) +{ + switch (variant) + { + default: + case DrawWallVariant::Opaque: + return blend_copy(fg); + case DrawWallVariant::Masked: + return blend_alpha_blend(fg, bg); + case DrawWallVariant::Add: + case DrawWallVariant::AddClamp: + return blend_add(fg, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawWallVariant::SubClamp: + return blend_sub(fg, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + case DrawWallVariant::RevSubClamp: + return blend_revsub(fg, bg, srcalpha, calc_blend_bgalpha(fg, destalpha)); + } +} diff --git a/tools/drawergen/fixedfunction/drawwallcodegen.h b/tools/drawergen/fixedfunction/drawwallcodegen.h new file mode 100644 index 000000000..cb46dcd5f --- /dev/null +++ b/tools/drawergen/fixedfunction/drawwallcodegen.h @@ -0,0 +1,80 @@ +/* +** DrawWall code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +enum class DrawWallVariant +{ + Opaque, + Masked, + Add, + AddClamp, + SubClamp, + RevSubClamp +}; + +class DrawWallCodegen : public DrawerCodegen +{ +public: + void Generate(DrawWallVariant variant, bool fourColumns, SSAValue args, SSAValue thread_data); + +private: + void LoopShade(DrawWallVariant variant, bool fourColumns, bool isSimpleShade); + void Loop(DrawWallVariant variant, bool fourColumns, bool isSimpleShade, bool isNearestFilter); + SSAVec4i Sample(SSAInt frac, int index, bool isNearestFilter); + SSAVec4i SampleLinear(SSAUBytePtr col0, SSAUBytePtr col1, SSAInt texturefracx, SSAInt texturefracy, SSAInt one, SSAInt height); + SSAVec4i Shade(SSAVec4i fg, int index, bool isSimpleShade); + SSAVec4i Blend(SSAVec4i fg, SSAVec4i bg, DrawWallVariant variant); + + SSAStack stack_index, stack_frac[4], stack_light_index; + SSAStack stack_lit_color; + SSAStack stack_z; + + SSAUBytePtr dest; + SSAUBytePtr source[4]; + SSAUBytePtr source2[4]; + SSAInt pitch; + SSAInt count; + SSAInt dest_y; + SSAInt texturefrac[4]; + SSAInt texturefracx[4]; + SSAInt iscale[4]; + SSAInt textureheight[4]; + SSAInt light[4]; + SSAInt srcalpha; + SSAInt destalpha; + SSABool is_simple_shade; + SSABool is_nearest_filter; + SSAShadeConstants shade_constants; + SSAWorkerThread thread; + + SSAInt fracstep[4]; + SSAInt one[4]; + + SSAFloat start_z, step_z; + + SSAValue dynlights; // TriLight* + SSAInt num_dynlights; + SSAFloat z; +}; diff --git a/tools/drawergen/fixedfunction/setuptrianglecodegen.cpp b/tools/drawergen/fixedfunction/setuptrianglecodegen.cpp new file mode 100644 index 000000000..f29764d9e --- /dev/null +++ b/tools/drawergen/fixedfunction/setuptrianglecodegen.cpp @@ -0,0 +1,573 @@ +/* +** DrawTriangle code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "fixedfunction/setuptrianglecodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" + +void SetupTriangleCodegen::Generate(bool subsectorTest, SSAValue args, SSAValue thread_data) +{ + this->subsectorTest = subsectorTest; + LoadArgs(args, thread_data); + Setup(); + LoopBlockY(); +} + +SSAInt SetupTriangleCodegen::FloatTo28_4(SSAFloat v) +{ + // SSAInt(SSAFloat::round(16.0f * v), false); + SSAInt a = SSAInt(v * 32.0f, false); + return (a + (a.ashr(31) | SSAInt(1))).ashr(1); +} + +void SetupTriangleCodegen::Setup() +{ + // 28.4 fixed-point coordinates + Y1 = FloatTo28_4(v1.y); + Y2 = FloatTo28_4(v2.y); + Y3 = FloatTo28_4(v3.y); + + X1 = FloatTo28_4(v1.x); + X2 = FloatTo28_4(v2.x); + X3 = FloatTo28_4(v3.x); + + // Deltas + DX12 = X1 - X2; + DX23 = X2 - X3; + DX31 = X3 - X1; + + DY12 = Y1 - Y2; + DY23 = Y2 - Y3; + DY31 = Y3 - Y1; + + // Fixed-point deltas + FDX12 = DX12 << 4; + FDX23 = DX23 << 4; + FDX31 = DX31 << 4; + + FDY12 = DY12 << 4; + FDY23 = DY23 << 4; + FDY31 = DY31 << 4; + + // Bounding rectangle + minx = SSAInt::MAX((SSAInt::MIN(SSAInt::MIN(X1, X2), X3) + 0xF).ashr(4), SSAInt(0)); + maxx = SSAInt::MIN((SSAInt::MAX(SSAInt::MAX(X1, X2), X3) + 0xF).ashr(4), clipright - 1); + miny = SSAInt::MAX((SSAInt::MIN(SSAInt::MIN(Y1, Y2), Y3) + 0xF).ashr(4), SSAInt(0)); + maxy = SSAInt::MIN((SSAInt::MAX(SSAInt::MAX(Y1, Y2), Y3) + 0xF).ashr(4), clipbottom - 1); + + SSAIfBlock if0; + if0.if_block(minx >= maxx || miny >= maxy); + if0.end_retvoid(); + + // Start in corner of 8x8 block + minx = minx & ~(q - 1); + miny = miny & ~(q - 1); + + // Half-edge constants + C1 = DY12 * X1 - DX12 * Y1; + C2 = DY23 * X2 - DX23 * Y2; + C3 = DY31 * X3 - DX31 * Y3; + + // Correct for fill convention + SSAIfBlock if1; + if1.if_block(DY12 < SSAInt(0) || (DY12 == SSAInt(0) && DX12 > SSAInt(0))); + stack_C1.store(C1 + 1); + if1.else_block(); + stack_C1.store(C1); + if1.end_block(); + C1 = stack_C1.load(); + SSAIfBlock if2; + if2.if_block(DY23 < SSAInt(0) || (DY23 == SSAInt(0) && DX23 > SSAInt(0))); + stack_C2.store(C2 + 1); + if2.else_block(); + stack_C2.store(C2); + if2.end_block(); + C2 = stack_C2.load(); + SSAIfBlock if3; + if3.if_block(DY31 < SSAInt(0) || (DY31 == SSAInt(0) && DX31 > SSAInt(0))); + stack_C3.store(C3 + 1); + if3.else_block(); + stack_C3.store(C3); + if3.end_block(); + C3 = stack_C3.load(); +} + +void SetupTriangleCodegen::LoopBlockY() +{ + SSAInt blocks_skipped = skipped_by_thread(miny / q, thread); + stack_y.store(miny + blocks_skipped * q); + stack_subsectorGBuffer.store(subsectorGBuffer[blocks_skipped * q * pitch]); + + SSAForBlock loop; + y = stack_y.load(); + subsectorGBuffer = stack_subsectorGBuffer.load(); + loop.loop_block(y < maxy, 0); + { + LoopBlockX(); + + stack_subsectorGBuffer.store(subsectorGBuffer[q * pitch * thread.num_cores]); + stack_y.store(y + thread.num_cores * q); + } + loop.end_block(); +} + +void SetupTriangleCodegen::LoopBlockX() +{ + stack_x.store(minx); + + SSAForBlock loop; + x = stack_x.load(); + loop.loop_block(x < maxx, 0); + { + // Corners of block + x0 = x << 4; + x1 = (x + q - 1) << 4; + y0 = y << 4; + y1 = (y + q - 1) << 4; + + // Evaluate half-space functions + SSABool a00 = C1 + DX12 * y0 - DY12 * x0 > SSAInt(0); + SSABool a10 = C1 + DX12 * y0 - DY12 * x1 > SSAInt(0); + SSABool a01 = C1 + DX12 * y1 - DY12 * x0 > SSAInt(0); + SSABool a11 = C1 + DX12 * y1 - DY12 * x1 > SSAInt(0); + + SSAInt a = (a00.zext_int() << 0) | (a10.zext_int() << 1) | (a01.zext_int() << 2) | (a11.zext_int() << 3); + + SSABool b00 = C2 + DX23 * y0 - DY23 * x0 > SSAInt(0); + SSABool b10 = C2 + DX23 * y0 - DY23 * x1 > SSAInt(0); + SSABool b01 = C2 + DX23 * y1 - DY23 * x0 > SSAInt(0); + SSABool b11 = C2 + DX23 * y1 - DY23 * x1 > SSAInt(0); + SSAInt b = (b00.zext_int() << 0) | (b10.zext_int() << 1) | (b01.zext_int() << 2) | (b11.zext_int() << 3); + + SSABool c00 = C3 + DX31 * y0 - DY31 * x0 > SSAInt(0); + SSABool c10 = C3 + DX31 * y0 - DY31 * x1 > SSAInt(0); + SSABool c01 = C3 + DX31 * y1 - DY31 * x0 > SSAInt(0); + SSABool c11 = C3 + DX31 * y1 - DY31 * x1 > SSAInt(0); + SSAInt c = (c00.zext_int() << 0) | (c10.zext_int() << 1) | (c01.zext_int() << 2) | (c11.zext_int() << 3); + + // Skip block when outside an edge + SSABool process_block = !(a == SSAInt(0) || b == SSAInt(0) || c == SSAInt(0)); + + SetStencilBlock(x / 8 + y / 8 * stencilPitch); + + // Stencil test the whole block, if possible + if (subsectorTest) + { + process_block = process_block && (!StencilIsSingleValue() || SSABool::compare_uge(StencilGetSingle(), stencilTestValue)); + } + else + { + process_block = process_block && (!StencilIsSingleValue() || StencilGetSingle() == stencilTestValue); + } + + SSAIfBlock branch; + branch.if_block(process_block); + + // Check if block needs clipping + SSABool clipneeded = (x + q) > clipright || (y + q) > clipbottom; + + SSABool covered = a == SSAInt(0xF) && b == SSAInt(0xF) && c == SSAInt(0xF) && !clipneeded && StencilIsSingleValue(); + + // Accept whole block when totally covered + SSAIfBlock branch_covered; + branch_covered.if_block(covered); + { + LoopFullBlock(); + } + branch_covered.else_block(); + { + SSAIfBlock branch_covered_stencil; + branch_covered_stencil.if_block(StencilIsSingleValue()); + { + SSABool stenciltestpass; + if (subsectorTest) + { + stenciltestpass = SSABool::compare_uge(StencilGetSingle(), stencilTestValue); + } + else + { + stenciltestpass = StencilGetSingle() == stencilTestValue; + } + + SSAIfBlock branch_stenciltestpass; + branch_stenciltestpass.if_block(stenciltestpass); + { + LoopPartialBlock(true); + } + branch_stenciltestpass.end_block(); + } + branch_covered_stencil.else_block(); + { + LoopPartialBlock(false); + } + branch_covered_stencil.end_block(); + } + branch_covered.end_block(); + + branch.end_block(); + + stack_x.store(x + q); + } + loop.end_block(); +} + +void SetupTriangleCodegen::LoopFullBlock() +{ + /* + if (variant == TriDrawVariant::Stencil) + { + StencilClear(stencilWriteValue); + } + else if (variant == TriDrawVariant::StencilClose) + { + StencilClear(stencilWriteValue); + for (int iy = 0; iy < q; iy++) + { + SSAIntPtr subsectorbuffer = subsectorGBuffer[x + iy * pitch]; + for (int ix = 0; ix < q; ix += 4) + { + subsectorbuffer[ix].store_unaligned_vec4i(SSAVec4i(subsectorDepth)); + } + } + } + else + { + int pixelsize = truecolor ? 4 : 1; + + AffineW = posx_w; + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosY[i] = posx_varying[i]; + + for (int iy = 0; iy < q; iy++) + { + SSAUBytePtr buffer = dest[(x + iy * pitch) * pixelsize]; + SSAIntPtr subsectorbuffer = subsectorGBuffer[x + iy * pitch]; + + SetupAffineBlock(); + + for (int ix = 0; ix < q; ix += 4) + { + SSAUBytePtr buf = buffer[ix * pixelsize]; + if (truecolor) + { + SSAVec16ub pixels16 = buf.load_unaligned_vec16ub(false); + SSAVec8s pixels8hi = SSAVec8s::extendhi(pixels16); + SSAVec8s pixels8lo = SSAVec8s::extendlo(pixels16); + SSAVec4i pixels[4] = + { + SSAVec4i::extendlo(pixels8lo), + SSAVec4i::extendhi(pixels8lo), + SSAVec4i::extendlo(pixels8hi), + SSAVec4i::extendhi(pixels8hi) + }; + + for (int sse = 0; sse < 4; sse++) + { + if (variant == TriDrawVariant::DrawSubsector || variant == TriDrawVariant::FillSubsector || variant == TriDrawVariant::FuzzSubsector) + { + SSABool subsectorTest = subsectorbuffer[ix].load(true) >= subsectorDepth; + pixels[sse] = subsectorTest.select(ProcessPixel32(pixels[sse], AffineVaryingPosX), pixels[sse]); + } + else + { + pixels[sse] = ProcessPixel32(pixels[sse], AffineVaryingPosX); + } + + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosX[i] = AffineVaryingPosX[i] + AffineVaryingStepX[i]; + } + + buf.store_unaligned_vec16ub(SSAVec16ub(SSAVec8s(pixels[0], pixels[1]), SSAVec8s(pixels[2], pixels[3]))); + } + else + { + SSAVec4i pixelsvec = buf.load_vec4ub(false); + SSAInt pixels[4] = + { + pixelsvec[0], + pixelsvec[1], + pixelsvec[2], + pixelsvec[3] + }; + + for (int sse = 0; sse < 4; sse++) + { + if (variant == TriDrawVariant::DrawSubsector || variant == TriDrawVariant::FillSubsector || variant == TriDrawVariant::FuzzSubsector) + { + SSABool subsectorTest = subsectorbuffer[ix].load(true) >= subsectorDepth; + pixels[sse] = subsectorTest.select(ProcessPixel8(pixels[sse], AffineVaryingPosX), pixels[sse]); + } + else + { + pixels[sse] = ProcessPixel8(pixels[sse], AffineVaryingPosX); + } + + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosX[i] = AffineVaryingPosX[i] + AffineVaryingStepX[i]; + } + + buf.store_vec4ub(SSAVec4i(pixels[0], pixels[1], pixels[2], pixels[3])); + } + + if (variant != TriDrawVariant::DrawSubsector && variant != TriDrawVariant::FillSubsector && variant != TriDrawVariant::FuzzSubsector) + subsectorbuffer[ix].store_unaligned_vec4i(SSAVec4i(subsectorDepth)); + } + + AffineW = AffineW + gradWY; + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosY[i] = AffineVaryingPosY[i] + gradVaryingY[i]; + } + } + */ +} + +void SetupTriangleCodegen::LoopPartialBlock(bool isSingleStencilValue) +{ + /* + int pixelsize = truecolor ? 4 : 1; + + if (variant == TriDrawVariant::Stencil || variant == TriDrawVariant::StencilClose) + { + if (isSingleStencilValue) + { + SSAInt stencilMask = StencilBlockMask.load(false); + SSAUByte val0 = stencilMask.trunc_ubyte(); + for (int i = 0; i < 8 * 8; i++) + StencilBlock[i].store(val0); + StencilBlockMask.store(SSAInt(0)); + } + + SSAUByte lastStencilValue = StencilBlock[0].load(false); + stack_stencilblock_restored.store(SSABool(true)); + stack_stencilblock_lastval.store(lastStencilValue); + } + + stack_CY1.store(C1 + DX12 * y0 - DY12 * x0); + stack_CY2.store(C2 + DX23 * y0 - DY23 * x0); + stack_CY3.store(C3 + DX31 * y0 - DY31 * x0); + stack_iy.store(SSAInt(0)); + stack_buffer.store(dest[x * pixelsize]); + stack_subsectorbuffer.store(subsectorGBuffer[x]); + stack_AffineW.store(posx_w); + for (int i = 0; i < TriVertex::NumVarying; i++) + { + stack_AffineVaryingPosY[i].store(posx_varying[i]); + } + + SSAForBlock loopy; + SSAInt iy = stack_iy.load(); + SSAUBytePtr buffer = stack_buffer.load(); + SSAIntPtr subsectorbuffer = stack_subsectorbuffer.load(); + SSAInt CY1 = stack_CY1.load(); + SSAInt CY2 = stack_CY2.load(); + SSAInt CY3 = stack_CY3.load(); + AffineW = stack_AffineW.load(); + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosY[i] = stack_AffineVaryingPosY[i].load(); + loopy.loop_block(iy < SSAInt(q), q); + { + SetupAffineBlock(); + + for (int i = 0; i < TriVertex::NumVarying; i++) + stack_AffineVaryingPosX[i].store(AffineVaryingPosX[i]); + + stack_CX1.store(CY1); + stack_CX2.store(CY2); + stack_CX3.store(CY3); + stack_ix.store(SSAInt(0)); + + SSAForBlock loopx; + SSABool stencilblock_restored; + SSAUByte lastStencilValue; + if (variant == TriDrawVariant::Stencil || variant == TriDrawVariant::StencilClose) + { + stencilblock_restored = stack_stencilblock_restored.load(); + lastStencilValue = stack_stencilblock_lastval.load(); + } + SSAInt ix = stack_ix.load(); + SSAInt CX1 = stack_CX1.load(); + SSAInt CX2 = stack_CX2.load(); + SSAInt CX3 = stack_CX3.load(); + for (int i = 0; i < TriVertex::NumVarying; i++) + AffineVaryingPosX[i] = stack_AffineVaryingPosX[i].load(); + loopx.loop_block(ix < SSAInt(q), q); + { + SSABool visible = (ix + x < clipright) && (iy + y < clipbottom); + SSABool covered = CX1 > SSAInt(0) && CX2 > SSAInt(0) && CX3 > SSAInt(0) && visible; + + if (!isSingleStencilValue) + { + SSAUByte stencilValue = StencilBlock[ix + iy * 8].load(false); + + if (variant == TriDrawVariant::DrawSubsector || variant == TriDrawVariant::FillSubsector || variant == TriDrawVariant::FuzzSubsector) + { + covered = covered && SSABool::compare_uge(stencilValue, stencilTestValue) && subsectorbuffer[ix].load(true) >= subsectorDepth; + } + else if (variant == TriDrawVariant::StencilClose) + { + covered = covered && SSABool::compare_uge(stencilValue, stencilTestValue); + } + else + { + covered = covered && stencilValue == stencilTestValue; + } + } + else if (variant == TriDrawVariant::DrawSubsector || variant == TriDrawVariant::FillSubsector || variant == TriDrawVariant::FuzzSubsector) + { + covered = covered && subsectorbuffer[ix].load(true) >= subsectorDepth; + } + + SSAIfBlock branch; + branch.if_block(covered); + { + if (variant == TriDrawVariant::Stencil) + { + StencilBlock[ix + iy * 8].store(stencilWriteValue); + } + else if (variant == TriDrawVariant::StencilClose) + { + StencilBlock[ix + iy * 8].store(stencilWriteValue); + subsectorbuffer[ix].store(subsectorDepth); + } + else + { + SSAUBytePtr buf = buffer[ix * pixelsize]; + + if (truecolor) + { + SSAVec4i bg = buf.load_vec4ub(false); + buf.store_vec4ub(ProcessPixel32(bg, AffineVaryingPosX)); + } + else + { + SSAUByte bg = buf.load(false); + buf.store(ProcessPixel8(bg.zext_int(), AffineVaryingPosX).trunc_ubyte()); + } + + if (variant != TriDrawVariant::DrawSubsector && variant != TriDrawVariant::FillSubsector && variant != TriDrawVariant::FuzzSubsector) + subsectorbuffer[ix].store(subsectorDepth); + } + } + branch.end_block(); + + if (variant == TriDrawVariant::Stencil || variant == TriDrawVariant::StencilClose) + { + SSAUByte newStencilValue = StencilBlock[ix + iy * 8].load(false); + stack_stencilblock_restored.store(stencilblock_restored && newStencilValue == lastStencilValue); + stack_stencilblock_lastval.store(newStencilValue); + } + + for (int i = 0; i < TriVertex::NumVarying; i++) + stack_AffineVaryingPosX[i].store(AffineVaryingPosX[i] + AffineVaryingStepX[i]); + + stack_CX1.store(CX1 - FDY12); + stack_CX2.store(CX2 - FDY23); + stack_CX3.store(CX3 - FDY31); + stack_ix.store(ix + 1); + } + loopx.end_block(); + + stack_AffineW.store(AffineW + gradWY); + for (int i = 0; i < TriVertex::NumVarying; i++) + stack_AffineVaryingPosY[i].store(AffineVaryingPosY[i] + gradVaryingY[i]); + stack_CY1.store(CY1 + FDX12); + stack_CY2.store(CY2 + FDX23); + stack_CY3.store(CY3 + FDX31); + stack_buffer.store(buffer[pitch * pixelsize]); + stack_subsectorbuffer.store(subsectorbuffer[pitch]); + stack_iy.store(iy + 1); + } + loopy.end_block(); + + if (variant == TriDrawVariant::Stencil || variant == TriDrawVariant::StencilClose) + { + SSAIfBlock branch; + SSABool restored = stack_stencilblock_restored.load(); + branch.if_block(restored); + { + SSAUByte lastStencilValue = stack_stencilblock_lastval.load(); + StencilClear(lastStencilValue); + } + branch.end_block(); + } + */ +} + +void SetupTriangleCodegen::SetStencilBlock(SSAInt block) +{ + StencilBlock = stencilValues[block * 64]; + StencilBlockMask = stencilMasks[block]; +} + +SSAUByte SetupTriangleCodegen::StencilGetSingle() +{ + return StencilBlockMask.load(false).trunc_ubyte(); +} + +void SetupTriangleCodegen::StencilClear(SSAUByte value) +{ + StencilBlockMask.store(SSAInt(0xffffff00) | value.zext_int()); +} + +SSABool SetupTriangleCodegen::StencilIsSingleValue() +{ + return (StencilBlockMask.load(false) & SSAInt(0xffffff00)) == SSAInt(0xffffff00); +} + +void SetupTriangleCodegen::LoadArgs(SSAValue args, SSAValue thread_data) +{ + pitch = args[0][1].load(true); + v1 = LoadTriVertex(args[0][2].load(true)); + v2 = LoadTriVertex(args[0][3].load(true)); + v3 = LoadTriVertex(args[0][4].load(true)); + clipright = args[0][6].load(true); + clipbottom = args[0][8].load(true); + stencilValues = args[0][14].load(true); + stencilMasks = args[0][15].load(true); + stencilPitch = args[0][16].load(true); + stencilTestValue = args[0][17].load(true); + stencilWriteValue = args[0][18].load(true); + subsectorGBuffer = args[0][19].load(true); + + thread.core = thread_data[0][0].load(true); + thread.num_cores = thread_data[0][1].load(true); + thread.pass_start_y = SSAInt(0); + thread.pass_end_y = SSAInt(32000); +} + +SSASetupVertex SetupTriangleCodegen::LoadTriVertex(SSAValue ptr) +{ + SSASetupVertex v; + v.x = ptr[0][0].load(true); + v.y = ptr[0][1].load(true); + v.z = ptr[0][2].load(true); + v.w = ptr[0][3].load(true); + return v; +} diff --git a/tools/drawergen/fixedfunction/setuptrianglecodegen.h b/tools/drawergen/fixedfunction/setuptrianglecodegen.h new file mode 100644 index 000000000..dda7b7667 --- /dev/null +++ b/tools/drawergen/fixedfunction/setuptrianglecodegen.h @@ -0,0 +1,98 @@ +/* +** SetupTriangle code generation +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "drawercodegen.h" + +struct SSASetupVertex +{ + SSAFloat x, y, z, w; +}; + +class SetupTriangleCodegen : public DrawerCodegen +{ +public: + void Generate(bool subsectorTest, SSAValue args, SSAValue thread_data); + +private: + void LoadArgs(SSAValue args, SSAValue thread_data); + SSASetupVertex LoadTriVertex(SSAValue v); + void Setup(); + SSAInt FloatTo28_4(SSAFloat v); + void LoopBlockY(); + void LoopBlockX(); + void LoopFullBlock(); + void LoopPartialBlock(bool isSingleStencilValue); + + void SetStencilBlock(SSAInt block); + void StencilClear(SSAUByte value); + SSAUByte StencilGetSingle(); + SSABool StencilIsSingleValue(); + + bool subsectorTest; + + SSAStack stack_C1, stack_C2, stack_C3; + SSAStack stack_y; + SSAStack stack_subsectorGBuffer; + SSAStack stack_x; + SSAStack stack_buffer; + SSAStack stack_iy, stack_ix; + SSAStack stack_CY1, stack_CY2, stack_CY3; + SSAStack stack_CX1, stack_CX2, stack_CX3; + //SSAStack stack_stencilblock_restored; + //SSAStack stack_stencilblock_lastval; + + SSAIntPtr subsectorGBuffer; + SSAInt pitch; + SSASetupVertex v1; + SSASetupVertex v2; + SSASetupVertex v3; + SSAInt clipright; + SSAInt clipbottom; + + SSAUBytePtr stencilValues; + SSAIntPtr stencilMasks; + SSAInt stencilPitch; + SSAUByte stencilTestValue; + SSAUByte stencilWriteValue; + + SSAWorkerThread thread; + + // Block size, standard 8x8 (must be power of two) + const int q = 8; + + SSAInt Y1, Y2, Y3; + SSAInt X1, X2, X3; + SSAInt DX12, DX23, DX31; + SSAInt DY12, DY23, DY31; + SSAInt FDX12, FDX23, FDX31; + SSAInt FDY12, FDY23, FDY31; + SSAInt minx, maxx, miny, maxy; + SSAInt C1, C2, C3; + + SSAInt x, y; + SSAInt x0, x1, y0, y1; + + SSAUBytePtr StencilBlock; + SSAIntPtr StencilBlockMask; +}; diff --git a/tools/drawergen/llvm_include.h b/tools/drawergen/llvm_include.h new file mode 100644 index 000000000..323eef014 --- /dev/null +++ b/tools/drawergen/llvm_include.h @@ -0,0 +1,99 @@ +/* +** LLVM includes +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#ifdef _MSC_VER + +#if defined(min) +#define llvm_min_bug min +#undef min +#endif +#if defined(max) +#define llvm_max_bug max +#undef max +#endif + +#pragma warning(disable: 4146) // warning C4146: unary minus operator applied to unsigned type, result still unsigned +#pragma warning(disable: 4624) // warning C4624: 'llvm::AugmentedUse' : destructor could not be generated because a base class destructor is inaccessible +#pragma warning(disable: 4355) // warning C4355: 'this' : used in base member initializer list +#pragma warning(disable: 4800) // warning C4800: 'const unsigned int' : forcing value to bool 'true' or 'false' (performance warning) +#pragma warning(disable: 4996) // warning C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_Sclan::SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' +#pragma warning(disable: 4244) // warning C4244: 'return' : conversion from 'uint64_t' to 'unsigned int', possible loss of data +#pragma warning(disable: 4141) // warning C4141: 'inline': used more than once +#pragma warning(disable: 4291) // warning C4291: 'void *llvm::User::operator new(std::size_t,unsigned int,unsigned int)': no matching operator delete found; memory will not be freed if initialization throws an exception +#pragma warning(disable: 4267) // warning C4267: 'return': conversion from 'size_t' to 'unsigned int', possible loss of data +#pragma warning(disable: 4244) // warning C4244: 'initializing': conversion from '__int64' to 'unsigned int', possible loss of data + +#endif + +#if defined(__APPLE__) || defined(__clang__) +#define __STDC_LIMIT_MACROS // DataTypes.h:57:3: error: "Must #define __STDC_LIMIT_MACROS before #including Support/DataTypes.h" +#define __STDC_CONSTANT_MACROS // DataTypes.h:61:3: error: "Must #define __STDC_CONSTANT_MACROS before " "#including Support/DataTypes.h" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wredundant-move" +#endif + +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) +#include +#endif + +#if defined(__APPLE__) || defined(__clang__) +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER + +#if defined(llvm_min_bug) +#define min llvm_min_bug +#undef llvm_min_bug +#endif +#if defined(llvm_max_bug) +#define max llvm_max_bug +#undef llvm_max_bug +#endif + +#endif diff --git a/tools/drawergen/llvmdrawers.cpp b/tools/drawergen/llvmdrawers.cpp new file mode 100644 index 000000000..099919997 --- /dev/null +++ b/tools/drawergen/llvmdrawers.cpp @@ -0,0 +1,435 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "llvmdrawers.h" +#include "exception.h" + +LLVMDrawers::LLVMDrawers(const std::string &triple, const std::string &cpuName, const std::string &features, const std::string namePostfix) : mNamePostfix(namePostfix) +{ + mProgram.CreateModule(); + + CodegenDrawColumn("FillColumn", DrawColumnVariant::Fill); + CodegenDrawColumn("FillColumnAdd", DrawColumnVariant::FillAdd); + CodegenDrawColumn("FillColumnAddClamp", DrawColumnVariant::FillAddClamp); + CodegenDrawColumn("FillColumnSubClamp", DrawColumnVariant::FillSubClamp); + CodegenDrawColumn("FillColumnRevSubClamp", DrawColumnVariant::FillRevSubClamp); + CodegenDrawColumn("DrawColumn", DrawColumnVariant::Draw); + CodegenDrawColumn("DrawColumnAdd", DrawColumnVariant::DrawAdd); + CodegenDrawColumn("DrawColumnShaded", DrawColumnVariant::DrawShaded); + CodegenDrawColumn("DrawColumnAddClamp", DrawColumnVariant::DrawAddClamp); + CodegenDrawColumn("DrawColumnSubClamp", DrawColumnVariant::DrawSubClamp); + CodegenDrawColumn("DrawColumnRevSubClamp", DrawColumnVariant::DrawRevSubClamp); + CodegenDrawColumn("DrawColumnTranslated", DrawColumnVariant::DrawTranslated); + CodegenDrawColumn("DrawColumnTlatedAdd", DrawColumnVariant::DrawTlatedAdd); + CodegenDrawColumn("DrawColumnAddClampTranslated", DrawColumnVariant::DrawAddClampTranslated); + CodegenDrawColumn("DrawColumnSubClampTranslated", DrawColumnVariant::DrawSubClampTranslated); + CodegenDrawColumn("DrawColumnRevSubClampTranslated", DrawColumnVariant::DrawRevSubClampTranslated); + CodegenDrawSpan("DrawSpan", DrawSpanVariant::Opaque); + CodegenDrawSpan("DrawSpanMasked", DrawSpanVariant::Masked); + CodegenDrawSpan("DrawSpanTranslucent", DrawSpanVariant::Translucent); + CodegenDrawSpan("DrawSpanMaskedTranslucent", DrawSpanVariant::MaskedTranslucent); + CodegenDrawSpan("DrawSpanAddClamp", DrawSpanVariant::AddClamp); + CodegenDrawSpan("DrawSpanMaskedAddClamp", DrawSpanVariant::MaskedAddClamp); + CodegenDrawWall("vlinec1", DrawWallVariant::Opaque, 1); + CodegenDrawWall("vlinec4", DrawWallVariant::Opaque, 4); + CodegenDrawWall("mvlinec1", DrawWallVariant::Masked, 1); + CodegenDrawWall("mvlinec4", DrawWallVariant::Masked, 4); + CodegenDrawWall("tmvline1_add", DrawWallVariant::Add, 1); + CodegenDrawWall("tmvline4_add", DrawWallVariant::Add, 4); + CodegenDrawWall("tmvline1_addclamp", DrawWallVariant::AddClamp, 1); + CodegenDrawWall("tmvline4_addclamp", DrawWallVariant::AddClamp, 4); + CodegenDrawWall("tmvline1_subclamp", DrawWallVariant::SubClamp, 1); + CodegenDrawWall("tmvline4_subclamp", DrawWallVariant::SubClamp, 4); + CodegenDrawWall("tmvline1_revsubclamp", DrawWallVariant::RevSubClamp, 1); + CodegenDrawWall("tmvline4_revsubclamp", DrawWallVariant::RevSubClamp, 4); + CodegenDrawSky("DrawSky1", DrawSkyVariant::Single, 1); + CodegenDrawSky("DrawSky4", DrawSkyVariant::Single, 4); + CodegenDrawSky("DrawDoubleSky1", DrawSkyVariant::Double, 1); + CodegenDrawSky("DrawDoubleSky4", DrawSkyVariant::Double, 4); + for (int i = 0; i < NumTriBlendModes(); i++) + { + CodegenDrawTriangle("TriDraw8_" + std::to_string(i), (TriBlendMode)i, false, false); + CodegenDrawTriangle("TriDraw32_" + std::to_string(i), (TriBlendMode)i, true, false); + CodegenDrawTriangle("TriFill8_" + std::to_string(i), (TriBlendMode)i, false, true); + CodegenDrawTriangle("TriFill32_" + std::to_string(i), (TriBlendMode)i, true, true); + } + + ObjectFile = mProgram.GenerateObjectFile(triple, cpuName, features); +} + +void LLVMDrawers::CodegenDrawColumn(const char *name, DrawColumnVariant variant) +{ + llvm::IRBuilder<> builder(mProgram.context()); + SSAScope ssa_scope(&mProgram.context(), mProgram.module(), &builder); + + SSAFunction function(name + mNamePostfix); + function.add_parameter(GetDrawColumnArgsStruct(mProgram.context())); + function.add_parameter(GetWorkerThreadDataStruct(mProgram.context())); + function.create_public(); + + DrawColumnCodegen codegen; + codegen.Generate(variant, function.parameter(0), function.parameter(1)); + + builder.CreateRetVoid(); + + if (llvm::verifyFunction(*function.func)) + throw Exception("verifyFunction failed for CodegenDrawColumn()"); +} + +void LLVMDrawers::CodegenDrawSpan(const char *name, DrawSpanVariant variant) +{ + llvm::IRBuilder<> builder(mProgram.context()); + SSAScope ssa_scope(&mProgram.context(), mProgram.module(), &builder); + + SSAFunction function(name + mNamePostfix); + function.add_parameter(GetDrawSpanArgsStruct(mProgram.context())); + function.create_public(); + + DrawSpanCodegen codegen; + codegen.Generate(variant, function.parameter(0)); + + builder.CreateRetVoid(); + + if (llvm::verifyFunction(*function.func)) + throw Exception("verifyFunction failed for CodegenDrawSpan()"); +} + +void LLVMDrawers::CodegenDrawWall(const char *name, DrawWallVariant variant, int columns) +{ + llvm::IRBuilder<> builder(mProgram.context()); + SSAScope ssa_scope(&mProgram.context(), mProgram.module(), &builder); + + SSAFunction function(name + mNamePostfix); + function.add_parameter(GetDrawWallArgsStruct(mProgram.context())); + function.add_parameter(GetWorkerThreadDataStruct(mProgram.context())); + function.create_public(); + + DrawWallCodegen codegen; + codegen.Generate(variant, columns == 4, function.parameter(0), function.parameter(1)); + + builder.CreateRetVoid(); + + if (llvm::verifyFunction(*function.func)) + throw Exception("verifyFunction failed for CodegenDrawWall()"); +} + +void LLVMDrawers::CodegenDrawSky(const char *name, DrawSkyVariant variant, int columns) +{ + llvm::IRBuilder<> builder(mProgram.context()); + SSAScope ssa_scope(&mProgram.context(), mProgram.module(), &builder); + + SSAFunction function(name + mNamePostfix); + function.add_parameter(GetDrawSkyArgsStruct(mProgram.context())); + function.add_parameter(GetWorkerThreadDataStruct(mProgram.context())); + function.create_public(); + + DrawSkyCodegen codegen; + codegen.Generate(variant, columns == 4, function.parameter(0), function.parameter(1)); + + builder.CreateRetVoid(); + + if (llvm::verifyFunction(*function.func)) + throw Exception("verifyFunction failed for CodegenDrawSky()"); +} + +void LLVMDrawers::CodegenDrawTriangle(const std::string &name, TriBlendMode blendmode, bool truecolor, bool colorfill) +{ + llvm::IRBuilder<> builder(mProgram.context()); + SSAScope ssa_scope(&mProgram.context(), mProgram.module(), &builder); + + SSAFunction function(name + mNamePostfix); + function.add_parameter(GetTriDrawTriangleArgs(mProgram.context())); + function.add_parameter(GetWorkerThreadDataStruct(mProgram.context())); + function.create_public(); + + DrawTriangleCodegen codegen; + codegen.Generate(blendmode, truecolor, colorfill, function.parameter(0), function.parameter(1)); + + builder.CreateRetVoid(); + + if (llvm::verifyFunction(*function.func)) + throw Exception("verifyFunction failed for CodegenDrawTriangle()"); +} + +llvm::Type *LLVMDrawers::GetDrawColumnArgsStruct(llvm::LLVMContext &context) +{ + if (DrawColumnArgsStruct) + return DrawColumnArgsStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint32_t *dest; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint32_t *source; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint32_t *source2; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint8_t *colormap; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint8_t *translation; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint32_t *basecolors; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t pitch; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t count; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t dest_y; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t iscale; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t texturefracx; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t textureheight; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t texturefrac; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t light; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t color; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t srccolor; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t srcalpha; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t destalpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t desaturate; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t flags; + DrawColumnArgsStruct = llvm::StructType::create(context, elements, "DrawColumnArgs", false)->getPointerTo(); + return DrawColumnArgsStruct; +} + +llvm::Type *LLVMDrawers::GetDrawSpanArgsStruct(llvm::LLVMContext &context) +{ + if (DrawSpanArgsStruct) + return DrawSpanArgsStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint8_t *destorg; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint32_t *source; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t destpitch; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t xfrac; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t yfrac; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t xstep; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t ystep; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t x1; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t x2; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t y; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t xbits; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t ybits; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t light; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t srcalpha; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t destalpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t desaturate; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t flags; + elements.push_back(llvm::Type::getFloatTy(context)); // float viewpos_x; + elements.push_back(llvm::Type::getFloatTy(context)); // float step_viewpos_x; + elements.push_back(GetTriLightStruct(context)); // TriLight *dynlights; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t num_dynlights; + DrawSpanArgsStruct = llvm::StructType::create(context, elements, "DrawSpanArgs", false)->getPointerTo(); + return DrawSpanArgsStruct; +} + +llvm::Type *LLVMDrawers::GetDrawWallArgsStruct(llvm::LLVMContext &context) +{ + if (DrawWallArgsStruct) + return DrawWallArgsStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt8PtrTy(context)); + for (int i = 0; i < 8; i++) + elements.push_back(llvm::Type::getInt8PtrTy(context)); + for (int i = 0; i < 25; i++) + elements.push_back(llvm::Type::getInt32Ty(context)); + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t desaturate; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t flags; + elements.push_back(llvm::Type::getFloatTy(context)); // float z; + elements.push_back(llvm::Type::getFloatTy(context)); // float step_z; + elements.push_back(GetTriLightStruct(context)); // TriLight *dynlights; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t num_dynlights; + + DrawWallArgsStruct = llvm::StructType::create(context, elements, "DrawWallArgs", false)->getPointerTo(); + return DrawWallArgsStruct; +} + +llvm::Type *LLVMDrawers::GetDrawSkyArgsStruct(llvm::LLVMContext &context) +{ + if (DrawSkyArgsStruct) + return DrawSkyArgsStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt8PtrTy(context)); + for (int i = 0; i < 8; i++) + elements.push_back(llvm::Type::getInt8PtrTy(context)); + for (int i = 0; i < 15; i++) + elements.push_back(llvm::Type::getInt32Ty(context)); + DrawSkyArgsStruct = llvm::StructType::create(context, elements, "DrawSkyArgs", false)->getPointerTo(); + return DrawSkyArgsStruct; +} + +llvm::Type *LLVMDrawers::GetWorkerThreadDataStruct(llvm::LLVMContext &context) +{ + if (WorkerThreadDataStruct) + return WorkerThreadDataStruct; + + std::vector elements; + for (int i = 0; i < 4; i++) + elements.push_back(llvm::Type::getInt32Ty(context)); + elements.push_back(llvm::Type::getInt8PtrTy(context)); + elements.push_back(GetTriFullSpanStruct(context)); + elements.push_back(GetTriPartialBlockStruct(context)); + for (int i = 0; i < 4; i++) + elements.push_back(llvm::Type::getInt32Ty(context)); + WorkerThreadDataStruct = llvm::StructType::create(context, elements, "ThreadData", false)->getPointerTo(); + return WorkerThreadDataStruct; +} + +llvm::Type *LLVMDrawers::GetTriLightStruct(llvm::LLVMContext &context) +{ + if (TriLightStruct) + return TriLightStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt32Ty(context)); + for (int i = 0; i < 4; i++) + elements.push_back(llvm::Type::getFloatTy(context)); + TriLightStruct = llvm::StructType::create(context, elements, "TriLight", false)->getPointerTo(); + return TriLightStruct; +} + +llvm::Type *LLVMDrawers::GetTriVertexStruct(llvm::LLVMContext &context) +{ + if (TriVertexStruct) + return TriVertexStruct; + + std::vector elements; + for (int i = 0; i < 4 + TriVertex::NumVarying; i++) + elements.push_back(llvm::Type::getFloatTy(context)); + TriVertexStruct = llvm::StructType::create(context, elements, "TriVertex", false)->getPointerTo(); + return TriVertexStruct; +} + +llvm::Type *LLVMDrawers::GetTriMatrixStruct(llvm::LLVMContext &context) +{ + if (TriMatrixStruct) + return TriMatrixStruct; + + std::vector elements; + for (int i = 0; i < 4 * 4; i++) + elements.push_back(llvm::Type::getFloatTy(context)); + TriMatrixStruct = llvm::StructType::create(context, elements, "TriMatrix", false)->getPointerTo(); + return TriMatrixStruct; +} + +llvm::Type *LLVMDrawers::GetTriUniformsStruct(llvm::LLVMContext &context) +{ + if (TriUniformsStruct) + return TriUniformsStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t light; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t subsectorDepth; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t color; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t srcalpha; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t destalpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t light_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_alpha; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_red; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_green; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t fade_blue; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint16_t desaturate; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t flags; + elements.push_back(GetTriMatrixStruct(context)); // TriMatrix objectToClip + TriUniformsStruct = llvm::StructType::create(context, elements, "TriUniforms", false)->getPointerTo(); + return TriUniformsStruct; +} + +llvm::Type *LLVMDrawers::GetTriFullSpanStruct(llvm::LLVMContext &context) +{ + if (TriFullSpanStruct) + return TriFullSpanStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint32_t X; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint32_t Y; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t Length; + TriFullSpanStruct = llvm::StructType::create(context, elements, "TriFullSpan", false)->getPointerTo(); + return TriFullSpanStruct; +} + +llvm::Type *LLVMDrawers::GetTriPartialBlockStruct(llvm::LLVMContext &context) +{ + if (TriPartialBlockStruct) + return TriPartialBlockStruct; + + std::vector elements; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint32_t X; + elements.push_back(llvm::Type::getInt16Ty(context)); // uint32_t Y; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t Mask0; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t Mask1; + TriPartialBlockStruct = llvm::StructType::create(context, elements, "TriPartialBlock", false)->getPointerTo(); + return TriPartialBlockStruct; +} + +llvm::Type *LLVMDrawers::GetTriDrawTriangleArgs(llvm::LLVMContext &context) +{ + if (TriDrawTriangleArgs) + return TriDrawTriangleArgs; + + std::vector elements; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint8_t *dest; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t pitch; + elements.push_back(GetTriVertexStruct(context)); // TriVertex *v1; + elements.push_back(GetTriVertexStruct(context)); // TriVertex *v2; + elements.push_back(GetTriVertexStruct(context)); // TriVertex *v3; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t clipleft; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t clipright; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t cliptop; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t clipbottom; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint8_t *texturePixels; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t textureWidth; + elements.push_back(llvm::Type::getInt32Ty(context)); // uint32_t textureHeight; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint8_t *translation; + elements.push_back(GetTriUniformsStruct(context)); // const TriUniforms *uniforms; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // uint8_t *stencilValues; + elements.push_back(llvm::Type::getInt32PtrTy(context)); // uint32_t *stencilMasks; + elements.push_back(llvm::Type::getInt32Ty(context)); // int32_t stencilPitch; + elements.push_back(llvm::Type::getInt8Ty(context)); // uint8_t stencilTestValue; + elements.push_back(llvm::Type::getInt8Ty(context)); // uint8_t stencilWriteValue; + elements.push_back(llvm::Type::getInt32PtrTy(context)); // uint32_t *subsectorGBuffer; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint8_t *colormaps; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint8_t *RGB256k; + elements.push_back(llvm::Type::getInt8PtrTy(context)); // const uint8_t *BaseColors; + TriDrawTriangleArgs = llvm::StructType::create(context, elements, "TriDrawTriangle", false)->getPointerTo(); + return TriDrawTriangleArgs; +} diff --git a/tools/drawergen/llvmdrawers.h b/tools/drawergen/llvmdrawers.h new file mode 100644 index 000000000..a7f1c8625 --- /dev/null +++ b/tools/drawergen/llvmdrawers.h @@ -0,0 +1,84 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "fixedfunction/drawspancodegen.h" +#include "fixedfunction/drawwallcodegen.h" +#include "fixedfunction/drawcolumncodegen.h" +#include "fixedfunction/drawskycodegen.h" +#include "fixedfunction/drawtrianglecodegen.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_scope.h" +#include "ssa/ssa_for_block.h" +#include "ssa/ssa_if_block.h" +#include "ssa/ssa_stack.h" +#include "ssa/ssa_function.h" +#include "ssa/ssa_struct_type.h" +#include "ssa/ssa_value.h" +#include "ssa/ssa_barycentric_weight.h" +#include "llvmprogram.h" +#include + +class LLVMDrawers +{ +public: + LLVMDrawers(const std::string &triple, const std::string &cpuName, const std::string &features, const std::string namePostfix); + + std::vector ObjectFile; + +private: + void CodegenDrawColumn(const char *name, DrawColumnVariant variant); + void CodegenDrawSpan(const char *name, DrawSpanVariant variant); + void CodegenDrawWall(const char *name, DrawWallVariant variant, int columns); + void CodegenDrawSky(const char *name, DrawSkyVariant variant, int columns); + void CodegenDrawTriangle(const std::string &name, TriBlendMode blendmode, bool truecolor, bool colorfill); + + llvm::Type *GetDrawColumnArgsStruct(llvm::LLVMContext &context); + llvm::Type *GetDrawSpanArgsStruct(llvm::LLVMContext &context); + llvm::Type *GetDrawWallArgsStruct(llvm::LLVMContext &context); + llvm::Type *GetDrawSkyArgsStruct(llvm::LLVMContext &context); + llvm::Type *GetWorkerThreadDataStruct(llvm::LLVMContext &context); + llvm::Type *GetTriLightStruct(llvm::LLVMContext &context); + llvm::Type *GetTriVertexStruct(llvm::LLVMContext &context); + llvm::Type *GetTriMatrixStruct(llvm::LLVMContext &context); + llvm::Type *GetTriUniformsStruct(llvm::LLVMContext &context); + llvm::Type *GetTriFullSpanStruct(llvm::LLVMContext &context); + llvm::Type *GetTriPartialBlockStruct(llvm::LLVMContext &context); + llvm::Type *GetTriDrawTriangleArgs(llvm::LLVMContext &context); + + llvm::Type *DrawColumnArgsStruct = nullptr; + llvm::Type *DrawSpanArgsStruct = nullptr; + llvm::Type *DrawWallArgsStruct = nullptr; + llvm::Type *DrawSkyArgsStruct = nullptr; + llvm::Type *WorkerThreadDataStruct = nullptr; + llvm::Type *TriLightStruct = nullptr; + llvm::Type *TriVertexStruct = nullptr; + llvm::Type *TriMatrixStruct = nullptr; + llvm::Type *TriUniformsStruct = nullptr; + llvm::Type *TriFullSpanStruct = nullptr; + llvm::Type *TriPartialBlockStruct = nullptr; + llvm::Type *TriDrawTriangleArgs = nullptr; + + LLVMProgram mProgram; + std::string mNamePostfix; +}; diff --git a/tools/drawergen/llvmprogram.cpp b/tools/drawergen/llvmprogram.cpp new file mode 100644 index 000000000..84094eda6 --- /dev/null +++ b/tools/drawergen/llvmprogram.cpp @@ -0,0 +1,171 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "timestamp.h" +#include "llvmprogram.h" + +LLVMProgram::LLVMProgram() +{ + mContext = std::make_unique(); +} + +void LLVMProgram::CreateModule() +{ + mModule = std::make_unique("render", context()); +} + +std::vector LLVMProgram::GenerateObjectFile(const std::string &triple, const std::string &cpuName, const std::string &features) +{ + using namespace llvm; + + std::string errorstring; + + llvm::Module *module = mModule.get(); + + const Target *target = TargetRegistry::lookupTarget(triple, errorstring); + +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + Reloc::Model relocationModel = Reloc::PIC_; +#else + Optional relocationModel = Reloc::PIC_; +#endif + + CodeModel::Model codeModel = CodeModel::Model::Default; + + TargetOptions options; + options.LessPreciseFPMADOption = true; + options.AllowFPOpFusion = FPOpFusion::Fast; + options.UnsafeFPMath = true; + options.NoInfsFPMath = true; + options.NoNaNsFPMath = true; + options.HonorSignDependentRoundingFPMathOption = false; + options.NoZerosInBSS = false; + options.GuaranteedTailCallOpt = false; + options.StackAlignmentOverride = 0; + options.UseInitArray = true; + options.DataSections = false; + options.FunctionSections = false; + options.JTType = JumpTable::Single; // Create a single table for all jumptable functions + options.ThreadModel = ThreadModel::POSIX; + options.DisableIntegratedAS = false; + options.MCOptions.SanitizeAddress = false; + options.MCOptions.MCRelaxAll = false; // relax all fixups in the emitted object file + options.MCOptions.DwarfVersion = 0; + options.MCOptions.ShowMCInst = false; + options.MCOptions.ABIName = ""; + options.MCOptions.MCFatalWarnings = false; + options.MCOptions.ShowMCEncoding = false; // Show encoding in .s output + options.MCOptions.MCUseDwarfDirectory = false; + options.MCOptions.AsmVerbose = true; + +#if LLVM_VERSION_MAJOR > 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 9) + options.Reciprocals = TargetRecip({ "all" }); + options.StackSymbolOrdering = true; + options.UniqueSectionNames = true; + options.EmulatedTLS = false; + options.ExceptionModel = ExceptionHandling::None; + options.EABIVersion = EABI::Default; + options.DebuggerTuning = DebuggerKind::Default; + options.MCOptions.MCIncrementalLinkerCompatible = false; + options.MCOptions.MCNoWarn = false; + options.MCOptions.PreserveAsmComments = true; +#endif + + CodeGenOpt::Level optimizationLevel = CodeGenOpt::Aggressive; + machine = target->createTargetMachine(triple, cpuName, features, options, relocationModel, codeModel, optimizationLevel); + + +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) + std::string targetTriple = machine->getTargetTriple(); +#else + std::string targetTriple = machine->getTargetTriple().getTriple(); +#endif + + module->setTargetTriple(targetTriple); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) + module->setDataLayout(new DataLayout(*machine->getSubtargetImpl()->getDataLayout())); +#else + module->setDataLayout(machine->createDataLayout()); +#endif + + legacy::FunctionPassManager PerFunctionPasses(module); + legacy::PassManager PerModulePasses; + +#if LLVM_VERSION_MAJOR > 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 8) + PerFunctionPasses.add(createTargetTransformInfoWrapperPass(machine->getTargetIRAnalysis())); + PerModulePasses.add(createTargetTransformInfoWrapperPass(machine->getTargetIRAnalysis())); +#endif + + SmallString<16 * 1024> str; +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) + raw_svector_ostream vecstream(str); + formatted_raw_ostream stream(vecstream); +#else + raw_svector_ostream stream(str); +#endif + machine->addPassesToEmitFile(PerModulePasses, stream, TargetMachine::CGFT_ObjectFile); + + PassManagerBuilder passManagerBuilder; + passManagerBuilder.OptLevel = 3; + passManagerBuilder.SizeLevel = 0; + passManagerBuilder.Inliner = createFunctionInliningPass(); + passManagerBuilder.SLPVectorize = true; + passManagerBuilder.LoopVectorize = true; + passManagerBuilder.LoadCombine = true; + passManagerBuilder.populateModulePassManager(PerModulePasses); + passManagerBuilder.populateFunctionPassManager(PerFunctionPasses); + + // Run function passes: + PerFunctionPasses.doInitialization(); + for (llvm::Function &func : *module) + { + if (!func.isDeclaration()) + PerFunctionPasses.run(func); + } + PerFunctionPasses.doFinalization(); + + // Run module passes: + PerModulePasses.run(*module); + + // Return the resulting object file +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) + stream.flush(); + vecstream.flush(); +#endif + std::vector data; + data.resize(str.size()); + memcpy(data.data(), str.data(), data.size()); + return data; +} + +std::string LLVMProgram::DumpModule() +{ + std::string str; + llvm::raw_string_ostream stream(str); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 8) + mModule->print(stream, nullptr); +#else + mModule->print(stream, nullptr, false, true); +#endif + return stream.str(); +} diff --git a/tools/drawergen/llvmprogram.h b/tools/drawergen/llvmprogram.h new file mode 100644 index 000000000..30cf33d5a --- /dev/null +++ b/tools/drawergen/llvmprogram.h @@ -0,0 +1,41 @@ +/* +** LLVM code generated drawers +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +class LLVMProgram +{ +public: + LLVMProgram(); + + void CreateModule(); + std::vector GenerateObjectFile(const std::string &triple, const std::string &cpuName, const std::string &features); + std::string DumpModule(); + + llvm::LLVMContext &context() { return *mContext; } + llvm::Module *module() { return mModule.get(); } + +private: + llvm::TargetMachine *machine = nullptr; + std::unique_ptr mContext; + std::unique_ptr mModule; +}; diff --git a/tools/drawergen/precomp.h b/tools/drawergen/precomp.h new file mode 100644 index 000000000..ea5a5e6df --- /dev/null +++ b/tools/drawergen/precomp.h @@ -0,0 +1,5 @@ + +#pragma once + +#include "llvm_include.h" +#include "../../src/r_drawers.h" diff --git a/tools/drawergen/ssa/ssa_barycentric_weight.h b/tools/drawergen/ssa/ssa_barycentric_weight.h new file mode 100644 index 000000000..1a07d6c75 --- /dev/null +++ b/tools/drawergen/ssa/ssa_barycentric_weight.h @@ -0,0 +1,118 @@ +/* +** SSA barycentric weight and viewport calculations +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_vec4f.h" +#include "ssa_float.h" +#include "ssa_int.h" + +class SSAViewport +{ +public: + SSAViewport(SSAInt x, SSAInt y, SSAInt width, SSAInt height) + : x(x), y(y), width(width), height(height), right(x + width), bottom(y + height), + half_width(SSAFloat(width) * 0.5f), half_height(SSAFloat(height) * 0.5f), + rcp_half_width(1.0f / (SSAFloat(width) * 0.5f)), + rcp_half_height(1.0f / (SSAFloat(height) * 0.5f)) + { + } + + SSAInt x, y; + SSAInt width, height; + SSAInt right, bottom; + SSAFloat half_width; + SSAFloat half_height; + SSAFloat rcp_half_width; + SSAFloat rcp_half_height; + + SSAVec4f clip_to_window(SSAVec4f clip) const + { + SSAFloat w = clip[3]; + SSAVec4f normalized = SSAVec4f::insert_element(clip / SSAVec4f::shuffle(clip, 3, 3, 3, 3), w, 3); + return normalized_to_window(normalized); + } + + SSAVec4f normalized_to_window(SSAVec4f normalized) const + { + return SSAVec4f( + SSAFloat(x) + (normalized[0] + 1.0f) * half_width, + SSAFloat(y) + (normalized[1] + 1.0f) * half_height, + 0.0f - normalized[2], + normalized[3]); + } +}; + +class SSABarycentricWeight +{ +public: + SSABarycentricWeight(SSAViewport vp, SSAVec4f v1, SSAVec4f v2); + SSAFloat from_window_x(SSAInt x) const; + SSAFloat from_window_y(SSAInt y) const; + + SSAViewport viewport; + SSAVec4f v1; + SSAVec4f v2; +}; + +inline SSABarycentricWeight::SSABarycentricWeight(SSAViewport viewport, SSAVec4f v1, SSAVec4f v2) +: viewport(viewport), v1(v1), v2(v2) +{ +} + +inline SSAFloat SSABarycentricWeight::from_window_x(SSAInt x) const +{ +/* SSAFloat xnormalized = (x + 0.5f - viewport.x) * viewport.rcp_half_width - 1.0f; + SSAFloat dx = v2.x-v1.x; + SSAFloat dw = v2.w-v1.w; + SSAFloat a = (v2.x - xnormalized * v2.w) / (dx - xnormalized * dw); + return a;*/ + + SSAFloat xnormalized = (SSAFloat(x) + 0.5f - SSAFloat(viewport.x)) * viewport.rcp_half_width - 1.0f; + SSAFloat dx = v2[0]-v1[0]; + SSAFloat dw = v2[3]-v1[3]; + SSAFloat t = (xnormalized * v1[3] - v1[0]) / (dx - xnormalized * dw); + return 1.0f - t; +} + +inline SSAFloat SSABarycentricWeight::from_window_y(SSAInt y) const +{ +/* SSAFloat ynormalized = (y + 0.5f - viewport.y) * viewport.rcp_half_height - 1.0f; + SSAFloat dy = v2.y-v1.y; + SSAFloat dw = v2.w-v1.w; + SSAFloat a = (v2.y - ynormalized * v2.w) / (dy - ynormalized * dw); + return a;*/ + + SSAFloat ynormalized = (SSAFloat(y) + 0.5f - SSAFloat(viewport.y)) * viewport.rcp_half_height - 1.0f; + SSAFloat dy = v2[1]-v1[1]; + SSAFloat dw = v2[3]-v1[3]; + SSAFloat t = (ynormalized * v1[3] - v1[1]) / (dy - ynormalized * dw); + return 1.0f - t; +} + +/* + y = (v1.y + t * dy) / (v1.w + t * dw) + + y * v1.w + y * t * dw = v1.y + t * dy + y * v1.w - v1.y = t * (dy - y * dw) + t = (y * v1.w - v1.y) / (dy - y * dw) +*/ diff --git a/tools/drawergen/ssa/ssa_bool.cpp b/tools/drawergen/ssa/ssa_bool.cpp new file mode 100644 index 000000000..7ce99b827 --- /dev/null +++ b/tools/drawergen/ssa/ssa_bool.cpp @@ -0,0 +1,168 @@ +/* +** SSA boolean +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_bool.h" +#include "ssa_ubyte.h" +#include "ssa_vec4i.h" +#include "ssa_value.h" +#include "ssa_scope.h" + +SSABool::SSABool() +: v(0) +{ +} + +SSABool::SSABool(bool constant) +: v(0) +{ + v = llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(1, constant, false)); +} + +SSABool::SSABool(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSABool::llvm_type() +{ + return llvm::Type::getInt1Ty(SSAScope::context()); +} + +SSAInt SSABool::zext_int() +{ + return SSAInt::from_llvm(SSAScope::builder().CreateZExt(v, SSAInt::llvm_type(), SSAScope::hint())); +} + +SSAInt SSABool::select(SSAInt a, SSAInt b) +{ + return SSAValue::from_llvm(SSAScope::builder().CreateSelect(v, a.v, b.v, SSAScope::hint())); +} + +SSAUByte SSABool::select(SSAUByte a, SSAUByte b) +{ + return SSAValue::from_llvm(SSAScope::builder().CreateSelect(v, a.v, b.v, SSAScope::hint())); +} + +SSAVec4i SSABool::select(SSAVec4i a, SSAVec4i b) +{ + return SSAValue::from_llvm(SSAScope::builder().CreateSelect(v, a.v, b.v, SSAScope::hint())); +} + +SSABool SSABool::compare_uge(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpUGE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator&&(const SSABool &a, const SSABool &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateAnd(a.v, b.v, SSAScope::hint())); +} + +SSABool operator||(const SSABool &a, const SSABool &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateOr(a.v, b.v, SSAScope::hint())); +} + +SSABool operator!(const SSABool &a) +{ + return SSABool::from_llvm(SSAScope::builder().CreateNot(a.v, SSAScope::hint())); +} + +SSABool operator<(const SSAInt &a, const SSAInt &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSLT(a.v, b.v, SSAScope::hint())); +} + +SSABool operator<=(const SSAInt &a, const SSAInt &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSLE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator==(const SSAInt &a, const SSAInt &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpEQ(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>=(const SSAInt &a, const SSAInt &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSGE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>(const SSAInt &a, const SSAInt &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSGT(a.v, b.v, SSAScope::hint())); +} + +///////////////////////////////////////////////////////////////////////////// + +SSABool operator<(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSLT(a.v, b.v, SSAScope::hint())); +} + +SSABool operator<=(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSLE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator==(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpEQ(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>=(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSGE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>(const SSAUByte &a, const SSAUByte &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateICmpSGT(a.v, b.v, SSAScope::hint())); +} + +///////////////////////////////////////////////////////////////////////////// + +SSABool operator<(const SSAFloat &a, const SSAFloat &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateFCmpOLT(a.v, b.v, SSAScope::hint())); +} + +SSABool operator<=(const SSAFloat &a, const SSAFloat &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateFCmpOLE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator==(const SSAFloat &a, const SSAFloat &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateFCmpOEQ(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>=(const SSAFloat &a, const SSAFloat &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateFCmpOGE(a.v, b.v, SSAScope::hint())); +} + +SSABool operator>(const SSAFloat &a, const SSAFloat &b) +{ + return SSABool::from_llvm(SSAScope::builder().CreateFCmpOGT(a.v, b.v, SSAScope::hint())); +} diff --git a/tools/drawergen/ssa/ssa_bool.h b/tools/drawergen/ssa/ssa_bool.h new file mode 100644 index 000000000..728c7b7e8 --- /dev/null +++ b/tools/drawergen/ssa/ssa_bool.h @@ -0,0 +1,74 @@ +/* +** SSA boolean +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_int.h" +#include "ssa_ubyte.h" +#include "ssa_float.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4i; + +class SSABool +{ +public: + SSABool(); + explicit SSABool(bool constant); + explicit SSABool(llvm::Value *v); + static SSABool from_llvm(llvm::Value *v) { return SSABool(v); } + static llvm::Type *llvm_type(); + + SSAInt zext_int(); + SSAInt select(SSAInt a, SSAInt b); + SSAUByte select(SSAUByte a, SSAUByte b); + SSAVec4i select(SSAVec4i a, SSAVec4i b); + + static SSABool compare_uge(const SSAUByte &a, const SSAUByte &b); + + llvm::Value *v; +}; + +SSABool operator&&(const SSABool &a, const SSABool &b); +SSABool operator||(const SSABool &a, const SSABool &b); + +SSABool operator!(const SSABool &a); + +SSABool operator<(const SSAInt &a, const SSAInt &b); +SSABool operator<=(const SSAInt &a, const SSAInt &b); +SSABool operator==(const SSAInt &a, const SSAInt &b); +SSABool operator>=(const SSAInt &a, const SSAInt &b); +SSABool operator>(const SSAInt &a, const SSAInt &b); + +SSABool operator<(const SSAUByte &a, const SSAUByte &b); +SSABool operator<=(const SSAUByte &a, const SSAUByte &b); +SSABool operator==(const SSAUByte &a, const SSAUByte &b); +SSABool operator>=(const SSAUByte &a, const SSAUByte &b); +SSABool operator>(const SSAUByte &a, const SSAUByte &b); + +SSABool operator<(const SSAFloat &a, const SSAFloat &b); +SSABool operator<=(const SSAFloat &a, const SSAFloat &b); +SSABool operator==(const SSAFloat &a, const SSAFloat &b); +SSABool operator>=(const SSAFloat &a, const SSAFloat &b); +SSABool operator>(const SSAFloat &a, const SSAFloat &b); diff --git a/tools/drawergen/ssa/ssa_float.cpp b/tools/drawergen/ssa/ssa_float.cpp new file mode 100644 index 000000000..f537792fc --- /dev/null +++ b/tools/drawergen/ssa/ssa_float.cpp @@ -0,0 +1,219 @@ +/* +** SSA float32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_float.h" +#include "ssa_int.h" +#include "ssa_scope.h" +#include "ssa_bool.h" +#include "ssa_vec4f.h" + +SSAFloat::SSAFloat() +: v(0) +{ +} + +SSAFloat::SSAFloat(float constant) +: v(0) +{ + v = llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant)); +} + +SSAFloat::SSAFloat(SSAInt i) +: v(0) +{ + v = SSAScope::builder().CreateSIToFP(i.v, llvm::Type::getFloatTy(SSAScope::context()), SSAScope::hint()); +} + +SSAFloat::SSAFloat(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAFloat::llvm_type() +{ + return llvm::Type::getFloatTy(SSAScope::context()); +} + +SSAFloat SSAFloat::sqrt(SSAFloat f) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::sqrt, params), f.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::fastsqrt(SSAFloat f) +{ + return f * rsqrt(f); +} + +SSAFloat SSAFloat::rsqrt(SSAFloat f) +{ + llvm::Value *f_ss = SSAScope::builder().CreateInsertElement(llvm::UndefValue::get(SSAVec4f::llvm_type()), f.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)0))); + f_ss = SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse_rsqrt_ss), f_ss, SSAScope::hint()); + return SSAFloat::from_llvm(SSAScope::builder().CreateExtractElement(f_ss, SSAInt(0).v, SSAScope::hint())); +} + +SSAFloat SSAFloat::sin(SSAFloat val) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::sin, params), val.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::cos(SSAFloat val) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::cos, params), val.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::pow(SSAFloat val, SSAFloat power) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + //params.push_back(SSAFloat::llvm_type()); + std::vector args; + args.push_back(val.v); + args.push_back(power.v); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::pow, params), args, SSAScope::hint())); +} + +SSAFloat SSAFloat::exp(SSAFloat val) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::exp, params), val.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::log(SSAFloat val) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::log, params), val.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::fma(SSAFloat a, SSAFloat b, SSAFloat c) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + //params.push_back(SSAFloat::llvm_type()); + //params.push_back(SSAFloat::llvm_type()); + std::vector args; + args.push_back(a.v); + args.push_back(b.v); + args.push_back(c.v); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::fma, params), args, SSAScope::hint())); +} + +/* This intrinsic isn't always available.. +SSAFloat SSAFloat::round(SSAFloat val) +{ + + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::round, params), val.v, SSAScope::hint())); +} +*/ + +SSAFloat SSAFloat::floor(SSAFloat val) +{ + std::vector params; + params.push_back(SSAFloat::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::floor, params), val.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::MIN(SSAFloat a, SSAFloat b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateSelect((a < b).v, a.v, b.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::MAX(SSAFloat a, SSAFloat b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateSelect((a > b).v, a.v, b.v, SSAScope::hint())); +} + +SSAFloat SSAFloat::clamp(SSAFloat a, SSAFloat b, SSAFloat c) +{ + return SSAFloat::MAX(SSAFloat::MIN(a, c), b); +} + +SSAFloat operator+(const SSAFloat &a, const SSAFloat &b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateFAdd(a.v, b.v, SSAScope::hint())); +} + +SSAFloat operator-(const SSAFloat &a, const SSAFloat &b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateFSub(a.v, b.v, SSAScope::hint())); +} + +SSAFloat operator*(const SSAFloat &a, const SSAFloat &b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateFMul(a.v, b.v, SSAScope::hint())); +} + +SSAFloat operator/(const SSAFloat &a, const SSAFloat &b) +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateFDiv(a.v, b.v, SSAScope::hint())); +} + +SSAFloat operator+(float a, const SSAFloat &b) +{ + return SSAFloat(a) + b; +} + +SSAFloat operator-(float a, const SSAFloat &b) +{ + return SSAFloat(a) - b; +} + +SSAFloat operator*(float a, const SSAFloat &b) +{ + return SSAFloat(a) * b; +} + +SSAFloat operator/(float a, const SSAFloat &b) +{ + return SSAFloat(a) / b; +} + +SSAFloat operator+(const SSAFloat &a, float b) +{ + return a + SSAFloat(b); +} + +SSAFloat operator-(const SSAFloat &a, float b) +{ + return a - SSAFloat(b); +} + +SSAFloat operator*(const SSAFloat &a, float b) +{ + return a * SSAFloat(b); +} + +SSAFloat operator/(const SSAFloat &a, float b) +{ + return a / SSAFloat(b); +} + diff --git a/tools/drawergen/ssa/ssa_float.h b/tools/drawergen/ssa/ssa_float.h new file mode 100644 index 000000000..f7e2b93ef --- /dev/null +++ b/tools/drawergen/ssa/ssa_float.h @@ -0,0 +1,70 @@ +/* +** SSA float32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAInt; + +class SSAFloat +{ +public: + SSAFloat(); + SSAFloat(SSAInt i); + explicit SSAFloat(float constant); + explicit SSAFloat(llvm::Value *v); + static SSAFloat from_llvm(llvm::Value *v) { return SSAFloat(v); } + static llvm::Type *llvm_type(); + static SSAFloat sqrt(SSAFloat f); + static SSAFloat fastsqrt(SSAFloat f); + static SSAFloat rsqrt(SSAFloat f); + static SSAFloat sin(SSAFloat val); + static SSAFloat cos(SSAFloat val); + static SSAFloat pow(SSAFloat val, SSAFloat power); + static SSAFloat exp(SSAFloat val); + static SSAFloat log(SSAFloat val); + static SSAFloat fma(SSAFloat a, SSAFloat b, SSAFloat c); + //static SSAFloat round(SSAFloat val); + static SSAFloat floor(SSAFloat val); + static SSAFloat MIN(SSAFloat a, SSAFloat b); + static SSAFloat MAX(SSAFloat a, SSAFloat b); + static SSAFloat clamp(SSAFloat a, SSAFloat b, SSAFloat c); + + llvm::Value *v; +}; + +SSAFloat operator+(const SSAFloat &a, const SSAFloat &b); +SSAFloat operator-(const SSAFloat &a, const SSAFloat &b); +SSAFloat operator*(const SSAFloat &a, const SSAFloat &b); +SSAFloat operator/(const SSAFloat &a, const SSAFloat &b); + +SSAFloat operator+(float a, const SSAFloat &b); +SSAFloat operator-(float a, const SSAFloat &b); +SSAFloat operator*(float a, const SSAFloat &b); +SSAFloat operator/(float a, const SSAFloat &b); + +SSAFloat operator+(const SSAFloat &a, float b); +SSAFloat operator-(const SSAFloat &a, float b); +SSAFloat operator*(const SSAFloat &a, float b); +SSAFloat operator/(const SSAFloat &a, float b); diff --git a/tools/drawergen/ssa/ssa_float_ptr.cpp b/tools/drawergen/ssa/ssa_float_ptr.cpp new file mode 100644 index 000000000..731fbbef8 --- /dev/null +++ b/tools/drawergen/ssa/ssa_float_ptr.cpp @@ -0,0 +1,91 @@ +/* +** SSA float32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_float_ptr.h" +#include "ssa_scope.h" + +SSAFloatPtr::SSAFloatPtr() +: v(0) +{ +} + +SSAFloatPtr::SSAFloatPtr(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAFloatPtr::llvm_type() +{ + return llvm::Type::getFloatPtrTy(SSAScope::context()); +} + +SSAFloatPtr SSAFloatPtr::operator[](SSAInt index) const +{ + return SSAFloatPtr::from_llvm(SSAScope::builder().CreateGEP(v, index.v, SSAScope::hint())); +} + +SSAFloat SSAFloatPtr::load(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateLoad(v, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAFloat::from_llvm(loadInst); +} + +SSAVec4f SSAFloatPtr::load_vec4f(bool constantScopeDomain) const +{ + llvm::PointerType *m4xfloattypeptr = llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m4xfloattypeptr, SSAScope::hint()), 16, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4f::from_llvm(loadInst); +} + +SSAVec4f SSAFloatPtr::load_unaligned_vec4f(bool constantScopeDomain) const +{ + llvm::PointerType *m4xfloattypeptr = llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m4xfloattypeptr, SSAScope::hint()), 1, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4f::from_llvm(loadInst); +} + +void SSAFloatPtr::store(const SSAFloat &new_value) +{ + auto inst = SSAScope::builder().CreateStore(new_value.v, v, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAFloatPtr::store_vec4f(const SSAVec4f &new_value) +{ + llvm::PointerType *m4xfloattypeptr = llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4)->getPointerTo(); + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m4xfloattypeptr, SSAScope::hint()), 16); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAFloatPtr::store_unaligned_vec4f(const SSAVec4f &new_value) +{ + llvm::PointerType *m4xfloattypeptr = llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4)->getPointerTo(); + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m4xfloattypeptr, SSAScope::hint()), 4); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} diff --git a/tools/drawergen/ssa/ssa_float_ptr.h b/tools/drawergen/ssa/ssa_float_ptr.h new file mode 100644 index 000000000..66e462539 --- /dev/null +++ b/tools/drawergen/ssa/ssa_float_ptr.h @@ -0,0 +1,49 @@ +/* +** SSA float32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_float.h" +#include "ssa_int.h" +#include "ssa_vec4f.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAFloatPtr +{ +public: + SSAFloatPtr(); + explicit SSAFloatPtr(llvm::Value *v); + static SSAFloatPtr from_llvm(llvm::Value *v) { return SSAFloatPtr(v); } + static llvm::Type *llvm_type(); + SSAFloatPtr operator[](SSAInt index) const; + SSAFloatPtr operator[](int index) const { return (*this)[SSAInt(index)]; } + SSAFloat load(bool constantScopeDomain) const; + SSAVec4f load_vec4f(bool constantScopeDomain) const; + SSAVec4f load_unaligned_vec4f(bool constantScopeDomain) const; + void store(const SSAFloat &new_value); + void store_vec4f(const SSAVec4f &new_value); + void store_unaligned_vec4f(const SSAVec4f &new_value); + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_for_block.cpp b/tools/drawergen/ssa/ssa_for_block.cpp new file mode 100644 index 000000000..12b2f1fc5 --- /dev/null +++ b/tools/drawergen/ssa/ssa_for_block.cpp @@ -0,0 +1,62 @@ +/* +** LLVM for loop branching +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_for_block.h" +#include "ssa_scope.h" + +SSAForBlock::SSAForBlock() +: if_basic_block(0), loop_basic_block(0), end_basic_block(0) +{ + if_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "forbegin", SSAScope::builder().GetInsertBlock()->getParent()); + loop_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "forloop", SSAScope::builder().GetInsertBlock()->getParent()); + end_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "forend", SSAScope::builder().GetInsertBlock()->getParent()); + SSAScope::builder().CreateBr(if_basic_block); + SSAScope::builder().SetInsertPoint(if_basic_block); +} + +void SSAForBlock::loop_block(SSABool true_condition, int unroll_count) +{ + auto branch = SSAScope::builder().CreateCondBr(true_condition.v, loop_basic_block, end_basic_block); +#if LLVM_VERSION_MAJOR > 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 9) + if (unroll_count > 0) + { + using namespace llvm; + auto md_unroll_enable = MDNode::get(SSAScope::context(), { + MDString::get(SSAScope::context(), "llvm.loop.unroll.enable") + }); + auto md_unroll_count = MDNode::get(SSAScope::context(), { + MDString::get(SSAScope::context(), "llvm.loop.unroll.count"), + ConstantAsMetadata::get(ConstantInt::get(SSAScope::context(), APInt(32, unroll_count))) + }); + auto md_loop = MDNode::getDistinct(SSAScope::context(), { md_unroll_enable, md_unroll_count }); + branch->setMetadata(LLVMContext::MD_loop, md_loop); + } +#endif + SSAScope::builder().SetInsertPoint(loop_basic_block); +} + +void SSAForBlock::end_block() +{ + SSAScope::builder().CreateBr(if_basic_block); + SSAScope::builder().SetInsertPoint(end_basic_block); +} diff --git a/tools/drawergen/ssa/ssa_for_block.h b/tools/drawergen/ssa/ssa_for_block.h new file mode 100644 index 000000000..b65fb1c8b --- /dev/null +++ b/tools/drawergen/ssa/ssa_for_block.h @@ -0,0 +1,38 @@ +/* +** LLVM for loop branching +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_bool.h" + +class SSAForBlock +{ +public: + SSAForBlock(); + void loop_block(SSABool true_condition, int unroll_count = 8); + void end_block(); + +private: + llvm::BasicBlock *if_basic_block; + llvm::BasicBlock *loop_basic_block; + llvm::BasicBlock *end_basic_block; +}; diff --git a/tools/drawergen/ssa/ssa_function.cpp b/tools/drawergen/ssa/ssa_function.cpp new file mode 100644 index 000000000..e21b0b229 --- /dev/null +++ b/tools/drawergen/ssa/ssa_function.cpp @@ -0,0 +1,76 @@ +/* +** LLVM function +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_function.h" +#include "ssa_int.h" +#include "ssa_scope.h" +#include "ssa_value.h" + +SSAFunction::SSAFunction(const std::string name) +: func(), name(name), return_type(llvm::Type::getVoidTy(SSAScope::context())) +{ +} + +void SSAFunction::set_return_type(llvm::Type *type) +{ + return_type = type; +} + +void SSAFunction::add_parameter(llvm::Type *type) +{ + parameters.push_back(type); +} + +void SSAFunction::create_public() +{ + func = SSAScope::module()->getFunction(name.c_str()); + if (func == 0) + { + llvm::FunctionType *function_type = llvm::FunctionType::get(return_type, parameters, false); + func = llvm::Function::Create(function_type, llvm::Function::ExternalLinkage, name.c_str(), SSAScope::module()); + //func->setCallingConv(llvm::CallingConv::X86_StdCall); + } + llvm::BasicBlock *entry = llvm::BasicBlock::Create(SSAScope::context(), "entry", func); + SSAScope::builder().SetInsertPoint(entry); +} + +void SSAFunction::create_private() +{ + func = SSAScope::module()->getFunction(name.c_str()); + if (func == 0) + { + llvm::FunctionType *function_type = llvm::FunctionType::get(return_type, parameters, false); + func = llvm::Function::Create(function_type, llvm::Function::PrivateLinkage, name.c_str(), SSAScope::module()); + func->addFnAttr(llvm::Attribute::AlwaysInline); + } + llvm::BasicBlock *entry = llvm::BasicBlock::Create(SSAScope::context(), "entry", func); + SSAScope::builder().SetInsertPoint(entry); +} + +SSAValue SSAFunction::parameter(int index) +{ + llvm::Function::arg_iterator arg_it = func->arg_begin(); + for (int i = 0; i < index; i++) + ++arg_it; + return SSAValue::from_llvm(static_cast(arg_it)); +} diff --git a/tools/drawergen/ssa/ssa_function.h b/tools/drawergen/ssa/ssa_function.h new file mode 100644 index 000000000..faa8b03fe --- /dev/null +++ b/tools/drawergen/ssa/ssa_function.h @@ -0,0 +1,51 @@ +/* +** LLVM function +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include +#include + +namespace llvm { class Value; } +namespace llvm { class Type; } +namespace llvm { class Function; } + +class SSAInt; +class SSAValue; + +class SSAFunction +{ +public: + SSAFunction(const std::string name); + void set_return_type(llvm::Type *type); + void add_parameter(llvm::Type *type); + void create_public(); + void create_private(); + SSAValue parameter(int index); + + llvm::Function *func; + +private: + std::string name; + llvm::Type *return_type; + std::vector parameters; +}; diff --git a/tools/drawergen/ssa/ssa_if_block.cpp b/tools/drawergen/ssa/ssa_if_block.cpp new file mode 100644 index 000000000..068073f98 --- /dev/null +++ b/tools/drawergen/ssa/ssa_if_block.cpp @@ -0,0 +1,58 @@ +/* +** LLVM if statement branching +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_if_block.h" +#include "ssa_scope.h" + +SSAIfBlock::SSAIfBlock() +: if_basic_block(0), else_basic_block(0), end_basic_block(0) +{ +} + +void SSAIfBlock::if_block(SSABool true_condition) +{ + if_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "if", SSAScope::builder().GetInsertBlock()->getParent()); + else_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "else", SSAScope::builder().GetInsertBlock()->getParent()); + end_basic_block = else_basic_block; + SSAScope::builder().CreateCondBr(true_condition.v, if_basic_block, else_basic_block); + SSAScope::builder().SetInsertPoint(if_basic_block); +} + +void SSAIfBlock::else_block() +{ + end_basic_block = llvm::BasicBlock::Create(SSAScope::context(), "end", SSAScope::builder().GetInsertBlock()->getParent()); + SSAScope::builder().CreateBr(end_basic_block); + SSAScope::builder().SetInsertPoint(else_basic_block); +} + +void SSAIfBlock::end_block() +{ + SSAScope::builder().CreateBr(end_basic_block); + SSAScope::builder().SetInsertPoint(end_basic_block); +} + +void SSAIfBlock::end_retvoid() +{ + SSAScope::builder().CreateRetVoid(); + SSAScope::builder().SetInsertPoint(end_basic_block); +} diff --git a/tools/drawergen/ssa/ssa_if_block.h b/tools/drawergen/ssa/ssa_if_block.h new file mode 100644 index 000000000..b958883eb --- /dev/null +++ b/tools/drawergen/ssa/ssa_if_block.h @@ -0,0 +1,67 @@ +/* +** LLVM if statement branching +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_bool.h" +#include "ssa_phi.h" + +class SSAIfBlock +{ +public: + SSAIfBlock(); + void if_block(SSABool true_condition); + void else_block(); + void end_block(); + void end_retvoid(); + +private: + llvm::BasicBlock *if_basic_block; + llvm::BasicBlock *else_basic_block; + llvm::BasicBlock *end_basic_block; +}; + +template +T ssa_min(T a, T b) +{ + SSAPhi phi; + SSAIfBlock if_block; + if_block.if_block(a <= b); + phi.add_incoming(a); + if_block.else_block(); + phi.add_incoming(b); + if_block.end_block(); + return phi.create(); +} + +template +T ssa_max(T a, T b) +{ + SSAPhi phi; + SSAIfBlock if_block; + if_block.if_block(a >= b); + phi.add_incoming(a); + if_block.else_block(); + phi.add_incoming(b); + if_block.end_block(); + return phi.create(); +} diff --git a/tools/drawergen/ssa/ssa_int.cpp b/tools/drawergen/ssa/ssa_int.cpp new file mode 100644 index 000000000..3bee48a7e --- /dev/null +++ b/tools/drawergen/ssa/ssa_int.cpp @@ -0,0 +1,208 @@ +/* +** SSA int32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_int.h" +#include "ssa_float.h" +#include "ssa_ubyte.h" +#include "ssa_bool.h" +#include "ssa_scope.h" + +SSAInt::SSAInt() +: v(0) +{ +} + +SSAInt::SSAInt(int constant) +: v(0) +{ + v = llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant, true)); +} + +SSAInt::SSAInt(SSAFloat f, bool uint) +: v(0) +{ + if (uint) + v = SSAScope::builder().CreateFPToUI(f.v, llvm::Type::getInt32Ty(SSAScope::context()), SSAScope::hint()); + else + v = SSAScope::builder().CreateFPToSI(f.v, llvm::Type::getInt32Ty(SSAScope::context()), SSAScope::hint()); +} + +SSAInt::SSAInt(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAInt::llvm_type() +{ + return llvm::Type::getInt32Ty(SSAScope::context()); +} + +SSAInt SSAInt::MIN(SSAInt a, SSAInt b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateSelect((a < b).v, a.v, b.v, SSAScope::hint())); +} + +SSAInt SSAInt::MAX(SSAInt a, SSAInt b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateSelect((a > b).v, a.v, b.v, SSAScope::hint())); +} + +SSAInt SSAInt::clamp(SSAInt a, SSAInt b, SSAInt c) +{ + return SSAInt::MAX(SSAInt::MIN(a, c), b); +} + +SSAInt SSAInt::add(SSAInt b, bool no_unsigned_wrap, bool no_signed_wrap) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateAdd(v, b.v, SSAScope::hint(), no_unsigned_wrap, no_signed_wrap)); +} + +SSAInt SSAInt::ashr(int bits) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateAShr(v, bits, SSAScope::hint())); +} + +SSAUByte SSAInt::trunc_ubyte() +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateTrunc(v, SSAUByte::llvm_type(), SSAScope::hint())); +} + +SSAInt operator+(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator-(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator*(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator/(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateSDiv(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator%(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateSRem(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator+(int a, const SSAInt &b) +{ + return SSAInt(a) + b; +} + +SSAInt operator-(int a, const SSAInt &b) +{ + return SSAInt(a) - b; +} + +SSAInt operator*(int a, const SSAInt &b) +{ + return SSAInt(a) * b; +} + +SSAInt operator/(int a, const SSAInt &b) +{ + return SSAInt(a) / b; +} + +SSAInt operator%(int a, const SSAInt &b) +{ + return SSAInt(a) % b; +} + +SSAInt operator+(const SSAInt &a, int b) +{ + return a + SSAInt(b); +} + +SSAInt operator-(const SSAInt &a, int b) +{ + return a - SSAInt(b); +} + +SSAInt operator*(const SSAInt &a, int b) +{ + return a * SSAInt(b); +} + +SSAInt operator/(const SSAInt &a, int b) +{ + return a / SSAInt(b); +} + +SSAInt operator%(const SSAInt &a, int b) +{ + return a % SSAInt(b); +} + +SSAInt operator<<(const SSAInt &a, int bits) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateShl(a.v, bits, SSAScope::hint())); +} + +SSAInt operator>>(const SSAInt &a, int bits) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateLShr(a.v, bits, SSAScope::hint())); +} + +SSAInt operator<<(const SSAInt &a, const SSAInt &bits) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateShl(a.v, bits.v, SSAScope::hint())); +} + +SSAInt operator>>(const SSAInt &a, const SSAInt &bits) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateLShr(a.v, bits.v, SSAScope::hint())); +} + +SSAInt operator&(const SSAInt &a, int b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateAnd(a.v, b, SSAScope::hint())); +} + +SSAInt operator&(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateAnd(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator|(const SSAInt &a, int b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateOr(a.v, b, SSAScope::hint())); +} + +SSAInt operator|(const SSAInt &a, const SSAInt &b) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateOr(a.v, b.v, SSAScope::hint())); +} + +SSAInt operator~(const SSAInt &a) +{ + return SSAInt::from_llvm(SSAScope::builder().CreateNot(a.v, SSAScope::hint())); +} diff --git a/tools/drawergen/ssa/ssa_int.h b/tools/drawergen/ssa/ssa_int.h new file mode 100644 index 000000000..dab8adcb9 --- /dev/null +++ b/tools/drawergen/ssa/ssa_int.h @@ -0,0 +1,80 @@ +/* +** SSA int32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAFloat; +class SSAUByte; + +class SSAInt +{ +public: + SSAInt(); + explicit SSAInt(int constant); + SSAInt(SSAFloat f, bool uint); + explicit SSAInt(llvm::Value *v); + static SSAInt from_llvm(llvm::Value *v) { return SSAInt(v); } + static llvm::Type *llvm_type(); + + static SSAInt MIN(SSAInt a, SSAInt b); + static SSAInt MAX(SSAInt a, SSAInt b); + static SSAInt clamp(SSAInt a, SSAInt b, SSAInt c); + + SSAInt add(SSAInt b, bool no_unsigned_wrap, bool no_signed_wrap); + SSAInt ashr(int bits); + + SSAUByte trunc_ubyte(); + + llvm::Value *v; +}; + +SSAInt operator+(const SSAInt &a, const SSAInt &b); +SSAInt operator-(const SSAInt &a, const SSAInt &b); +SSAInt operator*(const SSAInt &a, const SSAInt &b); +SSAInt operator/(const SSAInt &a, const SSAInt &b); +SSAInt operator%(const SSAInt &a, const SSAInt &b); + +SSAInt operator+(int a, const SSAInt &b); +SSAInt operator-(int a, const SSAInt &b); +SSAInt operator*(int a, const SSAInt &b); +SSAInt operator/(int a, const SSAInt &b); +SSAInt operator%(int a, const SSAInt &b); + +SSAInt operator+(const SSAInt &a, int b); +SSAInt operator-(const SSAInt &a, int b); +SSAInt operator*(const SSAInt &a, int b); +SSAInt operator/(const SSAInt &a, int b); +SSAInt operator%(const SSAInt &a, int b); + +SSAInt operator<<(const SSAInt &a, int bits); +SSAInt operator>>(const SSAInt &a, int bits); +SSAInt operator<<(const SSAInt &a, const SSAInt &bits); +SSAInt operator>>(const SSAInt &a, const SSAInt &bits); + +SSAInt operator&(const SSAInt &a, int b); +SSAInt operator&(const SSAInt &a, const SSAInt &b); +SSAInt operator|(const SSAInt &a, int b); +SSAInt operator|(const SSAInt &a, const SSAInt &b); +SSAInt operator~(const SSAInt &a); diff --git a/tools/drawergen/ssa/ssa_int_ptr.cpp b/tools/drawergen/ssa/ssa_int_ptr.cpp new file mode 100644 index 000000000..5f60f7358 --- /dev/null +++ b/tools/drawergen/ssa/ssa_int_ptr.cpp @@ -0,0 +1,111 @@ +/* +** SSA int32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_int_ptr.h" +#include "ssa_scope.h" +#include "ssa_bool.h" + +SSAIntPtr::SSAIntPtr() +: v(0) +{ +} + +SSAIntPtr::SSAIntPtr(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAIntPtr::llvm_type() +{ + return llvm::Type::getInt32PtrTy(SSAScope::context()); +} + +SSAIntPtr SSAIntPtr::operator[](SSAInt index) const +{ + return SSAIntPtr::from_llvm(SSAScope::builder().CreateGEP(v, index.v, SSAScope::hint())); +} + +SSAInt SSAIntPtr::load(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateLoad(v, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAInt::from_llvm(loadInst); +} + +SSAVec4i SSAIntPtr::load_vec4i(bool constantScopeDomain) const +{ + llvm::PointerType *m4xint32typeptr = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m4xint32typeptr, SSAScope::hint()), 16, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4i::from_llvm(loadInst); +} + +SSAVec4i SSAIntPtr::load_unaligned_vec4i(bool constantScopeDomain) const +{ + llvm::PointerType *m4xint32typeptr = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m4xint32typeptr, SSAScope::hint()), 1, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4i::from_llvm(loadInst); +} + +void SSAIntPtr::store(const SSAInt &new_value) +{ + auto inst = SSAScope::builder().CreateStore(new_value.v, v, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAIntPtr::store_vec4i(const SSAVec4i &new_value) +{ + llvm::PointerType *m4xint32typeptr = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m4xint32typeptr, SSAScope::hint()), 16); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAIntPtr::store_unaligned_vec4i(const SSAVec4i &new_value) +{ + llvm::PointerType *m4xint32typeptr = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m4xint32typeptr, SSAScope::hint()), 4); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAIntPtr::store_masked_vec4i(const SSAVec4i &new_value, SSABool mask[4]) +{ + // Create mask vector + std::vector maskconstants; + maskconstants.resize(4, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(1, 0, false))); + llvm::Value *maskValue = llvm::ConstantVector::get(maskconstants); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + for (int i = 0; i < 4; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i].v, SSAInt(i).v, SSAScope::hint()); +#else + for (int i = 0; i < 4; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i].v, (uint64_t)i, SSAScope::hint()); +#endif + + llvm::PointerType *m4xint32typeptr = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); + auto inst = SSAScope::builder().CreateMaskedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m4xint32typeptr, SSAScope::hint()), 1, maskValue); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} diff --git a/tools/drawergen/ssa/ssa_int_ptr.h b/tools/drawergen/ssa/ssa_int_ptr.h new file mode 100644 index 000000000..da6ecf168 --- /dev/null +++ b/tools/drawergen/ssa/ssa_int_ptr.h @@ -0,0 +1,52 @@ +/* +** SSA int32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_float.h" +#include "ssa_int.h" +#include "ssa_vec4i.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSABool; + +class SSAIntPtr +{ +public: + SSAIntPtr(); + explicit SSAIntPtr(llvm::Value *v); + static SSAIntPtr from_llvm(llvm::Value *v) { return SSAIntPtr(v); } + static llvm::Type *llvm_type(); + SSAIntPtr operator[](SSAInt index) const; + SSAIntPtr operator[](int index) const { return (*this)[SSAInt(index)]; } + SSAInt load(bool constantScopeDomain) const; + SSAVec4i load_vec4i(bool constantScopeDomain) const; + SSAVec4i load_unaligned_vec4i(bool constantScopeDomain) const; + void store(const SSAInt &new_value); + void store_vec4i(const SSAVec4i &new_value); + void store_unaligned_vec4i(const SSAVec4i &new_value); + void store_masked_vec4i(const SSAVec4i &new_value, SSABool mask[4]); + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_phi.h b/tools/drawergen/ssa/ssa_phi.h new file mode 100644 index 000000000..66f233b6d --- /dev/null +++ b/tools/drawergen/ssa/ssa_phi.h @@ -0,0 +1,54 @@ +/* +** SSA phi node +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_scope.h" + +class SSAIfBlock; + +template +class SSAPhi +{ +public: + void add_incoming(SSAVariable var) + { + incoming.push_back(Incoming(var.v, SSAScope::builder().GetInsertBlock())); + } + + SSAVariable create() + { + llvm::PHINode *phi_node = SSAScope::builder().CreatePHI(SSAVariable::llvm_type(), (unsigned int)incoming.size(), SSAScope::hint()); + for (size_t i = 0; i < incoming.size(); i++) + phi_node->addIncoming(incoming[i].v, incoming[i].bb); + return SSAVariable::from_llvm(phi_node); + } + +private: + struct Incoming + { + Incoming(llvm::Value *v, llvm::BasicBlock *bb) : v(v), bb(bb) { } + llvm::Value *v; + llvm::BasicBlock *bb; + }; + std::vector incoming; +}; diff --git a/tools/drawergen/ssa/ssa_scope.cpp b/tools/drawergen/ssa/ssa_scope.cpp new file mode 100644 index 000000000..6f081a74a --- /dev/null +++ b/tools/drawergen/ssa/ssa_scope.cpp @@ -0,0 +1,96 @@ +/* +** SSA scope data +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_scope.h" +#include "ssa_int.h" + +SSAScope::SSAScope(llvm::LLVMContext *context, llvm::Module *module, llvm::IRBuilder<> *builder) +: _context(context), _module(module), _builder(builder) +{ + instance = this; + + _constant_scope_domain = llvm::MDNode::get(SSAScope::context(), { llvm::MDString::get(SSAScope::context(), "ConstantScopeDomain") }); + _constant_scope = llvm::MDNode::getDistinct(SSAScope::context(), { _constant_scope_domain }); + _constant_scope_list = llvm::MDNode::get(SSAScope::context(), { _constant_scope }); +} + +SSAScope::~SSAScope() +{ + instance = 0; +} + +llvm::LLVMContext &SSAScope::context() +{ + return *instance->_context; +} + +llvm::Module *SSAScope::module() +{ + return instance->_module; +} + +llvm::IRBuilder<> &SSAScope::builder() +{ + return *instance->_builder; +} + +llvm::Function *SSAScope::intrinsic(llvm::Intrinsic::ID id, llvm::ArrayRef parameter_types) +{ + llvm::Function *func = module()->getFunction(llvm::Intrinsic::getName(id, parameter_types)); + if (func == 0) + func = llvm::Function::Create(llvm::Intrinsic::getType(context(), id, parameter_types), llvm::Function::ExternalLinkage, llvm::Intrinsic::getName(id, parameter_types), module()); + return func; +} + +llvm::Value *SSAScope::alloc_stack(llvm::Type *type) +{ + return alloc_stack(type, SSAInt(1)); +} + +llvm::Value *SSAScope::alloc_stack(llvm::Type *type, SSAInt size) +{ + // Allocas must be created at top of entry block for the PromoteMemoryToRegisterPass to work + llvm::BasicBlock &entry = SSAScope::builder().GetInsertBlock()->getParent()->getEntryBlock(); + llvm::IRBuilder<> alloca_builder(&entry, entry.begin()); + return alloca_builder.CreateAlloca(type, size.v, hint()); +} + +llvm::MDNode *SSAScope::constant_scope_list() +{ + return instance->_constant_scope_list; +} + +const std::string &SSAScope::hint() +{ + return instance->_hint; +} + +void SSAScope::set_hint(const std::string &new_hint) +{ + if (new_hint.empty()) + instance->_hint = "tmp"; + else + instance->_hint = new_hint; +} + +SSAScope *SSAScope::instance = 0; diff --git a/tools/drawergen/ssa/ssa_scope.h b/tools/drawergen/ssa/ssa_scope.h new file mode 100644 index 000000000..0b0228558 --- /dev/null +++ b/tools/drawergen/ssa/ssa_scope.h @@ -0,0 +1,64 @@ +/* +** SSA scope data +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +class SSAInt; + +class SSAScope +{ +public: + SSAScope(llvm::LLVMContext *context, llvm::Module *module, llvm::IRBuilder<> *builder); + ~SSAScope(); + static llvm::LLVMContext &context(); + static llvm::Module *module(); + static llvm::IRBuilder<> &builder(); + static llvm::Function *intrinsic(llvm::Intrinsic::ID id, llvm::ArrayRef parameter_types = llvm::ArrayRef()); + static llvm::Value *alloc_stack(llvm::Type *type); + static llvm::Value *alloc_stack(llvm::Type *type, SSAInt size); + static llvm::MDNode *constant_scope_list(); + static const std::string &hint(); + static void set_hint(const std::string &hint); + +private: + static SSAScope *instance; + llvm::LLVMContext *_context; + llvm::Module *_module; + llvm::IRBuilder<> *_builder; + llvm::MDNode *_constant_scope_domain; + llvm::MDNode *_constant_scope; + llvm::MDNode *_constant_scope_list; + std::string _hint; +}; + +class SSAScopeHint +{ +public: + SSAScopeHint() : old_hint(SSAScope::hint()) { } + SSAScopeHint(const std::string &hint) : old_hint(SSAScope::hint()) { SSAScope::set_hint(hint); } + ~SSAScopeHint() { SSAScope::set_hint(old_hint); } + void set(const std::string &hint) { SSAScope::set_hint(hint); } + void clear() { SSAScope::set_hint(old_hint); } + +private: + std::string old_hint; +}; diff --git a/tools/drawergen/ssa/ssa_short.cpp b/tools/drawergen/ssa/ssa_short.cpp new file mode 100644 index 000000000..ed9d90dd0 --- /dev/null +++ b/tools/drawergen/ssa/ssa_short.cpp @@ -0,0 +1,174 @@ +/* +** SSA int16 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_short.h" +#include "ssa_float.h" +#include "ssa_int.h" +#include "ssa_scope.h" + +SSAShort::SSAShort() +: v(0) +{ +} + +SSAShort::SSAShort(int constant) +: v(0) +{ + v = llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant, true)); +} + +SSAShort::SSAShort(SSAFloat f) +: v(0) +{ + v = SSAScope::builder().CreateFPToSI(f.v, llvm::Type::getInt16Ty(SSAScope::context()), SSAScope::hint()); +} + +SSAShort::SSAShort(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAShort::llvm_type() +{ + return llvm::Type::getInt16Ty(SSAScope::context()); +} + +SSAInt SSAShort::zext_int() +{ + return SSAInt::from_llvm(SSAScope::builder().CreateZExt(v, SSAInt::llvm_type(), SSAScope::hint())); +} + +SSAShort operator+(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator-(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator*(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator/(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateSDiv(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator%(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateSRem(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator+(int a, const SSAShort &b) +{ + return SSAShort(a) + b; +} + +SSAShort operator-(int a, const SSAShort &b) +{ + return SSAShort(a) - b; +} + +SSAShort operator*(int a, const SSAShort &b) +{ + return SSAShort(a) * b; +} + +SSAShort operator/(int a, const SSAShort &b) +{ + return SSAShort(a) / b; +} + +SSAShort operator%(int a, const SSAShort &b) +{ + return SSAShort(a) % b; +} + +SSAShort operator+(const SSAShort &a, int b) +{ + return a + SSAShort(b); +} + +SSAShort operator-(const SSAShort &a, int b) +{ + return a - SSAShort(b); +} + +SSAShort operator*(const SSAShort &a, int b) +{ + return a * SSAShort(b); +} + +SSAShort operator/(const SSAShort &a, int b) +{ + return a / SSAShort(b); +} + +SSAShort operator%(const SSAShort &a, int b) +{ + return a % SSAShort(b); +} + +SSAShort operator<<(const SSAShort &a, int bits) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateShl(a.v, bits, SSAScope::hint())); +} + +SSAShort operator>>(const SSAShort &a, int bits) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateLShr(a.v, bits, SSAScope::hint())); +} + +SSAShort operator<<(const SSAShort &a, const SSAInt &bits) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateShl(a.v, bits.v, SSAScope::hint())); +} + +SSAShort operator>>(const SSAShort &a, const SSAInt &bits) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateLShr(a.v, bits.v, SSAScope::hint())); +} + +SSAShort operator&(const SSAShort &a, int b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateAnd(a.v, b, SSAScope::hint())); +} + +SSAShort operator&(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateAnd(a.v, b.v, SSAScope::hint())); +} + +SSAShort operator|(const SSAShort &a, int b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateOr(a.v, b, SSAScope::hint())); +} + +SSAShort operator|(const SSAShort &a, const SSAShort &b) +{ + return SSAShort::from_llvm(SSAScope::builder().CreateOr(a.v, b.v, SSAScope::hint())); +} diff --git a/tools/drawergen/ssa/ssa_short.h b/tools/drawergen/ssa/ssa_short.h new file mode 100644 index 000000000..efb782b85 --- /dev/null +++ b/tools/drawergen/ssa/ssa_short.h @@ -0,0 +1,72 @@ +/* +** SSA int16 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAFloat; +class SSAInt; + +class SSAShort +{ +public: + SSAShort(); + explicit SSAShort(int constant); + SSAShort(SSAFloat f); + explicit SSAShort(llvm::Value *v); + static SSAShort from_llvm(llvm::Value *v) { return SSAShort(v); } + static llvm::Type *llvm_type(); + + SSAInt zext_int(); + + llvm::Value *v; +}; + +SSAShort operator+(const SSAShort &a, const SSAShort &b); +SSAShort operator-(const SSAShort &a, const SSAShort &b); +SSAShort operator*(const SSAShort &a, const SSAShort &b); +SSAShort operator/(const SSAShort &a, const SSAShort &b); +SSAShort operator%(const SSAShort &a, const SSAShort &b); + +SSAShort operator+(int a, const SSAShort &b); +SSAShort operator-(int a, const SSAShort &b); +SSAShort operator*(int a, const SSAShort &b); +SSAShort operator/(int a, const SSAShort &b); +SSAShort operator%(int a, const SSAShort &b); + +SSAShort operator+(const SSAShort &a, int b); +SSAShort operator-(const SSAShort &a, int b); +SSAShort operator*(const SSAShort &a, int b); +SSAShort operator/(const SSAShort &a, int b); +SSAShort operator%(const SSAShort &a, int b); + +SSAShort operator<<(const SSAShort &a, int bits); +SSAShort operator>>(const SSAShort &a, int bits); +SSAShort operator<<(const SSAShort &a, const SSAInt &bits); +SSAShort operator>>(const SSAShort &a, const SSAInt &bits); + +SSAShort operator&(const SSAShort &a, int b); +SSAShort operator&(const SSAShort &a, const SSAShort &b); +SSAShort operator|(const SSAShort &a, int b); +SSAShort operator|(const SSAShort &a, const SSAShort &b); diff --git a/tools/drawergen/ssa/ssa_stack.h b/tools/drawergen/ssa/ssa_stack.h new file mode 100644 index 000000000..24c807a8a --- /dev/null +++ b/tools/drawergen/ssa/ssa_stack.h @@ -0,0 +1,48 @@ +/* +** LLVM stack variable +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_scope.h" + +template +class SSAStack +{ +public: + SSAStack() + : v(0) + { + v = SSAScope::alloc_stack(SSAVariable::llvm_type()); + } + + SSAVariable load() const + { + return SSAVariable::from_llvm(SSAScope::builder().CreateLoad(v, SSAScope::hint())); + } + + void store(const SSAVariable &new_value) + { + SSAScope::builder().CreateStore(new_value.v, v); + } + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_struct_type.cpp b/tools/drawergen/ssa/ssa_struct_type.cpp new file mode 100644 index 000000000..9e11154ed --- /dev/null +++ b/tools/drawergen/ssa/ssa_struct_type.cpp @@ -0,0 +1,40 @@ +/* +** LLVM struct +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_struct_type.h" +#include "ssa_scope.h" + +void SSAStructType::add_parameter(llvm::Type *type) +{ + elements.push_back(type); +} + +llvm::Type *SSAStructType::llvm_type() +{ + return llvm::StructType::get(SSAScope::context(), elements, false); +} + +llvm::Type *SSAStructType::llvm_type_packed() +{ + return llvm::StructType::get(SSAScope::context(), elements, true); +} diff --git a/tools/drawergen/ssa/ssa_struct_type.h b/tools/drawergen/ssa/ssa_struct_type.h new file mode 100644 index 000000000..f21dc92c3 --- /dev/null +++ b/tools/drawergen/ssa/ssa_struct_type.h @@ -0,0 +1,38 @@ +/* +** LLVM struct +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include + +namespace llvm { class Type; } + +class SSAStructType +{ +public: + void add_parameter(llvm::Type *type); + llvm::Type *llvm_type(); + llvm::Type *llvm_type_packed(); + +private: + std::vector elements; +}; diff --git a/tools/drawergen/ssa/ssa_ubyte.cpp b/tools/drawergen/ssa/ssa_ubyte.cpp new file mode 100644 index 000000000..2ca75d036 --- /dev/null +++ b/tools/drawergen/ssa/ssa_ubyte.cpp @@ -0,0 +1,122 @@ +/* +** SSA uint8 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_ubyte.h" +#include "ssa_int.h" +#include "ssa_scope.h" + +SSAUByte::SSAUByte() +: v(0) +{ +} + +SSAUByte::SSAUByte(unsigned char constant) +: v(0) +{ + v = llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant, false)); +} + +SSAUByte::SSAUByte(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAUByte::llvm_type() +{ + return llvm::Type::getInt8Ty(SSAScope::context()); +} + +SSAInt SSAUByte::zext_int() +{ + return SSAInt::from_llvm(SSAScope::builder().CreateZExt(v, SSAInt::llvm_type(), SSAScope::hint())); +} + +SSAUByte operator+(const SSAUByte &a, const SSAUByte &b) +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAUByte operator-(const SSAUByte &a, const SSAUByte &b) +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAUByte operator*(const SSAUByte &a, const SSAUByte &b) +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} +/* +SSAUByte operator/(const SSAUByte &a, const SSAUByte &b) +{ + return SSAScope::builder().CreateDiv(a.v, b.v); +} +*/ +SSAUByte operator+(unsigned char a, const SSAUByte &b) +{ + return SSAUByte(a) + b; +} + +SSAUByte operator-(unsigned char a, const SSAUByte &b) +{ + return SSAUByte(a) - b; +} + +SSAUByte operator*(unsigned char a, const SSAUByte &b) +{ + return SSAUByte(a) * b; +} +/* +SSAUByte operator/(unsigned char a, const SSAUByte &b) +{ + return SSAUByte(a) / b; +} +*/ +SSAUByte operator+(const SSAUByte &a, unsigned char b) +{ + return a + SSAUByte(b); +} + +SSAUByte operator-(const SSAUByte &a, unsigned char b) +{ + return a - SSAUByte(b); +} + +SSAUByte operator*(const SSAUByte &a, unsigned char b) +{ + return a * SSAUByte(b); +} +/* +SSAUByte operator/(const SSAUByte &a, unsigned char b) +{ + return a / SSAUByte(b); +} +*/ +SSAUByte operator<<(const SSAUByte &a, unsigned char bits) +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateShl(a.v, bits)); +} + +SSAUByte operator>>(const SSAUByte &a, unsigned char bits) +{ + return SSAUByte::from_llvm(SSAScope::builder().CreateLShr(a.v, bits)); +} diff --git a/tools/drawergen/ssa/ssa_ubyte.h b/tools/drawergen/ssa/ssa_ubyte.h new file mode 100644 index 000000000..ef1390162 --- /dev/null +++ b/tools/drawergen/ssa/ssa_ubyte.h @@ -0,0 +1,60 @@ +/* +** SSA uint8 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAInt; + +class SSAUByte +{ +public: + SSAUByte(); + explicit SSAUByte(unsigned char constant); + explicit SSAUByte(llvm::Value *v); + static SSAUByte from_llvm(llvm::Value *v) { return SSAUByte(v); } + static llvm::Type *llvm_type(); + + SSAInt zext_int(); + + llvm::Value *v; +}; + +SSAUByte operator+(const SSAUByte &a, const SSAUByte &b); +SSAUByte operator-(const SSAUByte &a, const SSAUByte &b); +SSAUByte operator*(const SSAUByte &a, const SSAUByte &b); +//SSAUByte operator/(const SSAUByte &a, const SSAUByte &b); + +SSAUByte operator+(unsigned char a, const SSAUByte &b); +SSAUByte operator-(unsigned char a, const SSAUByte &b); +SSAUByte operator*(unsigned char a, const SSAUByte &b); +//SSAUByte operator/(unsigned char a, const SSAUByte &b); + +SSAUByte operator+(const SSAUByte &a, unsigned char b); +SSAUByte operator-(const SSAUByte &a, unsigned char b); +SSAUByte operator*(const SSAUByte &a, unsigned char b); +//SSAUByte operator/(const SSAUByte &a, unsigned char b); + +SSAUByte operator<<(const SSAUByte &a, unsigned char bits); +SSAUByte operator>>(const SSAUByte &a, unsigned char bits); diff --git a/tools/drawergen/ssa/ssa_ubyte_ptr.cpp b/tools/drawergen/ssa/ssa_ubyte_ptr.cpp new file mode 100644 index 000000000..bde0b5b64 --- /dev/null +++ b/tools/drawergen/ssa/ssa_ubyte_ptr.cpp @@ -0,0 +1,173 @@ +/* +** SSA uint8 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_ubyte_ptr.h" +#include "ssa_scope.h" +#include "ssa_bool.h" + +SSAUBytePtr::SSAUBytePtr() +: v(0) +{ +} + +SSAUBytePtr::SSAUBytePtr(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAUBytePtr::llvm_type() +{ + return llvm::Type::getInt8PtrTy(SSAScope::context()); +} + +SSAUBytePtr SSAUBytePtr::operator[](SSAInt index) const +{ + return SSAUBytePtr::from_llvm(SSAScope::builder().CreateGEP(v, index.v, SSAScope::hint())); +} + +SSAUByte SSAUBytePtr::load(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateLoad(v, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAUByte::from_llvm(loadInst); +} + +SSAVec4i SSAUBytePtr::load_vec4ub(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateLoad(SSAScope::builder().CreateBitCast(v, llvm::Type::getInt32PtrTy(SSAScope::context()), SSAScope::hint()), false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + SSAInt i32 = SSAInt::from_llvm(loadInst); + return SSAVec4i::unpack(i32); +} + +SSAVec16ub SSAUBytePtr::load_vec16ub(bool constantScopeDomain) const +{ + llvm::PointerType *m16xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m16xint8typeptr, SSAScope::hint()), 16, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec16ub::from_llvm(loadInst); +} + +SSAVec16ub SSAUBytePtr::load_unaligned_vec16ub(bool constantScopeDomain) const +{ + llvm::PointerType *m16xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16)->getPointerTo(); + auto loadInst = SSAScope::builder().CreateAlignedLoad(SSAScope::builder().CreateBitCast(v, m16xint8typeptr, SSAScope::hint()), 1, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec16ub::from_llvm(loadInst); +} + +void SSAUBytePtr::store(const SSAUByte &new_value) +{ + auto inst = SSAScope::builder().CreateStore(new_value.v, v, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAUBytePtr::store_vec4ub(const SSAVec4i &new_value) +{ + // Store using saturate: + SSAVec8s v8s(new_value, new_value); + SSAVec16ub v16ub(v8s, v8s); + + llvm::Type *m16xint8type = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16); + llvm::PointerType *m4xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 4)->getPointerTo(); + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 3))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + llvm::Value *val_vector = SSAScope::builder().CreateShuffleVector(v16ub.v, llvm::UndefValue::get(m16xint8type), mask, SSAScope::hint()); + llvm::StoreInst *inst = SSAScope::builder().CreateStore(val_vector, SSAScope::builder().CreateBitCast(v, m4xint8typeptr, SSAScope::hint()), false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAUBytePtr::store_masked_vec4ub(const SSAVec4i &new_value, SSABool mask[4]) +{ + // Store using saturate: + SSAVec8s v8s(new_value, new_value); + SSAVec16ub v16ub(v8s, v8s); + + // Create mask vector + std::vector maskconstants; + maskconstants.resize(4, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(1, 0, false))); + llvm::Value *maskValue = llvm::ConstantVector::get(maskconstants); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + for (int i = 0; i < 4; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i].v, SSAInt(i).v, SSAScope::hint()); +#else + for (int i = 0; i < 4; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i].v, (uint64_t)i, SSAScope::hint()); +#endif + + llvm::Type *m16xint8type = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16); + llvm::PointerType *m4xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 4)->getPointerTo(); + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 3))); + llvm::Value *shufflemask = llvm::ConstantVector::get(constants); + llvm::Value *val_vector = SSAScope::builder().CreateShuffleVector(v16ub.v, llvm::UndefValue::get(m16xint8type), shufflemask, SSAScope::hint()); + llvm::CallInst *inst = SSAScope::builder().CreateMaskedStore(val_vector, SSAScope::builder().CreateBitCast(v, m4xint8typeptr, SSAScope::hint()), 1, maskValue); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAUBytePtr::store_vec16ub(const SSAVec16ub &new_value) +{ + llvm::PointerType *m16xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16)->getPointerTo(); + llvm::StoreInst *inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m16xint8typeptr, SSAScope::hint()), 16); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); + + // The following generates _mm_stream_si128, maybe! + // llvm::MDNode *node = llvm::MDNode::get(SSAScope::context(), SSAScope::builder().getInt32(1)); + // inst->setMetadata(SSAScope::module()->getMDKindID("nontemporal"), node); +} + +void SSAUBytePtr::store_unaligned_vec16ub(const SSAVec16ub &new_value) +{ + llvm::PointerType *m16xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16)->getPointerTo(); + llvm::StoreInst *inst = SSAScope::builder().CreateAlignedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m16xint8typeptr, SSAScope::hint()), 4); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAUBytePtr::store_masked_vec16ub(const SSAVec16ub &new_value, SSABool mask[4]) +{ + std::vector constants; + constants.resize(16, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(1, 0, false))); + llvm::Value *maskValue = llvm::ConstantVector::get(constants); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + for (int i = 0; i < 16; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i / 4].v, SSAInt(i).v, SSAScope::hint()); +#else + for (int i = 0; i < 16; i++) + maskValue = SSAScope::builder().CreateInsertElement(maskValue, mask[i / 4].v, (uint64_t)i, SSAScope::hint()); +#endif + + llvm::PointerType *m16xint8typeptr = llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16)->getPointerTo(); + llvm::CallInst *inst = SSAScope::builder().CreateMaskedStore(new_value.v, SSAScope::builder().CreateBitCast(v, m16xint8typeptr, SSAScope::hint()), 1, maskValue); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} diff --git a/tools/drawergen/ssa/ssa_ubyte_ptr.h b/tools/drawergen/ssa/ssa_ubyte_ptr.h new file mode 100644 index 000000000..ba4fb5397 --- /dev/null +++ b/tools/drawergen/ssa/ssa_ubyte_ptr.h @@ -0,0 +1,57 @@ +/* +** SSA uint8 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_ubyte.h" +#include "ssa_int.h" +#include "ssa_vec4i.h" +#include "ssa_vec8s.h" +#include "ssa_vec16ub.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSABool; + +class SSAUBytePtr +{ +public: + SSAUBytePtr(); + explicit SSAUBytePtr(llvm::Value *v); + static SSAUBytePtr from_llvm(llvm::Value *v) { return SSAUBytePtr(v); } + static llvm::Type *llvm_type(); + SSAUBytePtr operator[](SSAInt index) const; + SSAUBytePtr operator[](int index) const { return (*this)[SSAInt(index)]; } + SSAUByte load(bool constantScopeDomain) const; + SSAVec4i load_vec4ub(bool constantScopeDomain) const; + SSAVec16ub load_vec16ub(bool constantScopeDomain) const; + SSAVec16ub load_unaligned_vec16ub(bool constantScopeDomain) const; + void store(const SSAUByte &new_value); + void store_vec4ub(const SSAVec4i &new_value); + void store_masked_vec4ub(const SSAVec4i &new_value, SSABool mask[4]); + void store_vec16ub(const SSAVec16ub &new_value); + void store_unaligned_vec16ub(const SSAVec16ub &new_value); + void store_masked_vec16ub(const SSAVec16ub &new_value, SSABool mask[4]); + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_value.cpp b/tools/drawergen/ssa/ssa_value.cpp new file mode 100644 index 000000000..881b85ad3 --- /dev/null +++ b/tools/drawergen/ssa/ssa_value.cpp @@ -0,0 +1,81 @@ +/* +** SSA value +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_value.h" +#include "ssa_int.h" +#include "ssa_scope.h" + +SSAValue SSAValue::load(bool constantScopeDomain) +{ + auto loadInst = SSAScope::builder().CreateLoad(v, false); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAValue::from_llvm(loadInst); +} + +void SSAValue::store(llvm::Value *value) +{ + auto inst = SSAScope::builder().CreateStore(value, v, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +SSAIndexLookup SSAValue::operator[](int index) +{ + SSAIndexLookup result; + result.v = v; + result.indexes.push_back(SSAInt(index).v); + return result; +} + +SSAIndexLookup SSAValue::operator[](SSAInt index) +{ + SSAIndexLookup result; + result.v = v; + result.indexes.push_back(index.v); + return result; +} + +///////////////////////////////////////////////////////////////////////////// + +SSAIndexLookup::operator SSAValue() +{ + return SSAValue::from_llvm(SSAScope::builder().CreateGEP(v, indexes)); +} + +SSAIndexLookup SSAIndexLookup::operator[](int index) +{ + SSAIndexLookup result; + result.v = v; + result.indexes = indexes; + result.indexes.push_back(SSAInt(index).v); + return result; +} + +SSAIndexLookup SSAIndexLookup::operator[](SSAInt index) +{ + SSAIndexLookup result; + result.v = v; + result.indexes = indexes; + result.indexes.push_back(index.v); + return result; +} diff --git a/tools/drawergen/ssa/ssa_value.h b/tools/drawergen/ssa/ssa_value.h new file mode 100644 index 000000000..1df94b267 --- /dev/null +++ b/tools/drawergen/ssa/ssa_value.h @@ -0,0 +1,74 @@ +/* +** SSA value +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include + +namespace llvm { class Value; } + +class SSAInt; +class SSAIndexLookup; + +class SSAValue +{ +public: + SSAValue() : v(0) { } + + static SSAValue from_llvm(llvm::Value *v) { SSAValue val; val.v = v; return val; } + + SSAValue load(bool constantScopeDomain); + void store(llvm::Value *v); + + template + operator Type() + { + return Type::from_llvm(v); + } + + SSAIndexLookup operator[](int index); + SSAIndexLookup operator[](SSAInt index); + + llvm::Value *v; +}; + +class SSAIndexLookup +{ +public: + SSAIndexLookup() : v(0) { } + + llvm::Value *v; + std::vector indexes; + + SSAValue load(bool constantScopeDomain) { SSAValue value = *this; return value.load(constantScopeDomain); } + void store(llvm::Value *v) { SSAValue value = *this; return value.store(v); } + + template + operator Type() + { + return Type::from_llvm(v); + } + + operator SSAValue(); + SSAIndexLookup operator[](int index); + SSAIndexLookup operator[](SSAInt index); +}; diff --git a/tools/drawergen/ssa/ssa_vec16ub.cpp b/tools/drawergen/ssa/ssa_vec16ub.cpp new file mode 100644 index 000000000..0fceab8e8 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec16ub.cpp @@ -0,0 +1,176 @@ +/* +** SSA vec16 uint8 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec16ub.h" +#include "ssa_vec8s.h" +#include "ssa_vec4i.h" +#include "ssa_scope.h" + +SSAVec16ub::SSAVec16ub() +: v(0) +{ +} + +SSAVec16ub::SSAVec16ub(unsigned char constant) +: v(0) +{ + std::vector constants; + constants.resize(16, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant, false))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec16ub::SSAVec16ub( + unsigned char constant0, unsigned char constant1, unsigned char constant2, unsigned char constant3, unsigned char constant4, unsigned char constant5, unsigned char constant6, unsigned char constant7, + unsigned char constant8, unsigned char constant9, unsigned char constant10, unsigned char constant11, unsigned char constant12, unsigned char constant13, unsigned char constant14, unsigned char constant15) +: v(0) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant0, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant1, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant2, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant3, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant4, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant5, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant6, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant7, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant8, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant9, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant10, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant11, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant12, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant13, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant14, false))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(8, constant15, false))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec16ub::SSAVec16ub(llvm::Value *v) +: v(v) +{ +} + +SSAVec16ub::SSAVec16ub(SSAVec8s s0, SSAVec8s s1) +: v(0) +{ + llvm::Value *values[2] = { s0.v, s1.v }; + v = SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_packuswb_128), values, SSAScope::hint()); +} + +llvm::Type *SSAVec16ub::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getInt8Ty(SSAScope::context()), 16); +} + +SSAVec16ub SSAVec16ub::bitcast(SSAVec4i i32) +{ + return SSAVec16ub::from_llvm(SSAScope::builder().CreateBitCast(i32.v, llvm_type(), SSAScope::hint())); +} + +SSAVec16ub SSAVec16ub::shuffle(const SSAVec16ub &i0, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7, int index8, int index9, int index10, int index11, int index12, int index13, int index14, int index15) +{ + return shuffle(i0, from_llvm(llvm::UndefValue::get(llvm_type())), index0, index1, index2, index3, index4, index5, index6, index7, index8, index9, index10, index11, index12, index13, index14, index15); +} + +SSAVec16ub SSAVec16ub::shuffle(const SSAVec16ub &i0, const SSAVec16ub &i1, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7, int index8, int index9, int index10, int index11, int index12, int index13, int index14, int index15) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index3))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index4))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index5))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index6))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index7))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index8))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index9))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index10))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index11))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index12))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index13))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index14))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index15))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + return SSAVec16ub::from_llvm(SSAScope::builder().CreateShuffleVector(i0.v, i1.v, mask, SSAScope::hint())); +} + +SSAVec16ub operator+(const SSAVec16ub &a, const SSAVec16ub &b) +{ + return SSAVec16ub::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAVec16ub operator-(const SSAVec16ub &a, const SSAVec16ub &b) +{ + return SSAVec16ub::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAVec16ub operator*(const SSAVec16ub &a, const SSAVec16ub &b) +{ + return SSAVec16ub::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} +/* +SSAVec16ub operator/(const SSAVec16ub &a, const SSAVec16ub &b) +{ + return SSAScope::builder().CreateDiv(a.v, b.v, SSAScope::hint()); +} +*/ +SSAVec16ub operator+(unsigned char a, const SSAVec16ub &b) +{ + return SSAVec16ub(a) + b; +} + +SSAVec16ub operator-(unsigned char a, const SSAVec16ub &b) +{ + return SSAVec16ub(a) - b; +} + +SSAVec16ub operator*(unsigned char a, const SSAVec16ub &b) +{ + return SSAVec16ub(a) * b; +} +/* +SSAVec16ub operator/(unsigned char a, const SSAVec16ub &b) +{ + return SSAVec16ub(a) / b; +} +*/ +SSAVec16ub operator+(const SSAVec16ub &a, unsigned char b) +{ + return a + SSAVec16ub(b); +} + +SSAVec16ub operator-(const SSAVec16ub &a, unsigned char b) +{ + return a - SSAVec16ub(b); +} + +SSAVec16ub operator*(const SSAVec16ub &a, unsigned char b) +{ + return a * SSAVec16ub(b); +} +/* +SSAVec16ub operator/(const SSAVec16ub &a, unsigned char b) +{ + return a / SSAVec16ub(b); +} +*/ \ No newline at end of file diff --git a/tools/drawergen/ssa/ssa_vec16ub.h b/tools/drawergen/ssa/ssa_vec16ub.h new file mode 100644 index 000000000..42f4ef3ee --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec16ub.h @@ -0,0 +1,63 @@ +/* +** SSA vec16 uint8 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec8s; +class SSAVec4i; + +class SSAVec16ub +{ +public: + SSAVec16ub(); + explicit SSAVec16ub(unsigned char constant); + explicit SSAVec16ub( + unsigned char constant0, unsigned char constant1, unsigned char constant2, unsigned char constant3, unsigned char constant4, unsigned char constant5, unsigned char constant6, unsigned char constant7, + unsigned char constant8, unsigned char constant9, unsigned char constant10, unsigned char constant11, unsigned char constant12, unsigned char constant13, unsigned char constant14, unsigned char constant15); + explicit SSAVec16ub(llvm::Value *v); + SSAVec16ub(SSAVec8s s0, SSAVec8s s1); + static SSAVec16ub from_llvm(llvm::Value *v) { return SSAVec16ub(v); } + static llvm::Type *llvm_type(); + static SSAVec16ub bitcast(SSAVec4i i32); + static SSAVec16ub shuffle(const SSAVec16ub &i0, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7, int index8, int index9, int index10, int index11, int index12, int index13, int index14, int index15); + static SSAVec16ub shuffle(const SSAVec16ub &i0, const SSAVec16ub &i1, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7, int index8, int index9, int index10, int index11, int index12, int index13, int index14, int index15); + + llvm::Value *v; +}; + +SSAVec16ub operator+(const SSAVec16ub &a, const SSAVec16ub &b); +SSAVec16ub operator-(const SSAVec16ub &a, const SSAVec16ub &b); +SSAVec16ub operator*(const SSAVec16ub &a, const SSAVec16ub &b); +SSAVec16ub operator/(const SSAVec16ub &a, const SSAVec16ub &b); + +SSAVec16ub operator+(unsigned char a, const SSAVec16ub &b); +SSAVec16ub operator-(unsigned char a, const SSAVec16ub &b); +SSAVec16ub operator*(unsigned char a, const SSAVec16ub &b); +SSAVec16ub operator/(unsigned char a, const SSAVec16ub &b); + +SSAVec16ub operator+(const SSAVec16ub &a, unsigned char b); +SSAVec16ub operator-(const SSAVec16ub &a, unsigned char b); +SSAVec16ub operator*(const SSAVec16ub &a, unsigned char b); +SSAVec16ub operator/(const SSAVec16ub &a, unsigned char b); diff --git a/tools/drawergen/ssa/ssa_vec4f.cpp b/tools/drawergen/ssa/ssa_vec4f.cpp new file mode 100644 index 000000000..5c40f7494 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4f.cpp @@ -0,0 +1,270 @@ +/* +** SSA vec4 float +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec4f.h" +#include "ssa_vec4i.h" +#include "ssa_float.h" +#include "ssa_int.h" +#include "ssa_scope.h" + +SSAVec4f::SSAVec4f() +: v(0) +{ +} + +SSAVec4f::SSAVec4f(float constant) +: v(0) +{ + std::vector constants; + constants.resize(4, llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec4f::SSAVec4f(float constant0, float constant1, float constant2, float constant3) +: v(0) +{ + std::vector constants; + constants.push_back(llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant0))); + constants.push_back(llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant1))); + constants.push_back(llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant2))); + constants.push_back(llvm::ConstantFP::get(SSAScope::context(), llvm::APFloat(constant3))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec4f::SSAVec4f(SSAFloat f) +: v(0) +{ + llvm::Type *m1xfloattype = llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 1); + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + v = SSAScope::builder().CreateShuffleVector(SSAScope::builder().CreateBitCast(f.v, m1xfloattype, SSAScope::hint()), llvm::UndefValue::get(m1xfloattype), mask, SSAScope::hint()); +} + +SSAVec4f::SSAVec4f(SSAFloat f0, SSAFloat f1, SSAFloat f2, SSAFloat f3) +: v(0) +{ + v = SSAScope::builder().CreateInsertElement(llvm::UndefValue::get(llvm_type()), f0.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)0))); + v = SSAScope::builder().CreateInsertElement(v, f1.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)1))); + v = SSAScope::builder().CreateInsertElement(v, f2.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)2))); + v = SSAScope::builder().CreateInsertElement(v, f3.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)3))); +} + +SSAVec4f::SSAVec4f(llvm::Value *v) +: v(v) +{ +} + +SSAVec4f::SSAVec4f(SSAVec4i i32) +: v(0) +{ + //llvm::VectorType *m128type = llvm::VectorType::get(llvm::Type::getFloatTy(*context), 4); + //return builder->CreateSIToFP(i32.v, m128type); + v = SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_cvtdq2ps), i32.v, SSAScope::hint()); +} + +llvm::Type *SSAVec4f::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4); +} + +SSAFloat SSAVec4f::operator[](SSAInt index) const +{ + return SSAFloat::from_llvm(SSAScope::builder().CreateExtractElement(v, index.v, SSAScope::hint())); +} + +SSAFloat SSAVec4f::operator[](int index) const +{ + return (*this)[SSAInt(index)]; +} + +SSAVec4f SSAVec4f::insert_element(SSAVec4f vec4f, SSAFloat value, int index) +{ + return from_llvm(SSAScope::builder().CreateInsertElement(vec4f.v, value.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)index)))); +} + +SSAVec4f SSAVec4f::bitcast(SSAVec4i i32) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateBitCast(i32.v, llvm_type(), SSAScope::hint())); +} + +SSAVec4f SSAVec4f::sqrt(SSAVec4f f) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::sqrt, params), f.v, SSAScope::hint())); + //return SSAVec4f::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse_sqrt_ps), f.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::rcp(SSAVec4f f) +{ + return SSAVec4f::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse_rcp_ps), f.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::sin(SSAVec4f val) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::sin, params), val.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::cos(SSAVec4f val) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::cos, params), val.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::pow(SSAVec4f val, SSAVec4f power) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + //params.push_back(SSAVec4f::llvm_type()); + std::vector args; + args.push_back(val.v); + args.push_back(power.v); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::pow, params), args, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::exp(SSAVec4f val) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::exp, params), val.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::log(SSAVec4f val) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::log, params), val.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::fma(SSAVec4f a, SSAVec4f b, SSAVec4f c) +{ + std::vector params; + params.push_back(SSAVec4f::llvm_type()); + //params.push_back(SSAVec4f::llvm_type()); + //params.push_back(SSAVec4f::llvm_type()); + std::vector args; + args.push_back(a.v); + args.push_back(b.v); + args.push_back(c.v); + return SSAFloat::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::fma, params), args, SSAScope::hint())); +} + +void SSAVec4f::transpose(SSAVec4f &row0, SSAVec4f &row1, SSAVec4f &row2, SSAVec4f &row3) +{ + SSAVec4f tmp0 = shuffle(row0, row1, 0x44);//_MM_SHUFFLE(1,0,1,0)); + SSAVec4f tmp2 = shuffle(row0, row1, 0xEE);//_MM_SHUFFLE(3,2,3,2)); + SSAVec4f tmp1 = shuffle(row2, row3, 0x44);//_MM_SHUFFLE(1,0,1,0)); + SSAVec4f tmp3 = shuffle(row2, row3, 0xEE);//_MM_SHUFFLE(3,2,3,2)); + row0 = shuffle(tmp0, tmp1, 0x88);//_MM_SHUFFLE(2,0,2,0)); + row1 = shuffle(tmp0, tmp1, 0xDD);//_MM_SHUFFLE(3,1,3,1)); + row2 = shuffle(tmp2, tmp3, 0x88);//_MM_SHUFFLE(2,0,2,0)); + row3 = shuffle(tmp2, tmp3, 0xDD);//_MM_SHUFFLE(3,1,3,1)); +} + +SSAVec4f SSAVec4f::shuffle(const SSAVec4f &f0, int index0, int index1, int index2, int index3) +{ + return shuffle(f0, from_llvm(llvm::UndefValue::get(llvm_type())), index0, index1, index2, index3); +} + +SSAVec4f SSAVec4f::shuffle(const SSAVec4f &f0, const SSAVec4f &f1, int index0, int index1, int index2, int index3) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index3))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + return SSAVec4f::from_llvm(SSAScope::builder().CreateShuffleVector(f0.v, f1.v, mask, SSAScope::hint())); +} + +SSAVec4f SSAVec4f::shuffle(const SSAVec4f &f0, const SSAVec4f &f1, int mask) +{ + return shuffle(f0, f1, mask & 3, (mask >> 2) & 3, ((mask >> 4) & 3) + 4, ((mask >> 6) & 3) + 4); +} + +SSAVec4f operator+(const SSAVec4f &a, const SSAVec4f &b) +{ + return SSAVec4f::from_llvm(SSAScope::builder().CreateFAdd(a.v, b.v, SSAScope::hint())); +} + +SSAVec4f operator-(const SSAVec4f &a, const SSAVec4f &b) +{ + return SSAVec4f::from_llvm(SSAScope::builder().CreateFSub(a.v, b.v, SSAScope::hint())); +} + +SSAVec4f operator*(const SSAVec4f &a, const SSAVec4f &b) +{ + return SSAVec4f::from_llvm(SSAScope::builder().CreateFMul(a.v, b.v, SSAScope::hint())); +} + +SSAVec4f operator/(const SSAVec4f &a, const SSAVec4f &b) +{ + return SSAVec4f::from_llvm(SSAScope::builder().CreateFDiv(a.v, b.v, SSAScope::hint())); +} + +SSAVec4f operator+(float a, const SSAVec4f &b) +{ + return SSAVec4f(a) + b; +} + +SSAVec4f operator-(float a, const SSAVec4f &b) +{ + return SSAVec4f(a) - b; +} + +SSAVec4f operator*(float a, const SSAVec4f &b) +{ + return SSAVec4f(a) * b; +} + +SSAVec4f operator/(float a, const SSAVec4f &b) +{ + return SSAVec4f(a) / b; +} + +SSAVec4f operator+(const SSAVec4f &a, float b) +{ + return a + SSAVec4f(b); +} + +SSAVec4f operator-(const SSAVec4f &a, float b) +{ + return a - SSAVec4f(b); +} + +SSAVec4f operator*(const SSAVec4f &a, float b) +{ + return a * SSAVec4f(b); +} + +SSAVec4f operator/(const SSAVec4f &a, float b) +{ + return a / SSAVec4f(b); +} diff --git a/tools/drawergen/ssa/ssa_vec4f.h b/tools/drawergen/ssa/ssa_vec4f.h new file mode 100644 index 000000000..d8a2c5d01 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4f.h @@ -0,0 +1,79 @@ +/* +** SSA vec4 float +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4i; +class SSAFloat; +class SSAInt; + +class SSAVec4f +{ +public: + SSAVec4f(); + explicit SSAVec4f(float constant); + explicit SSAVec4f(float constant0, float constant1, float constant2, float constant3); + SSAVec4f(SSAFloat f); + SSAVec4f(SSAFloat f0, SSAFloat f1, SSAFloat f2, SSAFloat f3); + explicit SSAVec4f(llvm::Value *v); + SSAVec4f(SSAVec4i i32); + SSAFloat operator[](SSAInt index) const; + SSAFloat operator[](int index) const; + static SSAVec4f insert_element(SSAVec4f vec4f, SSAFloat value, int index); + static SSAVec4f bitcast(SSAVec4i i32); + static SSAVec4f sqrt(SSAVec4f f); + static SSAVec4f rcp(SSAVec4f f); + static SSAVec4f sin(SSAVec4f val); + static SSAVec4f cos(SSAVec4f val); + static SSAVec4f pow(SSAVec4f val, SSAVec4f power); + static SSAVec4f exp(SSAVec4f val); + static SSAVec4f log(SSAVec4f val); + static SSAVec4f fma(SSAVec4f a, SSAVec4f b, SSAVec4f c); + static void transpose(SSAVec4f &row0, SSAVec4f &row1, SSAVec4f &row2, SSAVec4f &row3); + static SSAVec4f shuffle(const SSAVec4f &f0, int index0, int index1, int index2, int index3); + static SSAVec4f shuffle(const SSAVec4f &f0, const SSAVec4f &f1, int index0, int index1, int index2, int index3); + static SSAVec4f from_llvm(llvm::Value *v) { return SSAVec4f(v); } + static llvm::Type *llvm_type(); + + llvm::Value *v; + +private: + static SSAVec4f shuffle(const SSAVec4f &f0, const SSAVec4f &f1, int mask); +}; + +SSAVec4f operator+(const SSAVec4f &a, const SSAVec4f &b); +SSAVec4f operator-(const SSAVec4f &a, const SSAVec4f &b); +SSAVec4f operator*(const SSAVec4f &a, const SSAVec4f &b); +SSAVec4f operator/(const SSAVec4f &a, const SSAVec4f &b); + +SSAVec4f operator+(float a, const SSAVec4f &b); +SSAVec4f operator-(float a, const SSAVec4f &b); +SSAVec4f operator*(float a, const SSAVec4f &b); +SSAVec4f operator/(float a, const SSAVec4f &b); + +SSAVec4f operator+(const SSAVec4f &a, float b); +SSAVec4f operator-(const SSAVec4f &a, float b); +SSAVec4f operator*(const SSAVec4f &a, float b); +SSAVec4f operator/(const SSAVec4f &a, float b); diff --git a/tools/drawergen/ssa/ssa_vec4f_ptr.cpp b/tools/drawergen/ssa/ssa_vec4f_ptr.cpp new file mode 100644 index 000000000..866331f84 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4f_ptr.cpp @@ -0,0 +1,73 @@ +/* +** SSA vec4 float pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec4f_ptr.h" +#include "ssa_scope.h" + +SSAVec4fPtr::SSAVec4fPtr() +: v(0) +{ +} + +SSAVec4fPtr::SSAVec4fPtr(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAVec4fPtr::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getFloatTy(SSAScope::context()), 4)->getPointerTo(); +} + +SSAVec4fPtr SSAVec4fPtr::operator[](SSAInt index) const +{ + return SSAVec4fPtr::from_llvm(SSAScope::builder().CreateGEP(v, index.v, SSAScope::hint())); +} + +SSAVec4f SSAVec4fPtr::load(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateAlignedLoad(v, 16, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4f::from_llvm(loadInst); +} + +SSAVec4f SSAVec4fPtr::load_unaligned(bool constantScopeDomain) const +{ + auto loadInst = SSAScope::builder().CreateAlignedLoad(v, 1, false, SSAScope::hint()); + if (constantScopeDomain) + loadInst->setMetadata(llvm::LLVMContext::MD_alias_scope, SSAScope::constant_scope_list()); + return SSAVec4f::from_llvm(loadInst); +} + +void SSAVec4fPtr::store(const SSAVec4f &new_value) +{ + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, v, 16, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} + +void SSAVec4fPtr::store_unaligned(const SSAVec4f &new_value) +{ + auto inst = SSAScope::builder().CreateAlignedStore(new_value.v, v, 4, false); + inst->setMetadata(llvm::LLVMContext::MD_noalias, SSAScope::constant_scope_list()); +} diff --git a/tools/drawergen/ssa/ssa_vec4f_ptr.h b/tools/drawergen/ssa/ssa_vec4f_ptr.h new file mode 100644 index 000000000..46f31ef6d --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4f_ptr.h @@ -0,0 +1,45 @@ +/* +** SSA vec4 float pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_int.h" +#include "ssa_vec4f.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4fPtr +{ +public: + SSAVec4fPtr(); + explicit SSAVec4fPtr(llvm::Value *v); + static SSAVec4fPtr from_llvm(llvm::Value *v) { return SSAVec4fPtr(v); } + static llvm::Type *llvm_type(); + SSAVec4fPtr operator[](SSAInt index) const; + SSAVec4f load(bool constantScopeDomain) const; + SSAVec4f load_unaligned(bool constantScopeDomain) const; + void store(const SSAVec4f &new_value); + void store_unaligned(const SSAVec4f &new_value); + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_vec4i.cpp b/tools/drawergen/ssa/ssa_vec4i.cpp new file mode 100644 index 000000000..344b33e1e --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4i.cpp @@ -0,0 +1,276 @@ +/* +** SSA vec4 int32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec4i.h" +#include "ssa_vec4f.h" +#include "ssa_vec8s.h" +#include "ssa_vec16ub.h" +#include "ssa_int.h" +#include "ssa_scope.h" + +SSAVec4i::SSAVec4i() +: v(0) +{ +} + +SSAVec4i::SSAVec4i(int constant) +: v(0) +{ + std::vector constants; + constants.resize(4, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant, true))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec4i::SSAVec4i(int constant0, int constant1, int constant2, int constant3) +: v(0) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant0, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant1, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant2, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, constant3, true))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec4i::SSAVec4i(llvm::Value *v) +: v(v) +{ +} + +SSAVec4i::SSAVec4i(SSAInt i) +: v(0) +{ + llvm::Type *m1xi32type = llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 1); + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + v = SSAScope::builder().CreateShuffleVector(SSAScope::builder().CreateBitCast(i.v, m1xi32type, SSAScope::hint()), llvm::UndefValue::get(m1xi32type), mask, SSAScope::hint()); +} + +SSAVec4i::SSAVec4i(SSAInt i0, SSAInt i1, SSAInt i2, SSAInt i3) +: v(0) +{ + std::vector constants; + constants.resize(4, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, 0, true))); + v = llvm::ConstantVector::get(constants); +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + v = SSAScope::builder().CreateInsertElement(v, i0.v, SSAInt(0).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i1.v, SSAInt(1).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i2.v, SSAInt(2).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i3.v, SSAInt(3).v, SSAScope::hint()); +#else + v = SSAScope::builder().CreateInsertElement(v, i0.v, (uint64_t)0, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i1.v, (uint64_t)1, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i2.v, (uint64_t)2, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, i3.v, (uint64_t)3, SSAScope::hint()); +#endif +} + +SSAVec4i::SSAVec4i(SSAVec4f f32) +: v(0) +{ + v = SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_cvttps2dq), f32.v, SSAScope::hint()); +} + +SSAInt SSAVec4i::operator[](SSAInt index) const +{ + return SSAInt::from_llvm(SSAScope::builder().CreateExtractElement(v, index.v, SSAScope::hint())); +} + +SSAInt SSAVec4i::operator[](int index) const +{ + return (*this)[SSAInt(index)]; +} + +SSAVec4i SSAVec4i::insert(SSAInt index, SSAInt value) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateInsertElement(v, value.v, index.v, SSAScope::hint())); +} + +SSAVec4i SSAVec4i::insert(int index, SSAInt value) +{ +#if LLVM_VERSION_MAJOR < 3 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 9) + return SSAVec4i::from_llvm(SSAScope::builder().CreateInsertElement(v, value.v, SSAInt(index).v, SSAScope::hint())); +#else + return SSAVec4i::from_llvm(SSAScope::builder().CreateInsertElement(v, value.v, index, SSAScope::hint())); +#endif +} + +SSAVec4i SSAVec4i::insert(int index, int value) +{ + return insert(index, SSAInt(value)); +} + +llvm::Type *SSAVec4i::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4); +} + +SSAVec4i SSAVec4i::unpack(SSAInt i32) +{ + // _mm_cvtsi32_si128 as implemented by clang: + llvm::Value *v = SSAScope::builder().CreateInsertElement(llvm::UndefValue::get(SSAVec4i::llvm_type()), i32.v, SSAInt(0).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, SSAInt(0).v, SSAInt(1).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, SSAInt(0).v, SSAInt(2).v, SSAScope::hint()); + v = SSAScope::builder().CreateInsertElement(v, SSAInt(0).v, SSAInt(3).v, SSAScope::hint()); + SSAVec4i v4i = SSAVec4i::from_llvm(v); + + SSAVec8s low = SSAVec8s::bitcast(SSAVec16ub::shuffle(SSAVec16ub::bitcast(v4i), SSAVec16ub((unsigned char)0), 0, 16 + 0, 1, 16 + 1, 2, 16 + 2, 3, 16 + 3, 4, 16 + 4, 5, 16 + 5, 6, 16 + 6, 7, 16 + 7)); // _mm_unpacklo_epi8 + return SSAVec4i::extendlo(low); // _mm_unpacklo_epi16 +} + +SSAVec4i SSAVec4i::bitcast(SSAVec4f f32) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateBitCast(f32.v, llvm_type(), SSAScope::hint())); +} + +SSAVec4i SSAVec4i::bitcast(SSAVec8s i16) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateBitCast(i16.v, llvm_type(), SSAScope::hint())); +} + +SSAVec4i SSAVec4i::shuffle(const SSAVec4i &i0, int index0, int index1, int index2, int index3) +{ + return shuffle(i0, from_llvm(llvm::UndefValue::get(llvm_type())), index0, index1, index2, index3); +} + +SSAVec4i SSAVec4i::shuffle(const SSAVec4i &i0, const SSAVec4i &i1, int index0, int index1, int index2, int index3) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index3))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + return SSAVec4i::from_llvm(SSAScope::builder().CreateShuffleVector(i0.v, i1.v, mask, SSAScope::hint())); +} + +void SSAVec4i::extend(SSAVec16ub a, SSAVec4i &out0, SSAVec4i &out1, SSAVec4i &out2, SSAVec4i &out3) +{ + SSAVec8s low = SSAVec8s::extendlo(a); + SSAVec8s high = SSAVec8s::extendhi(a); + out0 = extendlo(low); + out1 = extendhi(low); + out2 = extendlo(high); + out3 = extendhi(high); +} + +SSAVec4i SSAVec4i::extendhi(SSAVec8s i16) +{ + return SSAVec4i::bitcast(SSAVec8s::shuffle(i16, SSAVec8s((short)0), 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7)); // _mm_unpackhi_epi16 +} + +SSAVec4i SSAVec4i::extendlo(SSAVec8s i16) +{ + return SSAVec4i::bitcast(SSAVec8s::shuffle(i16, SSAVec8s((short)0), 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3)); // _mm_unpacklo_epi16 +} + +SSAVec4i SSAVec4i::combinehi(SSAVec8s a, SSAVec8s b) +{ + return SSAVec4i::bitcast(SSAVec8s::shuffle(a, b, 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7)); // _mm_unpackhi_epi16 +} + +SSAVec4i SSAVec4i::combinelo(SSAVec8s a, SSAVec8s b) +{ + return SSAVec4i::bitcast(SSAVec8s::shuffle(a, b, 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3)); // _mm_unpacklo_epi16 +} + +SSAVec4i SSAVec4i::sqrt(SSAVec4i f) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_sqrt_pd), f.v, SSAScope::hint())); +} + +SSAVec4i operator+(const SSAVec4i &a, const SSAVec4i &b) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAVec4i operator-(const SSAVec4i &a, const SSAVec4i &b) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAVec4i operator*(const SSAVec4i &a, const SSAVec4i &b) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} + +SSAVec4i operator/(const SSAVec4i &a, const SSAVec4i &b) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateSDiv(a.v, b.v, SSAScope::hint())); +} + +SSAVec4i operator+(int a, const SSAVec4i &b) +{ + return SSAVec4i(a) + b; +} + +SSAVec4i operator-(int a, const SSAVec4i &b) +{ + return SSAVec4i(a) - b; +} + +SSAVec4i operator*(int a, const SSAVec4i &b) +{ + return SSAVec4i(a) * b; +} + +SSAVec4i operator/(int a, const SSAVec4i &b) +{ + return SSAVec4i(a) / b; +} + +SSAVec4i operator+(const SSAVec4i &a, int b) +{ + return a + SSAVec4i(b); +} + +SSAVec4i operator-(const SSAVec4i &a, int b) +{ + return a - SSAVec4i(b); +} + +SSAVec4i operator*(const SSAVec4i &a, int b) +{ + return a * SSAVec4i(b); +} + +SSAVec4i operator/(const SSAVec4i &a, int b) +{ + return a / SSAVec4i(b); +} + +SSAVec4i operator<<(const SSAVec4i &a, int bits) +{ + //return SSAScope::builder().CreateShl(a.v, bits); + llvm::Value *values[2] = { a.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)bits)) }; + return SSAVec4i::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_pslli_d), values, SSAScope::hint())); +} + +SSAVec4i operator>>(const SSAVec4i &a, int bits) +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateLShr(a.v, bits, SSAScope::hint())); +} diff --git a/tools/drawergen/ssa/ssa_vec4i.h b/tools/drawergen/ssa/ssa_vec4i.h new file mode 100644 index 000000000..2035b5457 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4i.h @@ -0,0 +1,81 @@ +/* +** SSA vec4 int32 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4f; +class SSAVec8s; +class SSAVec16ub; +class SSAInt; + +class SSAVec4i +{ +public: + SSAVec4i(); + explicit SSAVec4i(int constant); + explicit SSAVec4i(int constant0, int constant1, int constant2, int constant3); + SSAVec4i(SSAInt i); + SSAVec4i(SSAInt i0, SSAInt i1, SSAInt i2, SSAInt i3); + explicit SSAVec4i(llvm::Value *v); + SSAVec4i(SSAVec4f f32); + SSAInt operator[](SSAInt index) const; + SSAInt operator[](int index) const; + SSAVec4i insert(SSAInt index, SSAInt value); + SSAVec4i insert(int index, SSAInt value); + SSAVec4i insert(int index, int value); + static SSAVec4i unpack(SSAInt value); + static SSAVec4i bitcast(SSAVec4f f32); + static SSAVec4i bitcast(SSAVec8s i16); + static SSAVec4i shuffle(const SSAVec4i &f0, int index0, int index1, int index2, int index3); + static SSAVec4i shuffle(const SSAVec4i &f0, const SSAVec4i &f1, int index0, int index1, int index2, int index3); + static SSAVec4i extendhi(SSAVec8s i16); + static SSAVec4i extendlo(SSAVec8s i16); + static void extend(SSAVec16ub a, SSAVec4i &out0, SSAVec4i &out1, SSAVec4i &out2, SSAVec4i &out3); + static SSAVec4i combinehi(SSAVec8s v0, SSAVec8s v1); + static SSAVec4i combinelo(SSAVec8s v0, SSAVec8s v1); + static SSAVec4i sqrt(SSAVec4i f); + static SSAVec4i from_llvm(llvm::Value *v) { return SSAVec4i(v); } + static llvm::Type *llvm_type(); + + llvm::Value *v; +}; + +SSAVec4i operator+(const SSAVec4i &a, const SSAVec4i &b); +SSAVec4i operator-(const SSAVec4i &a, const SSAVec4i &b); +SSAVec4i operator*(const SSAVec4i &a, const SSAVec4i &b); +SSAVec4i operator/(const SSAVec4i &a, const SSAVec4i &b); + +SSAVec4i operator+(int a, const SSAVec4i &b); +SSAVec4i operator-(int a, const SSAVec4i &b); +SSAVec4i operator*(int a, const SSAVec4i &b); +SSAVec4i operator/(int a, const SSAVec4i &b); + +SSAVec4i operator+(const SSAVec4i &a, int b); +SSAVec4i operator-(const SSAVec4i &a, int b); +SSAVec4i operator*(const SSAVec4i &a, int b); +SSAVec4i operator/(const SSAVec4i &a, int b); + +SSAVec4i operator<<(const SSAVec4i &a, int bits); +SSAVec4i operator>>(const SSAVec4i &a, int bits); diff --git a/tools/drawergen/ssa/ssa_vec4i_ptr.cpp b/tools/drawergen/ssa/ssa_vec4i_ptr.cpp new file mode 100644 index 000000000..9f1ad9684 --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4i_ptr.cpp @@ -0,0 +1,65 @@ +/* +** SSA vec4 int32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec4i_ptr.h" +#include "ssa_scope.h" + +SSAVec4iPtr::SSAVec4iPtr() +: v(0) +{ +} + +SSAVec4iPtr::SSAVec4iPtr(llvm::Value *v) +: v(v) +{ +} + +llvm::Type *SSAVec4iPtr::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getInt32Ty(SSAScope::context()), 4)->getPointerTo(); +} + +SSAVec4iPtr SSAVec4iPtr::operator[](SSAInt index) const +{ + return SSAVec4iPtr::from_llvm(SSAScope::builder().CreateGEP(v, index.v, SSAScope::hint())); +} + +SSAVec4i SSAVec4iPtr::load() const +{ + return SSAVec4i::from_llvm(SSAScope::builder().CreateLoad(v, false, SSAScope::hint())); +} + +SSAVec4i SSAVec4iPtr::load_unaligned() const +{ + return SSAVec4i::from_llvm(SSAScope::builder().Insert(new llvm::LoadInst(v, SSAScope::hint(), false, 4))); +} + +void SSAVec4iPtr::store(const SSAVec4i &new_value) +{ + SSAScope::builder().CreateStore(new_value.v, v, false); +} + +void SSAVec4iPtr::store_unaligned(const SSAVec4i &new_value) +{ + SSAScope::builder().CreateAlignedStore(new_value.v, v, 4, false); +} diff --git a/tools/drawergen/ssa/ssa_vec4i_ptr.h b/tools/drawergen/ssa/ssa_vec4i_ptr.h new file mode 100644 index 000000000..e4d8134bb --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec4i_ptr.h @@ -0,0 +1,46 @@ +/* +** SSA vec4 int32 pointer +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +#include "ssa_int.h" +#include "ssa_vec4i.h" + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4iPtr +{ +public: + SSAVec4iPtr(); + explicit SSAVec4iPtr(llvm::Value *v); + static SSAVec4iPtr from_llvm(llvm::Value *v) { return SSAVec4iPtr(v); } + static llvm::Type *llvm_type(); + SSAVec4iPtr operator[](SSAInt index) const; + SSAVec4iPtr operator[](int index) const { return (*this)[SSAInt(index)]; } + SSAVec4i load() const; + SSAVec4i load_unaligned() const; + void store(const SSAVec4i &new_value); + void store_unaligned(const SSAVec4i &new_value); + + llvm::Value *v; +}; diff --git a/tools/drawergen/ssa/ssa_vec8s.cpp b/tools/drawergen/ssa/ssa_vec8s.cpp new file mode 100644 index 000000000..0950a289e --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec8s.cpp @@ -0,0 +1,199 @@ +/* +** SSA vec8 int16 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#include "precomp.h" +#include "ssa_vec8s.h" +#include "ssa_vec4i.h" +#include "ssa_vec16ub.h" +#include "ssa_scope.h" + +SSAVec8s::SSAVec8s() +: v(0) +{ +} + +SSAVec8s::SSAVec8s(short constant) +: v(0) +{ + std::vector constants; + constants.resize(8, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant, true))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec8s::SSAVec8s(short constant0, short constant1, short constant2, short constant3, short constant4, short constant5, short constant6, short constant7) +: v(0) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant0, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant1, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant2, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant3, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant4, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant5, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant6, true))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(16, constant7, true))); + v = llvm::ConstantVector::get(constants); +} + +SSAVec8s::SSAVec8s(llvm::Value *v) +: v(v) +{ +} + +SSAVec8s::SSAVec8s(SSAVec4i i0, SSAVec4i i1) +: v(0) +{ + llvm::Value *values[2] = { i0.v, i1.v }; + v = SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_packssdw_128), values, SSAScope::hint()); +} + +llvm::Type *SSAVec8s::llvm_type() +{ + return llvm::VectorType::get(llvm::Type::getInt16Ty(SSAScope::context()), 8); +} + +SSAVec8s SSAVec8s::bitcast(SSAVec16ub i8) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateBitCast(i8.v, llvm_type(), SSAScope::hint())); +} + +SSAVec8s SSAVec8s::shuffle(const SSAVec8s &i0, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7) +{ + return shuffle(i0, from_llvm(llvm::UndefValue::get(llvm_type())), index0, index1, index2, index3, index4, index5, index6, index7); +} + +SSAVec8s SSAVec8s::shuffle(const SSAVec8s &i0, const SSAVec8s &i1, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7) +{ + std::vector constants; + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index0))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index1))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index2))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index3))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index4))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index5))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index6))); + constants.push_back(llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, index7))); + llvm::Value *mask = llvm::ConstantVector::get(constants); + return SSAVec8s::from_llvm(SSAScope::builder().CreateShuffleVector(i0.v, i1.v, mask, SSAScope::hint())); +} + +SSAVec8s SSAVec8s::extendhi(SSAVec16ub a) +{ + return SSAVec8s::bitcast(SSAVec16ub::shuffle(a, SSAVec16ub((unsigned char)0), 8, 16+8, 9, 16+9, 10, 16+10, 11, 16+11, 12, 16+12, 13, 16+13, 14, 16+14, 15, 16+15)); // _mm_unpackhi_epi8 +} + +SSAVec8s SSAVec8s::extendlo(SSAVec16ub a) +{ + return SSAVec8s::bitcast(SSAVec16ub::shuffle(a, SSAVec16ub((unsigned char)0), 0, 16+0, 1, 16+1, 2, 16+2, 3, 16+3, 4, 16+4, 5, 16+5, 6, 16+6, 7, 16+7)); // _mm_unpacklo_epi8 +} + +/* +SSAVec8s SSAVec8s::min_sse2(SSAVec8s a, SSAVec8s b) +{ + llvm::Value *values[2] = { a.v, b.v }; + return SSAVec8s::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_pmins_w), values, SSAScope::hint())); +} + +SSAVec8s SSAVec8s::max_sse2(SSAVec8s a, SSAVec8s b) +{ + llvm::Value *values[2] = { a.v, b.v }; + return SSAVec8s::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_pmaxs_w), values, SSAScope::hint())); +} +*/ + +SSAVec8s SSAVec8s::mulhi(SSAVec8s a, SSAVec8s b) +{ + llvm::Value *values[2] = { a.v, b.v }; + return SSAVec8s::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_pmulh_w), values, SSAScope::hint())); +} + +SSAVec8s operator+(const SSAVec8s &a, const SSAVec8s &b) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateAdd(a.v, b.v, SSAScope::hint())); +} + +SSAVec8s operator-(const SSAVec8s &a, const SSAVec8s &b) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateSub(a.v, b.v, SSAScope::hint())); +} + +SSAVec8s operator*(const SSAVec8s &a, const SSAVec8s &b) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateMul(a.v, b.v, SSAScope::hint())); +} + +SSAVec8s operator/(const SSAVec8s &a, const SSAVec8s &b) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateSDiv(a.v, b.v, SSAScope::hint())); +} + +SSAVec8s operator+(short a, const SSAVec8s &b) +{ + return SSAVec8s(a) + b; +} + +SSAVec8s operator-(short a, const SSAVec8s &b) +{ + return SSAVec8s(a) - b; +} + +SSAVec8s operator*(short a, const SSAVec8s &b) +{ + return SSAVec8s(a) * b; +} + +SSAVec8s operator/(short a, const SSAVec8s &b) +{ + return SSAVec8s(a) / b; +} + +SSAVec8s operator+(const SSAVec8s &a, short b) +{ + return a + SSAVec8s(b); +} + +SSAVec8s operator-(const SSAVec8s &a, short b) +{ + return a - SSAVec8s(b); +} + +SSAVec8s operator*(const SSAVec8s &a, short b) +{ + return a * SSAVec8s(b); +} + +SSAVec8s operator/(const SSAVec8s &a, short b) +{ + return a / SSAVec8s(b); +} + +SSAVec8s operator<<(const SSAVec8s &a, int bits) +{ + //return SSAScope::builder().CreateShl(a.v, bits); + llvm::Value *values[2] = { a.v, llvm::ConstantInt::get(SSAScope::context(), llvm::APInt(32, (uint64_t)bits)) }; + return SSAVec8s::from_llvm(SSAScope::builder().CreateCall(SSAScope::intrinsic(llvm::Intrinsic::x86_sse2_pslli_d), values, SSAScope::hint())); +} + +SSAVec8s operator>>(const SSAVec8s &a, int bits) +{ + return SSAVec8s::from_llvm(SSAScope::builder().CreateLShr(a.v, bits, SSAScope::hint())); +} diff --git a/tools/drawergen/ssa/ssa_vec8s.h b/tools/drawergen/ssa/ssa_vec8s.h new file mode 100644 index 000000000..be320804e --- /dev/null +++ b/tools/drawergen/ssa/ssa_vec8s.h @@ -0,0 +1,69 @@ +/* +** SSA vec8 int16 +** Copyright (c) 2016 Magnus Norddahl +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any damages +** arising from the use of this software. +** +** Permission is granted to anyone to use this software for any purpose, +** including commercial applications, and to alter it and redistribute it +** freely, subject to the following restrictions: +** +** 1. The origin of this software must not be misrepresented; you must not +** claim that you wrote the original software. If you use this software +** in a product, an acknowledgment in the product documentation would be +** appreciated but is not required. +** 2. Altered source versions must be plainly marked as such, and must not be +** misrepresented as being the original software. +** 3. This notice may not be removed or altered from any source distribution. +** +*/ + +#pragma once + +namespace llvm { class Value; } +namespace llvm { class Type; } + +class SSAVec4i; +class SSAVec16ub; + +class SSAVec8s +{ +public: + SSAVec8s(); + explicit SSAVec8s(short constant); + explicit SSAVec8s(short constant0, short constant1, short constant2, short constant3, short constant4, short constant5, short constant6, short constant7); + explicit SSAVec8s(llvm::Value *v); + SSAVec8s(SSAVec4i i0, SSAVec4i i1); + static SSAVec8s bitcast(SSAVec16ub i8); + static SSAVec8s shuffle(const SSAVec8s &i0, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7); + static SSAVec8s shuffle(const SSAVec8s &i0, const SSAVec8s &i1, int index0, int index1, int index2, int index3, int index4, int index5, int index6, int index7); + static SSAVec8s extendhi(SSAVec16ub a); + static SSAVec8s extendlo(SSAVec16ub a); + //static SSAVec8s min_sse2(SSAVec8s a, SSAVec8s b); + //static SSAVec8s max_sse2(SSAVec8s a, SSAVec8s b); + static SSAVec8s mulhi(SSAVec8s a, SSAVec8s b); + static SSAVec8s from_llvm(llvm::Value *v) { return SSAVec8s(v); } + static llvm::Type *llvm_type(); + + llvm::Value *v; +}; + +SSAVec8s operator+(const SSAVec8s &a, const SSAVec8s &b); +SSAVec8s operator-(const SSAVec8s &a, const SSAVec8s &b); +SSAVec8s operator*(const SSAVec8s &a, const SSAVec8s &b); +SSAVec8s operator/(const SSAVec8s &a, const SSAVec8s &b); + +SSAVec8s operator+(short a, const SSAVec8s &b); +SSAVec8s operator-(short a, const SSAVec8s &b); +SSAVec8s operator*(short a, const SSAVec8s &b); +SSAVec8s operator/(short a, const SSAVec8s &b); + +SSAVec8s operator+(const SSAVec8s &a, short b); +SSAVec8s operator-(const SSAVec8s &a, short b); +SSAVec8s operator*(const SSAVec8s &a, short b); +SSAVec8s operator/(const SSAVec8s &a, short b); + +SSAVec8s operator<<(const SSAVec8s &a, int bits); +SSAVec8s operator>>(const SSAVec8s &a, int bits); diff --git a/tools/drawergen/timestamp.h b/tools/drawergen/timestamp.h new file mode 100644 index 000000000..6dd11bcff --- /dev/null +++ b/tools/drawergen/timestamp.h @@ -0,0 +1,12 @@ + +#pragma once + +void AddSourceFileTimestamp(const char *timestamp); + +namespace +{ + struct TimestampSourceFile + { + TimestampSourceFile() { AddSourceFileTimestamp(__TIME__); } + } timestamp; +} diff --git a/tools/drawergen/trustinfo.rc b/tools/drawergen/trustinfo.rc new file mode 100644 index 000000000..366f9b2fd --- /dev/null +++ b/tools/drawergen/trustinfo.rc @@ -0,0 +1,6 @@ +// This resource script is for compiling with MinGW only. Visual C++ +// compilations use the manifest tool to insert the manifest instead. + +#include + +1 RT_MANIFEST "trustinfo.txt" diff --git a/tools/drawergen/trustinfo.txt b/tools/drawergen/trustinfo.txt new file mode 100644 index 000000000..5216df650 --- /dev/null +++ b/tools/drawergen/trustinfo.txt @@ -0,0 +1,16 @@ + + + + + Drawergen for the ZDoom source build process. + + + + + + + + diff --git a/wadsrc/CMakeLists.txt b/wadsrc/CMakeLists.txt index 4e661e7dd..5a85840e0 100644 --- a/wadsrc/CMakeLists.txt +++ b/wadsrc/CMakeLists.txt @@ -1,3 +1,3 @@ cmake_minimum_required( VERSION 2.8.7 ) -add_pk3(zdoom.pk3 ${CMAKE_CURRENT_SOURCE_DIR}/static) +add_pk3(qzdoom.pk3 ${CMAKE_CURRENT_SOURCE_DIR}/static) diff --git a/wadsrc/static/compatibility.txt b/wadsrc/static/compatibility.txt index c486b48ae..020d8477d 100644 --- a/wadsrc/static/compatibility.txt +++ b/wadsrc/static/compatibility.txt @@ -496,3 +496,17 @@ ABC4EB5A1535ECCD0061AD14F3547908 // Plutonia Experiment, map26 { setsectorspecial 156 0 } + +712BB4CFBD0753178CA0C6814BE4C288 // map12 BTSX_E1 - patch some rendering glitches that are problematic to detect +{ + setsectortag 545 32000 + setsectortag 1618 32000 + setlinespecial 2853 Sector_Set3DFloor 32000 4 0 0 0 + setsectortag 439 32001 + setsectortag 458 32001 + setlinespecial 2182 Sector_Set3DFloor 32001 4 0 0 0 + setsectortag 454 32002 + setsectortag 910 32002 + setlinespecial 2410 Sector_Set3DFloor 32002 4 1 0 0 +} + diff --git a/wadsrc/static/filter/doom.doom1/sprofs.txt b/wadsrc/static/filter/doom.doom1/sprofs.txt new file mode 100644 index 000000000..eab3dc4ef --- /dev/null +++ b/wadsrc/static/filter/doom.doom1/sprofs.txt @@ -0,0 +1,164 @@ +BAR1A0, 10, 32, iwad +BAR1B0, 10, 32, iwad +BEXPA0, 10, 32, iwad +BEXPB0, 10, 31, iwad +BEXPC0, 19, 36, iwad +BEXPD0, 27, 49, iwad +BEXPE0, 29, 52, iwad +BOS2I0, 20, 71, iwad +BOS2J0, 26, 62, iwad +BOS2K0, 26, 52, iwad +BOS2L0, 29, 33, iwad +BOS2M0, 30, 29, iwad +BOS2N0, 30, 29, iwad +BOS2O0, 30, 29, iwad +BOSSI0, 20, 72, iwad +BOSSJ0, 26, 63, iwad +BOSSK0, 26, 51, iwad +BOSSL0, 29, 33, iwad +BOSSM0, 30, 29, iwad +BOSSN0, 30, 29, iwad +BOSSO0, 30, 29, iwad +BRS1A0, 13, 8, iwad +BSPIJ0, 50, 54, iwad +BSPIK0, 50, 57, iwad +BSPIL0, 47, 52, iwad +BSPIM0, 45, 44, iwad +BSPIN0, 45, 42, iwad +BSPIO0, 45, 30, iwad +BSPIP0, 45, 28, iwad +CBRAA0, 15, 60, iwad +CEYEA0, 21, 59, iwad +CEYEB0, 21, 58, iwad +CEYEC0, 21, 59, iwad +COL1A0, 16, 51, iwad +COL2A0, 16, 39, iwad +COL3A0, 16, 52, iwad +COL4A0, 17, 39, iwad +COL5A0, 16, 44, iwad +COL5B0, 16, 45, iwad +COL6A0, 17, 47, iwad +COLUA0, 9, 45, iwad +CPOSH0, 20, 61, iwad +CPOSI0, 23, 64, iwad +CPOSJ0, 28, 59, iwad +CPOSK0, 30, 48, iwad +CPOSL0, 31, 34, iwad +CPOSM0, 32, 22, iwad +CPOSN0, 32, 18, iwad +CPOSO0, 26, 59, iwad +CPOSP0, 28, 59, iwad +CPOSQ0, 30, 48, iwad +CPOSR0, 32, 40, iwad +CPOSS0, 32, 31, iwad +CPOST0, 32, 19, iwad +CYBRH0, 60, 108, iwad +CYBRI0, 55, 110, iwad +CYBRJ0, 49, 113, iwad +CYBRK0, 56, 114, iwad +CYBRL0, 62, 121, iwad +CYBRM0, 67, 128, iwad +CYBRN0, 70, 132, iwad +CYBRO0, 69, 132, iwad +CYBRP0, 60, 28, iwad +ELECA0, 19, 125, iwad +FATTO0, 35, 43, iwad +FATTP0, 36, 41, iwad +FATTQ0, 36, 40, iwad +FATTR0, 36, 40, iwad +FATTS0, 36, 40, iwad +FATTT0, 36, 39, iwad +FCANA0, 19, 52, iwad +FCANB0, 19, 52, iwad +FCANC0, 19, 50, iwad +PLAYH0, 16, 50, iwad +PLAYI0, 11, 42, iwad +PLAYJ0, 12, 45, iwad +PLAYK0, 17, 37, iwad +PLAYL0, 27, 14, iwad +PLAYM0, 27, 14, iwad +PLAYN0, 27, 14, iwad +POB1A0, 16, 6, iwad +POB2A0, 14, 3, iwad +POL1A0, 22, 65, iwad +POL2A0, 19, 66, iwad +POL3A0, 19, 42, iwad +POL3B0, 19, 42, iwad +POL4A0, 19, 55, iwad +POL5A0, 27, 8, iwad +POL6A0, 17, 65, iwad +POL6B0, 19, 65, iwad +POSSH0, 19, 55, iwad +POSSL0, 22, 14, iwad +SARGI0, 25, 56, iwad +SARGM0, 33, 43, iwad +SARGN0, 33, 29, iwad +SKELM0, 27, 78, iwad +SKELN0, 38, 69, iwad +SKELO0, 28, 55, iwad +SKELP0, 28, 35, iwad +SKELQ0, 40, 20, iwad +SMITA0, 22, 44, iwad +SPIDJ0, 79, 102, iwad +SPIDK0, 95, 95, iwad +SPIDL0, 94, 88, iwad +SPIDM0, 94, 76, iwad +SPIDN0, 98, 71, iwad +SPIDO0, 101, 68, iwad +SPIDP0, 104, 85, iwad +SPIDQ0, 109, 90, iwad +SPIDR0, 110, 111, iwad +SPIDS0, 98, 35, iwad +SPOSH0, 14, 60, iwad +SPOSL0, 24, 15, iwad +SSWVG0, 17, 55, iwad +SSWVH0, 17, 52, iwad +SSWVI0, 18, 54, iwad +SSWVJ0, 15, 44, iwad +SSWVK0, 15, 40, iwad +SSWVL0, 15, 25, iwad +SSWVM0, 24, 13, iwad +SSWVN0, 15, 57, iwad +SSWVO0, 22, 59, iwad +SSWVP0, 25, 58, iwad +TBLUA0, 14, 94, iwad +TBLUB0, 14, 94, iwad +TBLUC0, 14, 94, iwad +TBLUD0, 14, 95, iwad +TGRNA0, 14, 94, iwad +TGRNB0, 14, 89, iwad +TGRNC0, 14, 89, iwad +TGRND0, 14, 95, iwad +TLMPA0, 11, 78, iwad +TLMPB0, 11, 78, iwad +TLMPC0, 11, 78, iwad +TLMPD0, 11, 78, iwad +TLP2A0, 10, 58, iwad +TLP2B0, 10, 58, iwad +TLP2C0, 10, 58, iwad +TLP2D0, 10, 58, iwad +TRE1A0, 25, 67, iwad +TREDA0, 14, 94, iwad +TREDB0, 14, 89, iwad +TREDC0, 14, 89, iwad +TREDD0, 14, 95, iwad +TROOI0, 22, 62, iwad +TROOJ0, 21, 59, iwad +TROOM0, 29, 20, iwad +TROON0, 24, 59, iwad +TROOO0, 20, 61, iwad +TROOP0, 24, 61, iwad +TROOQ0, 24, 61, iwad +TROOR0, 24, 44, iwad +TROOS0, 27, 34, iwad +TROOT0, 27, 31, iwad +TROOU0, 27, 18, iwad +VILER0, 18, 80, iwad +VILES0, 23, 76, iwad +VILET0, 27, 69, iwad +VILEU0, 35, 56, iwad +VILEV0, 34, 45, iwad +VILEW0, 34, 35, iwad +VILEX0, 34, 23, iwad +VILEY0, 34, 20, iwad +VILEZ0, 34, 20, iwad diff --git a/wadsrc/static/filter/doom.doom2/sprofs.txt b/wadsrc/static/filter/doom.doom2/sprofs.txt new file mode 100644 index 000000000..eab3dc4ef --- /dev/null +++ b/wadsrc/static/filter/doom.doom2/sprofs.txt @@ -0,0 +1,164 @@ +BAR1A0, 10, 32, iwad +BAR1B0, 10, 32, iwad +BEXPA0, 10, 32, iwad +BEXPB0, 10, 31, iwad +BEXPC0, 19, 36, iwad +BEXPD0, 27, 49, iwad +BEXPE0, 29, 52, iwad +BOS2I0, 20, 71, iwad +BOS2J0, 26, 62, iwad +BOS2K0, 26, 52, iwad +BOS2L0, 29, 33, iwad +BOS2M0, 30, 29, iwad +BOS2N0, 30, 29, iwad +BOS2O0, 30, 29, iwad +BOSSI0, 20, 72, iwad +BOSSJ0, 26, 63, iwad +BOSSK0, 26, 51, iwad +BOSSL0, 29, 33, iwad +BOSSM0, 30, 29, iwad +BOSSN0, 30, 29, iwad +BOSSO0, 30, 29, iwad +BRS1A0, 13, 8, iwad +BSPIJ0, 50, 54, iwad +BSPIK0, 50, 57, iwad +BSPIL0, 47, 52, iwad +BSPIM0, 45, 44, iwad +BSPIN0, 45, 42, iwad +BSPIO0, 45, 30, iwad +BSPIP0, 45, 28, iwad +CBRAA0, 15, 60, iwad +CEYEA0, 21, 59, iwad +CEYEB0, 21, 58, iwad +CEYEC0, 21, 59, iwad +COL1A0, 16, 51, iwad +COL2A0, 16, 39, iwad +COL3A0, 16, 52, iwad +COL4A0, 17, 39, iwad +COL5A0, 16, 44, iwad +COL5B0, 16, 45, iwad +COL6A0, 17, 47, iwad +COLUA0, 9, 45, iwad +CPOSH0, 20, 61, iwad +CPOSI0, 23, 64, iwad +CPOSJ0, 28, 59, iwad +CPOSK0, 30, 48, iwad +CPOSL0, 31, 34, iwad +CPOSM0, 32, 22, iwad +CPOSN0, 32, 18, iwad +CPOSO0, 26, 59, iwad +CPOSP0, 28, 59, iwad +CPOSQ0, 30, 48, iwad +CPOSR0, 32, 40, iwad +CPOSS0, 32, 31, iwad +CPOST0, 32, 19, iwad +CYBRH0, 60, 108, iwad +CYBRI0, 55, 110, iwad +CYBRJ0, 49, 113, iwad +CYBRK0, 56, 114, iwad +CYBRL0, 62, 121, iwad +CYBRM0, 67, 128, iwad +CYBRN0, 70, 132, iwad +CYBRO0, 69, 132, iwad +CYBRP0, 60, 28, iwad +ELECA0, 19, 125, iwad +FATTO0, 35, 43, iwad +FATTP0, 36, 41, iwad +FATTQ0, 36, 40, iwad +FATTR0, 36, 40, iwad +FATTS0, 36, 40, iwad +FATTT0, 36, 39, iwad +FCANA0, 19, 52, iwad +FCANB0, 19, 52, iwad +FCANC0, 19, 50, iwad +PLAYH0, 16, 50, iwad +PLAYI0, 11, 42, iwad +PLAYJ0, 12, 45, iwad +PLAYK0, 17, 37, iwad +PLAYL0, 27, 14, iwad +PLAYM0, 27, 14, iwad +PLAYN0, 27, 14, iwad +POB1A0, 16, 6, iwad +POB2A0, 14, 3, iwad +POL1A0, 22, 65, iwad +POL2A0, 19, 66, iwad +POL3A0, 19, 42, iwad +POL3B0, 19, 42, iwad +POL4A0, 19, 55, iwad +POL5A0, 27, 8, iwad +POL6A0, 17, 65, iwad +POL6B0, 19, 65, iwad +POSSH0, 19, 55, iwad +POSSL0, 22, 14, iwad +SARGI0, 25, 56, iwad +SARGM0, 33, 43, iwad +SARGN0, 33, 29, iwad +SKELM0, 27, 78, iwad +SKELN0, 38, 69, iwad +SKELO0, 28, 55, iwad +SKELP0, 28, 35, iwad +SKELQ0, 40, 20, iwad +SMITA0, 22, 44, iwad +SPIDJ0, 79, 102, iwad +SPIDK0, 95, 95, iwad +SPIDL0, 94, 88, iwad +SPIDM0, 94, 76, iwad +SPIDN0, 98, 71, iwad +SPIDO0, 101, 68, iwad +SPIDP0, 104, 85, iwad +SPIDQ0, 109, 90, iwad +SPIDR0, 110, 111, iwad +SPIDS0, 98, 35, iwad +SPOSH0, 14, 60, iwad +SPOSL0, 24, 15, iwad +SSWVG0, 17, 55, iwad +SSWVH0, 17, 52, iwad +SSWVI0, 18, 54, iwad +SSWVJ0, 15, 44, iwad +SSWVK0, 15, 40, iwad +SSWVL0, 15, 25, iwad +SSWVM0, 24, 13, iwad +SSWVN0, 15, 57, iwad +SSWVO0, 22, 59, iwad +SSWVP0, 25, 58, iwad +TBLUA0, 14, 94, iwad +TBLUB0, 14, 94, iwad +TBLUC0, 14, 94, iwad +TBLUD0, 14, 95, iwad +TGRNA0, 14, 94, iwad +TGRNB0, 14, 89, iwad +TGRNC0, 14, 89, iwad +TGRND0, 14, 95, iwad +TLMPA0, 11, 78, iwad +TLMPB0, 11, 78, iwad +TLMPC0, 11, 78, iwad +TLMPD0, 11, 78, iwad +TLP2A0, 10, 58, iwad +TLP2B0, 10, 58, iwad +TLP2C0, 10, 58, iwad +TLP2D0, 10, 58, iwad +TRE1A0, 25, 67, iwad +TREDA0, 14, 94, iwad +TREDB0, 14, 89, iwad +TREDC0, 14, 89, iwad +TREDD0, 14, 95, iwad +TROOI0, 22, 62, iwad +TROOJ0, 21, 59, iwad +TROOM0, 29, 20, iwad +TROON0, 24, 59, iwad +TROOO0, 20, 61, iwad +TROOP0, 24, 61, iwad +TROOQ0, 24, 61, iwad +TROOR0, 24, 44, iwad +TROOS0, 27, 34, iwad +TROOT0, 27, 31, iwad +TROOU0, 27, 18, iwad +VILER0, 18, 80, iwad +VILES0, 23, 76, iwad +VILET0, 27, 69, iwad +VILEU0, 35, 56, iwad +VILEV0, 34, 45, iwad +VILEW0, 34, 35, iwad +VILEX0, 34, 23, iwad +VILEY0, 34, 20, iwad +VILEZ0, 34, 20, iwad diff --git a/wadsrc/static/filter/heretic/sprofs.txt b/wadsrc/static/filter/heretic/sprofs.txt new file mode 100644 index 000000000..5f51dcde1 --- /dev/null +++ b/wadsrc/static/filter/heretic/sprofs.txt @@ -0,0 +1,97 @@ +BARLA0, 14, 35, iwad +BEASK0, 37, 77, iwad +BEASM0, 42, 74, iwad +BEASQ0, 29, 11, iwad +BEASU0, 44, 91, iwad +BEASV0, 49, 79, iwad +BEASW0, 51, 68, iwad +BEASX0, 52, 56, iwad +BEASY0, 41, 41, iwad +BEASZ0, 41, 30, iwad +BRPLA0, 28, 128, iwad +CHKNF0, 18, 25, iwad +CHKNG0, 17, 27, iwad +CHKNH0, 18, 30, iwad +CHKNI0, 20, 29, iwad +CHKNJ0, 20, 25, iwad +CHKNK0, 17, 9, iwad +CHKNL0, 13, 4, iwad +CLNKO0, 23, 16, iwad +FDTHA0, 21, 55, iwad +FDTHB0, 21, 60, iwad +FDTHC0, 29, 80, iwad +FDTHD0, 21, 76, iwad +FDTHE0, 22, 75, iwad +FDTHF0, 23, 59, iwad +FDTHG0, 24, 51, iwad +FDTHH0, 23, 48, iwad +FDTHI0, 23, 53, iwad +FDTHJ0, 22, 53, iwad +FDTHK0, 22, 55, iwad +FDTHL0, 23, 56, iwad +FDTHM0, 25, 58, iwad +FDTHN0, 26, 58, iwad +FDTHO0, 24, 59, iwad +IMPXI0, 22, 24, iwad +IMPXJ0, 22, 34, iwad +IMPXK0, 21, 34, iwad +IMPXL0, 22, 9, iwad +IMPXW0, 32, 49, iwad +IMPXX0, 33, 41, iwad +IMPXY0, 33, 25, iwad +IMPXZ0, 33, 11, iwad +KFR1A0, 20, 77, iwad +KFR1B0, 20, 78, iwad +KFR1C0, 20, 81, iwad +KFR1D0, 20, 81, iwad +KFR1E0, 20, 76, iwad +KFR1F0, 20, 78, iwad +KFR1G0, 20, 80, iwad +KFR1H0, 20, 78, iwad +KGZ1A0, 18, 52, iwad +MUMMI0, 33, 64, iwad +MUMMJ0, 34, 66, iwad +MUMMK0, 39, 71, iwad +MUMML0, 40, 66, iwad +MUMMM0, 36, 55, iwad +MUMMN0, 37, 37, iwad +MUMMO0, 38, 19, iwad +MUMMP0, 31, 10, iwad +PLAYS0, 34, 71, iwad +PLAYT0, 35, 68, iwad +PLAYU0, 30, 44, iwad +PLAYV0, 30, 24, iwad +PLAYW0, 30, 23, iwad +PLAYX0, 30, 17, iwad +PLAYY0, 30, 14, iwad +SFFIA0, 5, 20, iwad +SFFIB0, 6, 15, iwad +SFFIC0, 6, 11, iwad +SFFID0, 5, 8, iwad +SFFIE0, 4, 5, iwad +SMPLA0, 14, 37, iwad +SNKEM0, 54, 48, iwad +SNKEN0, 49, 35, iwad +SNKEO0, 48, 23, iwad +SNKEP0, 46, 13, iwad +SRCRE0, 59, 131, iwad +SRCRF0, 52, 120, iwad +SRCRG0, 68, 122, iwad +SRCRH0, 60, 114, iwad +SRCRI0, 63, 105, iwad +SRCRJ0, 67, 76, iwad +SRCRK0, 67, 32, iwad +SRCRL0, 67, 23, iwad +SRCRM0, 67, 28, iwad +SRCRN0, 67, 29, iwad +SRCRO0, 67, 23, iwad +SRCRP0, 67, 17, iwad +SRTCA0, 5, 63, iwad +SRTCB0, 5, 63, iwad +SRTCC0, 5, 61, iwad +STGLA0, 18, 69, iwad +STGSA0, 9, 37, iwad +WZRDJ0, 34, 59, iwad +WZRDK0, 30, 49, iwad +WZRDL0, 29, 26, iwad +WZRDM0, 27, 12, iwad diff --git a/wadsrc/static/filter/hexen/sprofs.txt b/wadsrc/static/filter/hexen/sprofs.txt new file mode 100644 index 000000000..4408e3b95 --- /dev/null +++ b/wadsrc/static/filter/hexen/sprofs.txt @@ -0,0 +1,377 @@ +ZBARA0, 12, 33, iwad +BDPLA0, 7, 2, iwad +BDSHA0, 8, 6, iwad +BDSHB0, 8, 7, iwad +BDSHC0, 8, 7, iwad +BDSHD0, 9, 5, iwad +BISHK0, 43, 74, iwad +BISHL0, 45, 74, iwad +BISHM0, 45, 65, iwad +BISHN0, 43, 22, iwad +BISHO0, 40, 12, iwad +BISHP0, 30, 9, iwad +BRTRA0, 13, 61, iwad +BRTRB0, 13, 59, iwad +BRTRC0, 13, 57, iwad +BRTRD0, 13, 60, iwad +BRTRE0, 13, 59, iwad +BRTRF0, 13, 54, iwad +BRTRG0, 13, 54, iwad +BRTRH0, 13, 57, iwad +BRTRI0, 13, 60, iwad +BRTRJ0, 13, 62, iwad +BRTRK0, 13, 62, iwad +BRTRL0, 13, 58, iwad +BRTRM0, 13, 59, iwad +BCANA0, 10, 38, iwad +BCANB0, 10, 36, iwad +BCANC0, 10, 35, iwad +BCAND0, 10, 35, iwad +BCANE0, 10, 35, iwad +CDRNA0, 14, 24, iwad +CDRNB0, 14, 24, iwad +CDRNC0, 14, 24, iwad +CDRND0, 14, 24, iwad +CDRNE0, 14, 24, iwad +CDRNF0, 14, 24, iwad +CDRNG0, 14, 24, iwad +CDRNH0, 14, 24, iwad +CENTK0, 42, 73, iwad +CENTN0, 49, 76, iwad +CENTO0, 45, 83, iwad +CENTP0, 47, 80, iwad +CENTQ0, 55, 63, iwad +CENTR0, 53, 38, iwad +CENTS0, 43, 27, iwad +CENTT0, 43, 27, iwad +CLERM0, 28, 51, iwad +CLERN0, 26, 42, iwad +CLERO0, 26, 34, iwad +CLERQ0, 26, 16, iwad +CLERR0, 23, 67, iwad +CLERS0, 30, 67, iwad +CLERT0, 35, 68, iwad +CLERU0, 34, 64, iwad +CLERV0, 35, 61, iwad +CLERW0, 37, 53, iwad +CLERX0, 37, 43, iwad +CLERY0, 38, 30, iwad +CLERZ0, 38, 18, iwad +"CLER[0", 38, 12, iwad +CPB1A0, 8, 7, iwad +CPB2A0, 7, 6, iwad +CPB3A0, 12, 4, iwad +CPB4A0, 5, 10, iwad +CPS2A0, 24, 13, iwad +CPS6A0, 22, 36, iwad +CTDPJ0, 21, 9, iwad +DEM2H0, 50, 92, iwad +DEM2I0, 67, 124, iwad +DEM2J0, 60, 121, iwad +DEM2K0, 76, 123, iwad +DEM2L0, 68, 115, iwad +DEM2M0, 71, 105, iwad +DEM2N0, 75, 76, iwad +DEM2O0, 75, 32, iwad +DEM2P0, 75, 17, iwad +DEMNH0, 50, 92, iwad +DEMNI0, 67, 124, iwad +DEMNJ0, 60, 121, iwad +DEMNK0, 76, 123, iwad +DEMNL0, 68, 115, iwad +DEMNM0, 71, 105, iwad +DEMNN0, 75, 76, iwad +DEMNO0, 75, 32, iwad +DEMNP0, 75, 17, iwad +DRAGM0, 45, 22, iwad +ETTBB0, 45, 73, iwad +ETTBC0, 39, 80, iwad +ETTBD0, 45, 87, iwad +ETTBE0, 51, 84, iwad +ETTBF0, 53, 74, iwad +ETTBG0, 48, 70, iwad +ETTBH0, 49, 64, iwad +ETTBI0, 50, 52, iwad +ETTBJ0, 50, 31, iwad +ETTBK0, 50, 22, iwad +ETTBL0, 50, 22, iwad +ETTBM0, 14, 20, iwad +ETTNO0, 42, 46, iwad +ETTNP0, 42, 56, iwad +ETTNQ0, 36, 34, iwad +FDTHA0, 29, 64, iwad +FDTHB0, 29, 64, iwad +FDTHE0, 28, 62, iwad +FDTHF0, 28, 62, iwad +FDTHG0, 29, 80, iwad +FDTHH0, 17, 76, iwad +FDTHI0, 19, 76, iwad +FDTHJ0, 20, 56, iwad +FDTHK0, 21, 51, iwad +FDTHL0, 21, 47, iwad +FDTHM0, 21, 46, iwad +FDTHN0, 21, 47, iwad +FDTHO0, 20, 49, iwad +FDTHP0, 21, 49, iwad +FDTHQ0, 19, 50, iwad +FDTHR0, 20, 51, iwad +FFLGA0, 4, 4, iwad +FFLGB0, 4, 11, iwad +FFLGC0, 6, 24, iwad +FFLGD0, 10, 28, iwad +FFLGE0, 6, 35, iwad +FFLGF0, 7, 40, iwad +FFLGG0, 7, 40, iwad +FFLGH0, 7, 34, iwad +FFLGI0, 7, 33, iwad +FFLGJ0, 7, 28, iwad +FFLGK0, 7, 28, iwad +FFLGL0, 7, 31, iwad +FFLGM0, 7, 34, iwad +FFLGN0, 7, 37, iwad +FFLGO0, 7, 39, iwad +FFLGP0, 7, 40, iwad +FFLGQ0, 7, 33, iwad +FFSMA0, 2, 20, iwad +FFSMB0, 2, 20, iwad +FFSMC0, 2, 18, iwad +FFSMD0, 2, 16, iwad +FFSME0, 2, 17, iwad +FSKLA0, 11, 54, iwad +FSKLB0, 11, 52, iwad +FSKLC0, 11, 50, iwad +FSKLD0, 11, 53, iwad +FSKLE0, 11, 47, iwad +FSKLF0, 11, 47, iwad +FSKLG0, 11, 53, iwad +FSKLH0, 11, 48, iwad +FSKLI0, 11, 51, iwad +GAR1A0, 25, 121, iwad +GAR2A0, 25, 121, iwad +GAR3A0, 25, 121, iwad +GAR4A0, 25, 121, iwad +GAR5A0, 25, 121, iwad +GAR6A0, 25, 75, iwad +GAR7A0, 25, 75, iwad +GAR8A0, 24, 75, iwad +GAR9A0, 25, 75, iwad +GMPDA0, 14, 46, iwad +GMPDB0, 14, 53, iwad +ICM4A0, 2, 23, iwad +IRONA0, 23, 62, iwad +LOGGA0, 20, 55, iwad +MAGEK0, 41, 42, iwad +MAGEL0, 43, 33, iwad +MAGEM0, 43, 21, iwad +MAGEN0, 31, 12, iwad +MAGEO0, 26, 71, iwad +MAGEP0, 30, 72, iwad +MAGEQ0, 33, 66, iwad +MAGER0, 34, 60, iwad +MAGES0, 36, 57, iwad +MAGET0, 37, 50, iwad +MAGEU0, 35, 39, iwad +MAGEV0, 36, 30, iwad +MAGEW0, 35, 18, iwad +MAGEX0, 35, 9, iwad +MSH1A0, 15, 25, iwad +MSH2A0, 13, 25, iwad +MSH3A0, 11, 21, iwad +MSH4A0, 7, 15, iwad +MSH5A0, 7, 11, iwad +MSH6A0, 6, 11, iwad +MSH7A0, 7, 12, iwad +MSH8A0, 5, 16, iwad +PIGYE0, 12, 24, iwad +PIGYF0, 17, 29, iwad +PIGYG0, 22, 41, iwad +PLAYL0, 36, 42, iwad +PLAYM0, 36, 31, iwad +PLAYN0, 40, 17, iwad +PLAYO0, 24, 72, iwad +PLAYP0, 31, 74, iwad +PLAYQ0, 35, 70, iwad +PLAYR0, 38, 64, iwad +PLAYS0, 38, 55, iwad +PLAYT0, 40, 44, iwad +PLAYU0, 40, 34, iwad +PLAYV0, 41, 28, iwad +PLAYW0, 39, 13, iwad +POT1A0, 10, 37, iwad +POT2A0, 10, 30, iwad +POT3A0, 12, 24, iwad +RBL1A0, 21, 9, iwad +RBL2A0, 14, 8, iwad +RBL3A0, 15, 10, iwad +RCK1A0, 7, 7, iwad +RCK2A0, 10, 11, iwad +RCK3A0, 14, 18, iwad +RCK4A0, 24, 22, iwad +RKBKA0, 30, 40, iwad +RKBSA0, 18, 50, iwad +ROKKA0, 11, 16, iwad +ROKKB0, 8, 11, iwad +ROKKC0, 4, 6, iwad +ROKKD0, 6, 6, iwad +ROKKE0, 4, 5, iwad +ROKKG0, 3, 5, iwad +ROKKH0, 3, 3, iwad +SGM1A0, 17, 69, iwad +SGM2A0, 12, 54, iwad +SGM3A0, 14, 44, iwad +SGMPA0, 18, 126, iwad +SHRMA0, 13, 25, iwad +SHRMB0, 15, 26, iwad +SHRMC0, 21, 36, iwad +SHRMD0, 23, 40, iwad +SHRME0, 17, 26, iwad +SHRMF0, 19, 15, iwad +SLTRA0, 23, 52, iwad +SORCH0, 29, 92, iwad +SORCI0, 34, 97, iwad +SORCJ0, 36, 98, iwad +SORCK0, 41, 101, iwad +SORCL0, 48, 97, iwad +SORCM0, 50, 97, iwad +SORCN0, 47, 97, iwad +SORCO0, 46, 97, iwad +SORCP0, 46, 95, iwad +SORCQ0, 34, 95, iwad +SORCR0, 34, 86, iwad +SORCS0, 34, 72, iwad +SORCT0, 34, 50, iwad +SORCU0, 34, 29, iwad +SORCV0, 40, 31, iwad +SORCW0, 52, 41, iwad +SORCX0, 54, 46, iwad +SORCY0, 48, 33, iwad +SORCZ0, 34, 12, iwad +SSPTO0, 36, 66, iwad +SSPTP0, 38, 73, iwad +SSPTQ0, 35, 69, iwad +SSPTR0, 33, 53, iwad +SSPTS0, 34, 52, iwad +SSPTT0, 44, 43, iwad +SSPTU0, 47, 30, iwad +SSPTV0, 41, 35, iwad +SSPTW0, 35, 43, iwad +SSPTX0, 29, 47, iwad +SSPTY0, 24, 33, iwad +SSPTZ0, 27, 17, iwad +SSXDA0, 36, 66, iwad +SSXDB0, 37, 68, iwad +SSXDC0, 52, 68, iwad +SSXDD0, 58, 54, iwad +SSXDE0, 59, 37, iwad +SSXDF0, 61, 22, iwad +SSXDG0, 57, 18, iwad +SSXDH0, 52, 13, iwad +STM1A0, 24, 39, iwad +STM2A0, 25, 32, iwad +STM3A0, 13, 25, iwad +STM4A0, 12, 34, iwad +STT2A0, 25, 121, iwad +STT3A0, 25, 121, iwad +STT4A0, 25, 75, iwad +STT5A0, 25, 75, iwad +STTWA0, 29, 83, iwad +STWNA0, 29, 83, iwad +STWNB0, 29, 83, iwad +ZSUIA0, 18, 80, iwad +ZSUIB0, 8, 8, iwad +ZSUIC0, 6, 11, iwad +ZSUID0, 6, 9, iwad +ZSUIE0, 9, 11, iwad +ZSUIF0, 6, 10, iwad +ZSUIG0, 4, 7, iwad +ZSUIH0, 12, 14, iwad +ZSUII0, 11, 7, iwad +ZSUIJ0, 7, 3, iwad +ZSUIK0, 13, 3, iwad +SWMVA0, 22, 68, iwad +TMS1A0, 19, 52, iwad +TMS2A0, 19, 52, iwad +TMS3A0, 20, 52, iwad +TMS4A0, 16, 58, iwad +TMS5A0, 18, 58, iwad +TMS6A0, 14, 54, iwad +TMS7A0, 15, 54, iwad +TRDTA0, 57, 187, iwad +TRDTB0, 76, 181, iwad +TRDTC0, 88, 153, iwad +TRDTD0, 84, 85, iwad +TRDTE0, 81, 52, iwad +TRDTF0, 61, 31, iwad +TRDTG0, 23, 31, iwad +TRDTH0, 58, 187, iwad +TRDTI0, 77, 183, iwad +TRDTJ0, 89, 191, iwad +TRDTK0, 85, 191, iwad +TRDTL0, 82, 156, iwad +TRDTM0, 62, 141, iwad +TRDTN0, 48, 140, iwad +TRDTO0, 48, 82, iwad +TRDTP0, 38, 39, iwad +TRDTQ0, 26, 39, iwad +ZTREA0, 43, 134, iwad +TRESA0, 51, 179, iwad +TRE4A0, 73, 187, iwad +TRE5A0, 72, 187, iwad +TRE6A0, 56, 122, iwad +TRE7A0, 55, 122, iwad +TSPKB0, 26, 131, iwad +TSPKD0, 22, 9, iwad +TST0A0, 12, 22, iwad +TST1A0, 6, 20, iwad +TST2A0, 6, 16, iwad +TST3A0, 9, 25, iwad +TST4A0, 6, 21, iwad +TST5A0, 6, 25, iwad +TST6A0, 8, 10, iwad +TST7A0, 6, 13, iwad +TST8A0, 6, 10, iwad +TST9A0, 6, 10, iwad +TWTRA0, 14, 79, iwad +TWTRB0, 14, 81, iwad +TWTRC0, 14, 83, iwad +TWTRD0, 14, 83, iwad +TWTRE0, 14, 79, iwad +TWTRF0, 14, 80, iwad +TWTRG0, 14, 82, iwad +TWTRH0, 14, 80, iwad +TWTRI0, 14, 65, iwad +VASEA0, 11, 53, iwad +XMASA0, 23, 150, iwad +XMASB0, 25, 151, iwad +XMASC0, 25, 151, iwad +XMASD0, 30, 151, iwad +XMASE0, 20, 151, iwad +XMASF0, 14, 156, iwad +XMASG0, 5, 163, iwad +XMASH0, 5, 152, iwad +XMASI0, 8, 132, iwad +XMASJ0, 10, 72, iwad +XMASK0, 13, 17, iwad +FHFXN0, 26, 21, iwad +CTDPG0, 15, 15, iwad +CTDPH0, 21, 7, iwad +CTDPI0, 17, 12, iwad +CTDPJ0, 21, 11, iwad +CTDPR0, 18, 12, iwad +CTDPS0, 21, 6, iwad +CTDPT0, 23, 3, iwad +ETTBM0, 14, 15, iwad +ETTBN0, 18, 8, iwad +ETTBO0, 15, 5, iwad +ETTBP0, 13, 8, iwad +ETTBQ0, 9, 16, iwad +ETTBR0, 18, 18, iwad +ETTBS0, 20, 15, iwad +THRWA0, 10, 15, iwad +THRWB0, 10, 18, iwad +THRWC0, 8, 20, iwad +THRWD0, 6, 18, iwad +THRWE0, 6, 16, iwad +THRWF0, 8, 19, iwad +THRWG0, 8, 19, iwad +THRWH0, 11, 19, iwad diff --git a/wadsrc/static/filter/strife/sprofs.txt b/wadsrc/static/filter/strife/sprofs.txt new file mode 100644 index 000000000..c6dafb581 --- /dev/null +++ b/wadsrc/static/filter/strife/sprofs.txt @@ -0,0 +1,364 @@ +TWAVA0, 47, 20, iwad +TWAVB0, 20, 15, iwad +ZAP5A0, 13, 6, iwad +ZAP5B0, 15, 6, iwad +ZAP5C0, 13, 6, iwad +ZAP5D0, 14, 6, iwad +BARTB0, 11, 31, iwad +BARTC0, 14, 31, iwad +BARTD0, 19, 34, iwad +BARTE0, 23, 36, iwad +BARTF0, 26, 40, iwad +BARTG0, 27, 43, iwad +BARTH0, 27, 44, iwad +BARTI0, 27, 45, iwad +BARTJ0, 27, 46, iwad +BARTK0, 27, 50, iwad +BARTL0, 27, 7, iwad +BARWB0, 12, 30, iwad +BARWC0, 14, 30, iwad +BARWD0, 15, 29, iwad +BARWE0, 15, 26, iwad +BARWF0, 18, 23, iwad +BARWG0, 19, 18, iwad +BARWH0, 19, 11, iwad +FLBEC0, 21, 51, iwad +FLBED0, 24, 77, iwad +DIE1A0, 27, 7, iwad +DEADA0, 31, 11, iwad +SACRA0, 31, 13, iwad +RGIBD0, 27, 48, iwad +RGIBE0, 27, 30, iwad +RGIBF0, 27, 17, iwad +RGIBG0, 27, 12, iwad +RGIBH0, 27, 10, iwad +GIBSM0, 18, 54, iwad +GIBSN0, 23, 58, iwad +GIBSO0, 23, 60, iwad +GIBSP0, 26, 54, iwad +GIBSQ0, 27, 42, iwad +GIBSR0, 27, 29, iwad +GIBSS0, 27, 19, iwad +GIBST0, 27, 11, iwad +GIBSU0, 27, 8, iwad +GIBSV0, 27, 7, iwad +GIBSA0, 28, 58, iwad +GIBSB0, 31, 62, iwad +GIBSC0, 31, 62, iwad +GIBSD0, 31, 60, iwad +GIBSE0, 31, 54, iwad +GIBSF0, 31, 38, iwad +GIBSG0, 31, 22, iwad +GIBSH0, 31, 13, iwad +GIBSI0, 31, 10, iwad +GIBSJ0, 31, 10, iwad +GIBSK0, 31, 10, iwad +GIBSL0, 31, 10, iwad +PLAYG0, 26, 54, iwad +PLAYN0, 24, 28, iwad +PLAYO0, 27, 22, iwad +PLAYP0, 27, 13, iwad +BURNA0, 15, 55, iwad +BURNB0, 23, 58, iwad +BURNC0, 23, 61, iwad +BURND0, 22, 67, iwad +BURNE0, 20, 65, iwad +BURNF0, 18, 69, iwad +BURNQ0, 23, 54, iwad +BURNR0, 23, 22, iwad +BURNS0, 23, 30, iwad +BURNT0, 23, 21, iwad +BURNU0, 23, 13, iwad +BURNV0, 23, 11, iwad +MRSTA0, 11, 59, iwad +MRLKA0, 11, 59, iwad +MRLKB0, 11, 59, iwad +MRBDA0, 11, 59, iwad +MRBDB0, 8, 59, iwad +MRBDC0, 8, 59, iwad +MRBDD0, 8, 59, iwad +MRBDE0, 8, 60, iwad +MRBDF0, 11, 59, iwad +MRYSA0, 16, 55, iwad +MRPNA0, 16, 50, iwad +MRPNB0, 11, 47, iwad +MRPNC0, 11, 43, iwad +MRPND0, 10, 41, iwad +MRGTA0, 17, 59, iwad +MRGTB0, 17, 59, iwad +MRGTC0, 19, 59, iwad +MRGTD0, 17, 59, iwad +MRGTE0, 17, 59, iwad +MRGTF0, 18, 59, iwad +MRGTG0, 16, 59, iwad +MRGTH0, 13, 59, iwad +MRGTI0, 14, 59, iwad +MRNOA0, 11, 59, iwad +MRNOB0, 11, 59, iwad +MRNOC0, 11, 58, iwad +ARMRA0, 31, 68, iwad +PEASG0, 14, 49, iwad +PEASH0, 11, 42, iwad +PEASI0, 12, 45, iwad +PEASJ0, 11, 43, iwad +PEASK0, 14, 37, iwad +PEASL0, 26, 16, iwad +PEASM0, 27, 13, iwad +PEASN0, 27, 13, iwad +BEGRF0, 10, 54, iwad +BEGRG0, 14, 58, iwad +BEGRH0, 18, 60, iwad +BEGRL0, 15, 37, iwad +BEGRM0, 17, 21, iwad +BEGRN0, 19, 10, iwad +HMN1G0, 23, 53, iwad +HMN1H0, 22, 50, iwad +HMN1J0, 20, 49, iwad +HMN1K0, 20, 45, iwad +HMN1L0, 20, 39, iwad +HMN1M0, 20, 24, iwad +HMN1N0, 20, 16, iwad +LEADG0, 26, 52, iwad +LEADH0, 24, 51, iwad +LEADI0, 23, 53, iwad +LEADJ0, 22, 51, iwad +LEADK0, 22, 49, iwad +LEADL0, 22, 47, iwad +LEADM0, 22, 49, iwad +LEADN0, 22, 53, iwad +LEADO0, 22, 50, iwad +LEADP0, 22, 43, iwad +LEADQ0, 31, 40, iwad +LEADR0, 31, 33, iwad +LEADS0, 31, 30, iwad +LEADT0, 31, 27, iwad +LEADU0, 31, 23, iwad +LEADV0, 31, 18, iwad +LEADW0, 31, 13, iwad +LEADX0, 31, 10, iwad +ROB2G0, 40, 67, iwad +ROB2H0, 48, 70, iwad +ROB2I0, 54, 92, iwad +ROB2J0, 48, 92, iwad +ROB2K0, 52, 79, iwad +ROB2L0, 58, 85, iwad +ROB2M0, 55, 92, iwad +ROB2N0, 51, 93, iwad +ROB2O0, 47, 98, iwad +SEWRI0, 46, 48, iwad +SEWRJ0, 29, 30, iwad +DISRA0, 23, 55, iwad +DISRB0, 23, 57, iwad +DISRC0, 22, 57, iwad +DISRD0, 16, 62, iwad +DISRE0, 19, 61, iwad +DISRF0, 19, 59, iwad +DISRG0, 22, 55, iwad +DISRH0, 23, 44, iwad +DISRI0, 23, 38, iwad +DISRJ0, 23, 32, iwad +PRGRA0, 51, 69, iwad +PRGRS0, 51, 28, iwad +PRGRT0, 51, 21, iwad +PRGRU0, 51, 20, iwad +PRGRV0, 51, 19, iwad +PRGRW0, 51, 19, iwad +PRGRX0, 51, 18, iwad +BASEG0, 35, 23, iwad +BASEH0, 35, 23, iwad +SPIDB1, 30, 34, iwad +SPIDB2, 37, 33, iwad +SPIDB3, 26, 34, iwad +SPIDB4, 37, 34, iwad +SPIDB5, 33, 32, iwad +SPIDB6, 37, 34, iwad +SPIDB7, 27, 34, iwad +SPIDB8, 37, 32, iwad +ROB3L0, 60, 122, iwad +ROB3M0, 65, 121, iwad +ROB3N0, 98, 114, iwad +ROB3O0, 94, 105, iwad +RBB3D0, 43, 43, iwad +RBB3E0, 43, 29, iwad +RBB3G0, 33, 46, iwad +RBB3H0, 37, 36, iwad +PGRDI0, 27, 56, iwad +PGRDJ0, 31, 56, iwad +PGRDK0, 35, 60, iwad +PGRDL0, 31, 61, iwad +PGRDM0, 27, 60, iwad +PGRDN0, 27, 63, iwad +PGRDO0, 31, 60, iwad +PGRDP0, 39, 53, iwad +PGRDQ0, 43, 39, iwad +PGRDR0, 43, 32, iwad +PGRDS0, 39, 26, iwad +PGRDT0, 35, 28, iwad +PGRDU0, 35, 28, iwad +PGRDV0, 35, 28, iwad +PGRDW0, 35, 28, iwad +PGRDX0, 35, 28, iwad +PGRDY0, 35, 28, iwad +PGRDZ0, 35, 28, iwad +"PGRD[0", 35, 28, iwad +"PGRD\0", 35, 28, iwad +PDEDE0, 22, 20, iwad +PDEDF0, 23, 16, iwad +PDEDG0, 23, 15, iwad +PDEDH0, 23, 15, iwad +PDEDI0, 23, 15, iwad +PDEDJ0, 23, 17, iwad +PDEDK0, 23, 20, iwad +PDEDL0, 23, 22, iwad +PDEDM0, 22, 23, iwad +PDEDN0, 22, 26, iwad +PDEDO0, 23, 26, iwad +PDEDP0, 23, 24, iwad +PDEDQ0, 23, 21, iwad +PDEDR0, 23, 15, iwad +PDEDS0, 23, 11, iwad +PDEDT0, 23, 5, iwad +ORCLB0, 23, 77, iwad +ORCLC0, 23, 70, iwad +ORCLD0, 23, 70, iwad +ORCLE0, 23, 70, iwad +ORCLF0, 23, 70, iwad +ORCLG0, 23, 70, iwad +ORCLH0, 23, 70, iwad +ORCLI0, 23, 71, iwad +ORCLJ0, 23, 68, iwad +ORCLK0, 23, 61, iwad +ORCLL0, 23, 53, iwad +ORCLM0, 23, 50, iwad +ORCLN0, 23, 45, iwad +ORCLO0, 23, 42, iwad +ORCLP0, 23, 42, iwad +ORCLQ0, 23, 42, iwad +NEALD0, 14, 48, iwad +NEALE0, 10, 43, iwad +NEALF0, 7, 38, iwad +NEALG0, 4, 35, iwad +NEALH0, 3, 32, iwad +NEALI0, 3, 28, iwad +NEALJ0, 3, 11, iwad +MLDRH0, 41, 131, iwad +MLDRI0, 54, 122, iwad +MLDRJ0, 57, 115, iwad +MLDRK0, 59, 127, iwad +MLDRL0, 72, 126, iwad +MLDRM0, 72, 134, iwad +MLDRN0, 63, 102, iwad +MLDRQ0, 38, 85, iwad +MLDRR0, 59, 61, iwad +MLDRT0, 55, 44, iwad +MLDRU0, 55, 44, iwad +MLDRV0, 55, 46, iwad +TRAYA0, 11, 39, iwad +RUB1A0, 4, 9, iwad +RUB2A0, 4, 10, iwad +RUB5A0, 2, 12, iwad +RUB7A0, 3, 12, iwad +RUB8A0, 4, 11, iwad +SPLHA0, 4, 8, iwad +SPLHB0, 4, 8, iwad +SPLHC0, 4, 8, iwad +SPLHD0, 4, 8, iwad +SPLHE0, 4, 8, iwad +SPLHF0, 4, 8, iwad +SPLHG0, 4, 7, iwad +CNDLA0, 4, 16, iwad +BARLA0, 12, 41, iwad +BARLB0, 12, 41, iwad +BARLC0, 12, 41, iwad +BARLD0, 12, 41, iwad +MUGGA0, 7, 11, iwad +VASEA0, 11, 22, iwad +STATA0, 19, 64, iwad +LTRHA0, 10, 70, iwad +LTRHB0, 10, 65, iwad +LTRHC0, 10, 69, iwad +LTRHD0, 10, 68, iwad +HERTA0, 15, 56, iwad +HERTB0, 15, 56, iwad +HERTC0, 15, 56, iwad +MONIA0, 19, 125, iwad +STELA0, 15, 127, iwad +STLEA0, 15, 40, iwad +VASEB0, 11, 31, iwad +STOLA0, 7, 23, iwad +POT1A0, 7, 13, iwad +LAMPA0, 11, 79, iwad +TUB1A0, 11, 14, iwad +TREEC0, 14, 63, iwad +BUSHA0, 15, 47, iwad +SHRBA0, 23, 63, iwad +BAR1A0, 15, 57, iwad +HUGEA0, 23, 190, iwad +HUGEB0, 23, 190, iwad +HUGEC0, 23, 190, iwad +HUGED0, 23, 190, iwad +STLGB0, 16, 60, iwad +STLGE0, 16, 100, iwad +STLGF0, 6, 31, iwad +TNK1A0, 15, 192, iwad +TNK1B0, 15, 192, iwad +TNK1C0, 15, 192, iwad +TNK2A0, 15, 192, iwad +TNK2B0, 15, 192, iwad +TNK2C0, 15, 192, iwad +TNK4A0, 15, 56, iwad +TNK4B0, 15, 56, iwad +TNK4C0, 15, 56, iwad +TNK3A0, 15, 192, iwad +TNK3B0, 15, 192, iwad +TNK3C0, 15, 192, iwad +TNK5A0, 15, 56, iwad +TNK5B0, 15, 56, iwad +TNK5C0, 15, 56, iwad +TNK6A0, 15, 56, iwad +TNK6B0, 15, 56, iwad +TNK6C0, 15, 56, iwad +APOWA0, 27, 198, iwad +LANTA0, 8, 79, iwad +LMPCA0, 11, 78, iwad +LMPCB0, 11, 78, iwad +LMPCC0, 11, 74, iwad +LMPCD0, 11, 78, iwad +LMPCE0, 11, 78, iwad +STLAA0, 15, 78, iwad +TLMPA0, 10, 63, iwad +TLMPB0, 11, 78, iwad +LOGSA0, 14, 91, iwad +LOGSB0, 14, 93, iwad +LOGSC0, 14, 93, iwad +LOGSD0, 14, 93, iwad +LOGSE0, 14, 93, iwad +HOGNA0, 23, 80, iwad +HOGNB0, 11, 80, iwad +HOGNC0, 2, 80, iwad +PSTNA0, 23, 128, iwad +PSTNB0, 23, 128, iwad +PSTNC0, 23, 128, iwad +PSTND0, 23, 128, iwad +PSTNE0, 23, 128, iwad +FLGRA0, 8, 39, iwad +FLGBA0, 8, 39, iwad +FLGGA0, 8, 39, iwad +PSTNF0, 23, 126, iwad +PSTNG0, 23, 94, iwad +PSTNH0, 23, 63, iwad +PSTNI0, 23, 15, iwad +STAKA0, 17, 127, iwad +COUPA0, 11, 22, iwad +COUPB0, 11, 22, iwad +COUPC0, 11, 22, iwad +AFEDA0, 11, 24, iwad +BOTRA0, 8, 16, iwad +HATRA0, 4, 13, iwad +TOPRA0, 12, 11, iwad +BUBBA0, 15, 127, iwad +BUBFA0, 15, 65, iwad +ASPRA0, 23, 127, iwad +SPDLA0, 30, 52, iwad +SPDLB0, 30, 52, iwad +SPDLC0, 30, 51, iwad diff --git a/wadsrc/static/glstuff/gllight.png b/wadsrc/static/glstuff/gllight.png new file mode 100644 index 000000000..a3a296b9f Binary files /dev/null and b/wadsrc/static/glstuff/gllight.png differ diff --git a/wadsrc/static/glstuff/glpart.png b/wadsrc/static/glstuff/glpart.png new file mode 100644 index 000000000..ddb0aea8e Binary files /dev/null and b/wadsrc/static/glstuff/glpart.png differ diff --git a/wadsrc/static/glstuff/glpart2.png b/wadsrc/static/glstuff/glpart2.png new file mode 100644 index 000000000..f95255ebf Binary files /dev/null and b/wadsrc/static/glstuff/glpart2.png differ diff --git a/wadsrc/static/glstuff/mirror.png b/wadsrc/static/glstuff/mirror.png new file mode 100644 index 000000000..08a6abcbe Binary files /dev/null and b/wadsrc/static/glstuff/mirror.png differ diff --git a/wadsrc/static/language.eng b/wadsrc/static/language.eng index ca27bf80a..bf0a0a91d 100644 --- a/wadsrc/static/language.eng +++ b/wadsrc/static/language.eng @@ -108,3 +108,5 @@ CMPTMNU_SECTORSOUNDS = "Sector sounds use centre as source"; OPTVAL_MAPDEFINEDCOLORSONLY = "Map defined colours only"; C_GRAY = "\ccgrey"; C_DARKGRAY = "\cudark grey"; + +OPTVAL_ANYFIXEDCOLORMAP = "Any fixed colourmap"; diff --git a/wadsrc/static/language.enu b/wadsrc/static/language.enu index 28db40e64..c6de55f6f 100644 --- a/wadsrc/static/language.enu +++ b/wadsrc/static/language.enu @@ -1656,6 +1656,7 @@ OPTMNU_NETWORK = "Network Options"; OPTMNU_SOUND = "Sound Options"; OPTMNU_DISPLAY = "Display Options"; OPTMNU_VIDEO = "Set video mode"; +OPTMNU_CHANGERENDER = "Change Rendering Output"; OPTMNU_DEFAULTS = "Reset to defaults"; OPTMNU_RESETTOSAVED = "Reset to last saved"; OPTMNU_CONSOLE = "Go to console"; @@ -1780,6 +1781,8 @@ DSPLYMNU_BRIGHTNESS = "Brightness"; DSPLYMNU_VSYNC = "Vertical Sync"; DSPLYMNU_CAPFPS = "Rendering Interpolation"; DSPLYMNU_COLUMNMETHOD = "Column render mode"; +DSPLYMNU_BLENDMETHOD = "Transparency render mode"; + DSPLYMNU_WIPETYPE = "Screen wipe style"; DSPLYMNU_SHOWENDOOM = "Show ENDOOM screen"; DSPLYMNU_BLOODFADE = "Blood Flash Intensity"; @@ -1788,6 +1791,7 @@ DSPLYMNU_WATERFADE = "Underwater Blend Intensity"; DSPLYMNU_PALLETEHACK = "DirectDraw palette hack"; // Not used DSPLYMNU_ATTACHEDSURFACES = "Use attached surfaces"; // Not used DSPLYMNU_SKYMODE = "Sky render mode"; +DSPLYMNU_LINEARSKY = "Linear skies"; DSPLYMNU_GZDFULLBRIGHT = "Fullbright overrides sector color"; DSPLYMNU_DRAWFUZZ = "Use fuzz effect"; DSPLYMNU_TRANSSOUL = "Lost Soul translucency"; @@ -2146,6 +2150,13 @@ MODMNU_QUALITY = "Quality"; MODMNU_VOLUMERAMPING = "Volume ramping"; MODMNU_CHIPOMATIC = "Chip-o-matic"; +// Renderer Options +RNDMNU_TITLE = "CHANGE RENDERER"; +RNDMNU_RENDERER = "Hardware Acceleration"; +RNDMNU_TRUECOLOR = "Software Truecolor Mode"; +RNDMNU_POLY = "Poly Renderer (experimental)"; +RNDMNU_CANVAS = "Software Canvas"; + // Video Options VIDMNU_TITLE = "VIDEO MODE"; VIDMNU_FULLSCREEN = "Fullscreen"; @@ -2189,6 +2200,8 @@ OPTVAL_INVERTED = "Inverted"; OPTVAL_NOTINVERTED = "Not Inverted"; OPTVAL_ORIGINAL = "Original"; OPTVAL_OPTIMIZED = "Optimized"; +OPTVAL_CLASSIC = "Classic (Faster)"; +OPTVAL_PRECISE = "Precise"; OPTVAL_NORMAL = "Normal"; OPTVAL_STRETCH = "Stretch"; OPTVAL_CAPPED = "Capped"; @@ -2303,6 +2316,12 @@ OPTVAL_ERRORS = "Errors"; OPTVAL_WARNINGS = "Warnings"; OPTVAL_NOTIFICATIONS = "Notifications"; OPTVAL_EVERYTHING = "Everything"; +OPTVAL_FULLSCREENONLY = "Fullscreen only"; +OPTVAL_GL = "OpenGL"; +OPTVAL_D3D = "Direct3D"; +OPTVAL_HWPOLY = "OpenGL-Accelerated"; +OPTVAL_SWDOOM = "Doom Software Renderer"; + // Colors C_BRICK = "\cabrick"; C_TAN = "\cbtan"; @@ -2578,3 +2597,166 @@ MUSIC_ULTIMA = "ultima"; MUSIC_READ_M = "read_m"; MUSIC_DM2TTL = "dm2ttl"; MUSIC_DM2INT = "dm2int"; + +// GZDoom exclusive: + +DSPLYMNU_GLOPT = "OpenGL Options"; +DSPLYMNU_GAMMA = "Gamma correction"; +DSPLYMNU_CONTRAST ="Contrast"; +DSPLYMNU_HWGAMMA = "Hardware Gamma"; + +// OpenGL Options +GLMNU_TITLE = "OPENGL OPTIONS"; +GLMNU_DYNLIGHT = "Dynamic Light Options"; +GLMNU_TEXOPT = "Texture Options"; +GLMNU_PREFS = "Preferences"; + +// Texture Options +GLTEXMNU_TITLE = "TEXTURE OPTIONS"; +GLTEXMNU_TEXENABLED = "Textures enabled"; +GLTEXMNU_TEXFILTER = "Texture Filter mode"; +GLTEXMNU_ANISOTROPIC = "Anisotropic filter"; +GLTEXMNU_TEXFORMAT = "Texture Format"; +GLTEXMNU_ENABLEHIRES = "Enable hires textures"; +GLTEXMNU_HQRESIZE = "High Quality Resize mode"; +GLTEXMNU_RESIZETEX = "Resize textures"; +GLTEXMNU_RESIZESPR = "Resize sprites"; +GLTEXMNU_RESIZEFNT = "Resize fonts"; +GLTEXMNU_PRECACHETEX = "Precache GL textures"; +GLTEXMNU_TRIMSPREDGE = "Trim sprite edges"; +GLTEXMNU_SORTDRAWLIST = "Sort draw lists by texture"; + +// Dynamic Light Options +GLLIGHTMNU_TITLE = "DYNAMIC LIGHTS"; +GLLIGHTMNU_LIGHTSENABLED = "Dynamic Lights enabled"; +GLLIGHTMNU_LIGHTDEFS = "Enable light definitions"; +GLLIGHTMNU_CLIPLIGHTS = "Clip lights"; +GLLIGHTMNU_LIGHTSPRITES = "Lights affect sprites"; +GLLIGHTMNU_LIGHTPARTICLES = "Lights affect particles"; +GLLIGHTMNU_LIGHTMATH = "Light quality"; + +// OpenGL Preferences +GLPREFMNU_TITLE = "OPENGL PREFERENCES"; +GLPREFMNU_SECLIGHTMODE = "Sector light mode"; +GLPREFMNU_FOGMODE = "Fog mode"; +GLPREFMNU_FOGFORCEFULLBRIGHT = "Fog forces fullbright"; +GLPREFMNU_WPNLIGHTSTR = "Weapon light strength"; +GLPREFMNU_ENVIRONMENTMAPMIRROR = "Environment map on mirrors"; +GLPREFMNU_ENV = "Enhanced night vision mode"; +GLPREFMNU_ENVSTEALTH = "ENV shows stealth monsters"; +GLPREFMNU_SPRBRIGHTFOG = "Force brightness in fog"; +GLPREFMNU_SPRCLIP = "Adjust sprite clipping"; +GLPREFMNU_SPRBLEND = "Smooth sprite edges"; +GLPREFMNU_FUZZSTYLE = "Fuzz Style"; +GLPREFMNU_SPRBILLBOARD = "Sprite billboard"; +GLPREFMNU_SPRBILLFACECAMERA = "Sprites face camera"; +GLPREFMNU_PARTICLESTYLE = "Particle style"; +GLPREFMNU_AMBLIGHT = "Ambient light level"; +GLPREFMNU_RENDERQUALITY = "Rendering quality"; +GLPREFMNU_VRMODE = "Stereo 3D VR"; +GLPREFMNU_VRQUADSTEREO = "Enable Quad Stereo"; +GLPREFMNU_MULTISAMPLE = "Multisample"; +GLPREFMNU_TONEMAP = "Tonemap Mode"; +GLPREFMNU_BLOOM = "Bloom effect"; +GLPREFMNU_LENS = "Lens distortion effect"; +GLPREFMNU_SSAO = "Ambient occlusion quality"; +GLPREFMNU_SSAO_PORTALS = "Portals with AO"; +GLPREFMNU_FXAA = "FXAA Quality"; + +// Option Values +OPTVAL_SMART = "Smart"; +OPTVAL_SMARTER = "Smarter"; +OPTVAL_INFRAREDONLY = "Infrared only"; +OPTVAL_INFRAREDANDTORCH = "Infrared and torch"; +OPTVAL_ANYFIXEDCOLORMAP = "Any fixed colormap"; +OPTVAL_NONENEARESTMIPMAP = "None (nearest mipmap)"; +OPTVAL_NONELINEARMIPMAP = "None (linear mipmap)"; +OPTVAL_NONETRILINEAR = "None (trilinear)"; +OPTVAL_BILINEAR = "Bilinear"; +OPTVAL_TRILINEAR = "Trilinear"; +OPTVAL_RGBA8 = "RGBA8"; +OPTVAL_RGB5A1 = "RGB5_A1"; +OPTVAL_RGBA4 = "RGBA4"; +OPTVAL_RGBA2 = "RGBA2"; +OPTVAL_COMPRRGBA = "COMPR_RGBA"; +OPTVAL_S3TCDXT1 = "S3TC_DXT1"; +OPTVAL_S3TCDXT3 = "S3TC_DXT3"; +OPTVAL_S3TCDXT5 = "S3TC_DXT5"; +OPTVAL_2X = "2x"; +OPTVAL_4X = "4x"; +OPTVAL_8X = "8x"; +OPTVAL_16X = "16x"; +OPTVAL_32X = "32x"; +OPTVAL_USEASPALETTE = "Use as palette"; +OPTVAL_BLEND = "Blend"; +OPTVAL_STANDARD = "Standard"; +OPTVAL_BRIGHT = "Bright"; +OPTVAL_DARK = "Dark"; +OPTVAL_LEGACY = "Legacy"; +OPTVAL_SOFTWARE = "Software"; +OPTVAL_SPEED = "Speed"; +OPTVAL_QUALITY = "Quality"; +OPTVAL_OPTIMAL = "Optimal"; +OPTVAL_60 = "60"; +OPTVAL_70 = "70"; +OPTVAL_72 = "72"; +OPTVAL_75 = "75"; +OPTVAL_85 = "85"; +OPTVAL_100 = "100"; +OPTVAL_YAXIS = "Y Axis"; +OPTVAL_XYAXIS = "X/Y Axis"; +OPTVAL_SQUARE = "Square"; +OPTVAL_ROUND = "Round"; +OPTVAL_SCALE2X = "Scale2x"; +OPTVAL_SCALE3X = "Scale3x"; +OPTVAL_SCALE4X = "Scale4x"; +OPTVAL_HQ2X = "hq2x"; +OPTVAL_HQ3X = "hq3x"; +OPTVAL_HQ4X = "hq4x"; +OPTVAL_HQ2XMMX = "hq2x MMX"; +OPTVAL_HQ3XMMX = "hq3x MMX"; +OPTVAL_HQ4XMMX = "hq4x MMX"; +OPTVAL_RADIAL = "Radial"; +OPTVAL_PIXELFUZZ = "Pixel fuzz"; +OPTVAL_SMOOTHFUZZ = "Smooth fuzz"; +OPTVAL_SWIRLYFUZZ = "Swirly fuzz"; +OPTVAL_TRANSLUCENTFUZZ = "Translucent fuzz"; +OPTVAL_NOISE = "Noise"; +OPTVAL_SMOOTHNOISE = "Smooth Noise"; +OPTVAL_JAGGEDFUZZ = "Jagged fuzz"; +OPTVAL_NORMAL = "Normal"; +OPTVAL_GREENMAGENTA = "Green/Magenta"; +OPTVAL_REDCYAN = "Red/Cyan"; +OPTVAL_AMBERBLUE = "Amber/Blue"; +OPTVAL_LEFTEYE = "Left Eye"; +OPTVAL_RIGHTEYE = "Right Eye"; +OPTVAL_SBSFULL = "Side-by-side Full"; +OPTVAL_SBSNARROW = "Side-by-side Narrow"; +OPTVAL_TOPBOTTOM = "Top/Bottom"; +OPTVAL_ROWINTERLEAVED = "Row Interleaved"; +OPTVAL_COLUMNINTERLEAVED = "Column Interleaved"; +OPTVAL_CHECKERBOARD = "Checkerboard"; +OPTVAL_QUADBUFFERED = "Quad-buffered"; +OPTVAL_UNCHARTED2 = "Uncharted 2"; +OPTVAL_HEJLDAWSON = "Hejl Dawson"; +OPTVAL_REINHARD = "Reinhard"; +OPTVAL_PALETTE = "Palette"; +OPTVAL_LOW = "Low"; +OPTVAL_MEDIUM = "Medium"; +OPTVAL_HIGH = "High"; +OPTVAL_EXTREME = "Extreme"; + +// QZDoom exclusive: + +DSPLYMNU_TCOPT = "TrueColor Options"; + +TCMNU_TITLE = "TRUECOLOR OPTIONS"; + + +TCMNU_MULTITHREADED = "Multithreaded Drawing"; +TCMNU_TRUECOLOR = "True color output"; +TCMNU_MINFILTER = "Linear filter when downscaling"; +TCMNU_MAGFILTER = "Linear filter when upscaling"; +TCMNU_MIPMAP = "Use mipmapped textures"; +TCMNU_DYNLIGHTS = "Dynamic lights"; + diff --git a/wadsrc/static/mapinfo/common.txt b/wadsrc/static/mapinfo/common.txt index 986b8e48c..5782f8808 100644 --- a/wadsrc/static/mapinfo/common.txt +++ b/wadsrc/static/mapinfo/common.txt @@ -30,8 +30,8 @@ DoomEdNums 1411 = "$SSeqOverride" 1500 = "$VavoomFloor" 1501 = "$VavoomCeiling" - 1502 = none - 1503 = none + 1502 = VavoomLightWhite + 1503 = VavoomLightColor 1504 = "$VertexFloorZ" 1505 = "$VertexCeilingZ" 5001 = PointPusher @@ -88,22 +88,27 @@ DoomEdNums 9503 = "$SetCeilingSlope" 9510 = "$CopyFloorPlane" 9511 = "$CopyCeilingPlane" - 9800 = none - 9801 = none - 9802 = none - 9803 = none - 9804 = none - 9810 = none - 9811 = none - 9812 = none - 9813 = none - 9814 = none - 9820 = none - 9821 = none - 9822 = none - 9823 = none - 9824 = none - 9825 = none + 9800 = PointLight + 9801 = PointLightPulse + 9802 = PointLightFlicker + 9803 = SectorPointLight + 9804 = PointLightFlickerRandom + 9810 = PointLightAdditive + 9811 = PointLightPulseAdditive + 9812 = PointLightFlickerAdditive + 9813 = SectorPointLightAdditive + 9814 = PointLightFlickerRandomAdditive + 9820 = PointLightSubtractive + 9821 = PointLightPulseSubtractive + 9822 = PointLightFlickerSubtractive + 9823 = SectorPointLightSubtractive + 9824 = PointLightFlickerRandomSubtractive + 9825 = VavoomLight + 9830 = PointLightAttenuated + 9831 = PointLightPulseAttenuated + 9832 = PointLightFlickerAttenuated + 9833 = SectorPointLightAttenuated + 9834 = PointLightFlickerRandomAttenuated 9982 = SecActEyesAboveC 9983 = SecActEyesBelowC 9988 = CustomSprite diff --git a/wadsrc/static/menudef.txt b/wadsrc/static/menudef.txt index 30cad4dd2..314534bb7 100644 --- a/wadsrc/static/menudef.txt +++ b/wadsrc/static/menudef.txt @@ -345,6 +345,7 @@ OptionMenu "OptionsMenu" Submenu "$OPTMNU_SOUND", "SoundOptions" Submenu "$OPTMNU_DISPLAY", "VideoOptions" Submenu "$OPTMNU_VIDEO", "VideoModeMenu" + Submenu "$OPTMNU_CHANGERENDER", "RendererMenu" StaticText " " SafeCommand "$OPTMNU_DEFAULTS", "reset2defaults" SafeCommand "$OPTMNU_RESETTOSAVED", "reset2saved" @@ -600,6 +601,12 @@ OptionValue ColumnMethods 1.0, "$OPTVAL_OPTIMIZED" } +OptionValue BlendMethods +{ + 0.0, "$OPTVAL_CLASSIC" + 1.0, "$OPTVAL_PRECISE" +} + OptionValue SkyModes { 0.0, "$OPTVAL_NORMAL" @@ -657,20 +664,47 @@ OptionValue Fuzziness 2.0, "$OPTVAL_SHADOW" } +OptionMenu "OpenGLOptions" +{ + Title "$GLMNU_TITLE" + Submenu "$GLMNU_DYNLIGHT", "GLLightOptions" + Submenu "$GLMNU_TEXOPT", "GLTextureGLOptions" + Submenu "$GLMNU_PREFS", "GLPrefOptions" +} + +OptionMenu "TrueColorOptions" +{ + Title "$TCMNU_TITLE" + Option "$TCMNU_MULTITHREADED", "r_multithreaded", "OnOff" + StaticText " " + //Option "$TCMNU_TRUECOLOR", "swtruecolor", "OnOff" + Option "$TCMNU_MINFILTER", "r_minfilter", "OnOff" + Option "$TCMNU_MAGFILTER", "r_magfilter", "OnOff" + Option "$TCMNU_MIPMAP", "r_mipmap", "OnOff" + Option "$TCMNU_DYNLIGHTS", "r_dynlights", "OnOff" +} + OptionMenu "VideoOptions" { Title "$DSPLYMNU_TITLE" + Submenu "$DSPLYMNU_GLOPT", "OpenGLOptions" + Submenu "$DSPLYMNU_TCOPT", "TrueColorOptions" Submenu "$DSPLYMNU_SCOREBOARD", "ScoreboardOptions" StaticText " " Slider "$DSPLYMNU_SCREENSIZE", "screenblocks", 3.0, 12.0, 1.0, 0 - Slider "$DSPLYMNU_BRIGHTNESS", "Gamma", 0.75, 3.0, 0.05, 2 + + Slider "$DSPLYMNU_GAMMA", "Gamma", 0.75, 3.0, 0.05, 2 + Slider "$DSPLYMNU_BRIGHTNESS", "vid_brightness", -0.8,0.8, 0.05,2 + Slider "$DSPLYMNU_CONTRAST", "vid_contrast", 0.1, 3.0, 0.1 + Option "$DSPLYMNU_HWGAMMA", "vid_hwgamma", "HWGammaModes" + Option "$DSPLYMNU_VSYNC", "vid_vsync", "OnOff" Option "$DSPLYMNU_CAPFPS", "cl_capfps", "OffOn" Slider "$DSPLYMNU_BLOODFADE", "blood_fade_scalar", 0.0, 1.0, 0.05, 2 Slider "$DSPLYMNU_PICKUPFADE", "pickup_fade_scalar", 0.0, 1.0, 0.05, 2 Slider "$DSPLYMNU_WATERFADE", "underwater_fade_scalar", 0.0, 1.0, 0.05, 2 - Option "$DSPLYMNU_COLUMNMETHOD", "r_columnmethod", "ColumnMethods" + Option "$DSPLYMNU_BLENDMETHOD", "r_blendmethod", "BlendMethods" StaticText " " Option "$DSPLYMNU_WIPETYPE", "wipetype", "Wipes" @@ -683,6 +717,7 @@ OptionMenu "VideoOptions" } Option "$DSPLYMNU_SKYMODE", "r_skymode", "SkyModes" + Option "$DSPLYMNU_LINEARSKY", "r_linearsky", "OnOff" Option "$DSPLYMNU_GZDFULLBRIGHT", "r_fullbrightignoresectorcolor", "OnOff" Option "$DSPLYMNU_DRAWFUZZ", "r_drawfuzz", "Fuzziness" Slider "$DSPLYMNU_TRANSSOUL", "transsouls", 0.25, 1.0, 0.05, 2 @@ -1716,6 +1751,42 @@ OptionMenu ModReplayerOptions // the foo_dumb preferences in foobar2000. } +/*======================================= + * + * Change Renderer Menu + * + *=======================================*/ + +OptionValue "PolyDoom" +{ + 0, "$OPTVAL_SWDOOM" + 1, "$OPTVAL_HWPOLY" +} + +OptionValue "D3DGL" +{ + 0, "$OPTVAL_GL" + 1, "$OPTVAL_D3D" +} + +OptionValue "GLD3D" +{ + 0, "$OPTVAL_D3D" + 1, "$OPTVAL_GL" +} + +OptionMenu RendererMenu +{ + Title "$RNDMNU_TITLE" + Option "$RNDMNU_RENDERER", "vid_renderer", "PolyDoom" + Option "$RNDMNU_TRUECOLOR", "swtruecolor", "OnOff" + Option "$RNDMNU_POLY", "r_polyrenderer", "OnOff" + IfOption(Windows) + { + Option "$RNDMNU_CANVAS", "vid_used3d", "D3DGL" + } +} + /*======================================= * * Video mode menu diff --git a/wadsrc/static/menudef.zz b/wadsrc/static/menudef.zz new file mode 100644 index 000000000..599c28a2d --- /dev/null +++ b/wadsrc/static/menudef.zz @@ -0,0 +1,252 @@ +OptionValue "SpriteclipModes" +{ + 0, "$OPTVAL_NEVER" + 1, "$OPTVAL_SMART" + 2, "$OPTVAL_ALWAYS" + 3, "$OPTVAL_SMARTER" +} + +OptionValue "EnhancedStealth" +{ + 0, "$OPTVAL_NEVER" + 1, "$OPTVAL_INFRAREDONLY" + 2, "$OPTVAL_INFRAREDANDTORCH" + 3, "$OPTVAL_ANYFIXEDCOLORMAP" +} + +OptionValue "FilterModes" +{ + 0, "$OPTVAL_NONE" + 1, "$OPTVAL_NONENEARESTMIPMAP" + 5, "$OPTVAL_NONELINEARMIPMAP" + 6, "$OPTVAL_NONETRILINEAR" + 2, "$OPTVAL_LINEAR" + 3, "$OPTVAL_BILINEAR" + 4, "$OPTVAL_TRILINEAR" +} + +OptionValue "HWGammaModes" +{ + 0, "$OPTVAL_ON" + 1, "$OPTVAL_OFF" + 2, "$OPTVAL_FULLSCREENONLY" +} + +OptionValue "TonemapModes" +{ + 0, "$OPTVAL_OFF" + 1, "$OPTVAL_UNCHARTED2" + 2, "$OPTVAL_HEJLDAWSON" + 3, "$OPTVAL_REINHARD" + 4, "$OPTVAL_LINEAR" + 5, "$OPTVAL_PALETTE" +} + +OptionValue "SSAOModes" +{ + 0, "$OPTVAL_OFF" + 1, "$OPTVAL_LOW" + 2, "$OPTVAL_MEDIUM" + 3, "$OPTVAL_HIGH" +} + +OptionValue "FXAAQuality" +{ + 0, "$OPTVAL_OFF" + 1, "$OPTVAL_LOW" + 2, "$OPTVAL_MEDIUM" + 3, "$OPTVAL_HIGH" + 4, "$OPTVAL_EXTREME" +} + +OptionValue "TextureFormats" +{ + 0, "$OPTVAL_RGBA8" + 1, "$OPTVAL_RGB5A1" + 2, "$OPTVAL_RGBA4" + 3, "$OPTVAL_RGBA2" + // [BB] Added modes for texture compression. + 4, "$OPTVAL_COMPRRGBA" + 5, "$OPTVAL_S3TCDXT1" + 6, "$OPTVAL_S3TCDXT3" + 7, "$OPTVAL_S3TCDXT5" +} + +OptionValue "Anisotropy" +{ + 1, "$OPTVAL_OFF" + 2, "$OPTVAL_2X" + 4, "$OPTVAL_4X" + 8, "$OPTVAL_8X" + 16, "$OPTVAL_16X" +} + +OptionValue "Multisample" +{ + 1, "$OPTVAL_OFF" + 2, "$OPTVAL_2X" + 4, "$OPTVAL_4X" + 8, "$OPTVAL_8X" + 16, "$OPTVAL_16X" + 32, "$OPTVAL_32X" +} + +OptionValue "Colormaps" +{ + 0, "$OPTVAL_USEASPALETTE" + 1, "$OPTVAL_BLEND" +} + +OptionValue "LightingModes" +{ + 0, "$OPTVAL_STANDARD" + 1, "$OPTVAL_BRIGHT" + 2, "$OPTVAL_DOOM" + 3, "$OPTVAL_DARK" + 4, "$OPTVAL_LEGACY" + 8, "$OPTVAL_SOFTWARE" +} + +OptionValue "Precision" +{ + 0, "$OPTVAL_SPEED" + 1, "$OPTVAL_QUALITY" +} + + +OptionValue "Hz" +{ + 0, "$OPTVAL_OPTIMAL" + 60, "$OPTVAL_60" + 70, "$OPTVAL_70" + 72, "$OPTVAL_72" + 75, "$OPTVAL_75" + 85, "$OPTVAL_85" + 100, "$OPTVAL_100" +} + +OptionValue "BillboardModes" +{ + 0, "$OPTVAL_YAXIS" + 1, "$OPTVAL_XYAXIS" +} + + +OptionValue "Particles" +{ + 0, "$OPTVAL_SQUARE" + 1, "$OPTVAL_ROUND" + 2, "$OPTVAL_SMOOTH" +} + +OptionValue "HqResizeModes" +{ + 0, "$OPTVAL_OFF" + 1, "$OPTVAL_SCALE2X" + 2, "$OPTVAL_SCALE3X" + 3, "$OPTVAL_SCALE4X" + 4, "$OPTVAL_HQ2X" + 5, "$OPTVAL_HQ3X" + 6, "$OPTVAL_HQ4X" + 7, "$OPTVAL_HQ2XMMX" + 8, "$OPTVAL_HQ3XMMX" + 9, "$OPTVAL_HQ4XMMX" + 10, "xBRZ 2x" + 11, "xBRZ 3x" + 12, "xBRZ 4x" + 13, "xBRZ_old 2x" + 14, "xBRZ_old 3x" + 15, "xBRZ_old 4x" +} + +OptionValue "FogMode" +{ + 0, "$OPTVAL_OFF" + 1, "$OPTVAL_STANDARD" + 2, "$OPTVAL_RADIAL" +} + +OptionValue "FuzzStyle" +{ + 0, "$OPTVAL_SHADOW" + 1, "$OPTVAL_PIXELFUZZ" + 2, "$OPTVAL_SMOOTHFUZZ" + 3, "$OPTVAL_SWIRLYFUZZ" + 4, "$OPTVAL_TRANSLUCENTFUZZ" + 6, "$OPTVAL_NOISE" + 7, "$OPTVAL_SMOOTHNOISE" + //5, "$OPTVAL_JAGGEDFUZZ" I can't see any difference between this and 4 so it's disabled for now. +} + +OptionValue VRMode +{ + 0, "$OPTVAL_NORMAL" + 1, "$OPTVAL_GREENMAGENTA" + 2, "$OPTVAL_REDCYAN" + 9, "$OPTVAL_AMBERBLUE" + 3, "$OPTVAL_SBSFULL" + 4, "$OPTVAL_SBSNARROW" + 11, "$OPTVAL_TOPBOTTOM" + 12, "$OPTVAL_ROWINTERLEAVED" + 13, "$OPTVAL_COLUMNINTERLEAVED" + 14, "$OPTVAL_CHECKERBOARD" + 5, "$OPTVAL_LEFTEYE" + 6, "$OPTVAL_RIGHTEYE" + 7, "$OPTVAL_QUADBUFFERED" +} + +OptionMenu "GLTextureGLOptions" +{ + Title "$GLTEXMNU_TITLE" + Option "$GLTEXMNU_TEXENABLED", gl_texture, "YesNo" + Option "$GLTEXMNU_TEXFILTER", gl_texture_filter, "FilterModes" + Option "$GLTEXMNU_ANISOTROPIC", gl_texture_filter_anisotropic, "Anisotropy" + Option "$GLTEXMNU_TEXFORMAT", gl_texture_format, "TextureFormats" + Option "$GLTEXMNU_ENABLEHIRES", gl_texture_usehires, "YesNo" + Option "$GLTEXMNU_HQRESIZE", gl_texture_hqresize, "HqResizeModes" + Option "$GLTEXMNU_RESIZETEX", gl_texture_hqresize_textures, "OnOff" + Option "$GLTEXMNU_RESIZESPR", gl_texture_hqresize_sprites, "OnOff" + Option "$GLTEXMNU_RESIZEFNT", gl_texture_hqresize_fonts, "OnOff" + Option "$GLTEXMNU_PRECACHETEX", gl_precache, "YesNo" + Option "$GLTEXMNU_TRIMSPREDGE", gl_trimsprites, "OnOff" + Option "$GLTEXMNU_SORTDRAWLIST", gl_sort_textures, "YesNo" +} + +OptionMenu "GLLightOptions" +{ + Title "$GLLIGHTMNU_TITLE" + Option "$GLLIGHTMNU_LIGHTSENABLED", gl_lights, "YesNo" + Option "$GLLIGHTMNU_LIGHTDEFS", gl_attachedlights, "YesNo" + Option "$GLLIGHTMNU_CLIPLIGHTS", gl_lights_checkside, "YesNo" + Option "$GLLIGHTMNU_LIGHTSPRITES", gl_light_sprites, "YesNo" + Option "$GLLIGHTMNU_LIGHTPARTICLES", gl_light_particles, "YesNo" +} + +OptionMenu "GLPrefOptions" +{ + Title "$GLPREFMNU_TITLE" + Option "$GLPREFMNU_SECLIGHTMODE", gl_lightmode, "LightingModes" + Option "$GLPREFMNU_FOGMODE", gl_fogmode, "FogMode" + Option "$GLPREFMNU_FOGFORCEFULLBRIGHT", gl_brightfog, "YesNo" + Slider "$GLPREFMNU_WPNLIGHTSTR", gl_weaponlight, 0,32, 2 + Option "$GLPREFMNU_ENVIRONMENTMAPMIRROR", gl_mirror_envmap, "OnOff" + Option "$GLPREFMNU_ENV", gl_enhanced_nightvision, "OnOff" + Option "$GLPREFMNU_ENVSTEALTH", gl_enhanced_nv_stealth, "EnhancedStealth" + Option "$GLPREFMNU_SPRBRIGHTFOG", gl_spritebrightfog, "OnOff" + Option "$GLPREFMNU_SPRCLIP", gl_spriteclip, "SpriteclipModes" + Option "$GLPREFMNU_SPRBLEND", gl_sprite_blend, "OnOff" + Option "$GLPREFMNU_FUZZSTYLE", gl_fuzztype, "FuzzStyle" + Option "$GLPREFMNU_SPRBILLBOARD", gl_billboard_mode, "BillboardModes" + Option "$GLPREFMNU_SPRBILLFACECAMERA", gl_billboard_faces_camera, "OnOff" + Option "$GLPREFMNU_PARTICLESTYLE", gl_particles_style, "Particles" + Option "$GLPREFMNU_RENDERQUALITY", gl_render_precise, "Precision" + Option "$GLPREFMNU_VRMODE", vr_mode, "VRMode" + Option "$GLPREFMNU_VRQUADSTEREO", vr_enable_quadbuffered, "OnOff" + Option "$GLPREFMNU_MULTISAMPLE", gl_multisample, "Multisample" + Option "$GLPREFMNU_TONEMAP", gl_tonemap, "TonemapModes" + Option "$GLPREFMNU_BLOOM", gl_bloom, "OnOff" + Option "$GLPREFMNU_LENS", gl_lens, "OnOff" + Option "$GLPREFMNU_SSAO", gl_ssao, "SSAOModes" + Slider "$GLPREFMNU_SSAO_PORTALS", gl_ssao_portals, 0.0, 4.0, 1.0, 0 + Option "$GLPREFMNU_FXAA", gl_fxaa, "FXAAQuality" +} diff --git a/wadsrc/static/shaders/glsl/bloomcombine.fp b/wadsrc/static/shaders/glsl/bloomcombine.fp new file mode 100644 index 000000000..57496771c --- /dev/null +++ b/wadsrc/static/shaders/glsl/bloomcombine.fp @@ -0,0 +1,10 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D Bloom; + +void main() +{ + FragColor = vec4(texture(Bloom, TexCoord).rgb, 0.0); +} diff --git a/wadsrc/static/shaders/glsl/bloomextract.fp b/wadsrc/static/shaders/glsl/bloomextract.fp new file mode 100644 index 000000000..9c5aa0bea --- /dev/null +++ b/wadsrc/static/shaders/glsl/bloomextract.fp @@ -0,0 +1,15 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D SceneTexture; +uniform sampler2D ExposureTexture; +uniform vec2 Scale; +uniform vec2 Offset; + +void main() +{ + float exposureAdjustment = texture(ExposureTexture, vec2(0.5)).x; + vec4 color = texture(SceneTexture, Offset + TexCoord * Scale); + FragColor = max(vec4((color.rgb + vec3(0.001)) * exposureAdjustment - 1, 1), vec4(0)); +} diff --git a/wadsrc/static/shaders/glsl/burn.fp b/wadsrc/static/shaders/glsl/burn.fp new file mode 100644 index 000000000..f928fd8db --- /dev/null +++ b/wadsrc/static/shaders/glsl/burn.fp @@ -0,0 +1,15 @@ +uniform sampler2D tex; +uniform sampler2D texture2; +in vec4 vTexCoord; +in vec4 vColor; +out vec4 FragColor; + +void main() +{ + vec4 frag = vColor; + + vec4 t1 = texture(tex, vTexCoord.xy); + vec4 t2 = texture(texture2, vec2(vTexCoord.x, 1.0-vTexCoord.y)); + + FragColor = frag * vec4(t1.r, t1.g, t1.b, t2.a); +} diff --git a/wadsrc/static/shaders/glsl/colormap.fp b/wadsrc/static/shaders/glsl/colormap.fp new file mode 100644 index 000000000..e86429c37 --- /dev/null +++ b/wadsrc/static/shaders/glsl/colormap.fp @@ -0,0 +1,16 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D tex; +uniform vec4 uFixedColormapStart; +uniform vec4 uFixedColormapRange; + +void main() +{ + vec4 frag = texture(tex, TexCoord); + float gray = (frag.r * 0.3 + frag.g * 0.56 + frag.b * 0.14); + vec4 cm = uFixedColormapStart + gray * uFixedColormapRange; + FragColor = vec4(clamp(cm.rgb, 0.0, 1.0), frag.a); +} + diff --git a/wadsrc/static/shaders/glsl/depthblur.fp b/wadsrc/static/shaders/glsl/depthblur.fp new file mode 100644 index 000000000..7e3dad074 --- /dev/null +++ b/wadsrc/static/shaders/glsl/depthblur.fp @@ -0,0 +1,69 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D AODepthTexture; +uniform float BlurSharpness; +uniform vec2 InvFullResolution; +uniform float PowExponent; + +#define KERNEL_RADIUS 3.0 + +float CrossBilateralWeight(float r, float sampleDepth, float centerDepth) +{ + const float blurSigma = KERNEL_RADIUS * 0.5; + const float blurFalloff = 1.0 / (2.0 * blurSigma * blurSigma); + + float deltaZ = (sampleDepth - centerDepth) * BlurSharpness; + + return exp2(-r * r * blurFalloff - deltaZ * deltaZ); +} + +void ProcessSample(float ao, float z, float r, float centerDepth, inout float totalAO, inout float totalW) +{ + float w = CrossBilateralWeight(r, z, centerDepth); + totalAO += w * ao; + totalW += w; +} + +void ProcessRadius(vec2 deltaUV, float centerDepth, inout float totalAO, inout float totalW) +{ + for (float r = 1; r <= KERNEL_RADIUS; r += 1.0) + { + vec2 uv = r * deltaUV + TexCoord; + vec2 aoZ = texture(AODepthTexture, uv).xy; + ProcessSample(aoZ.x, aoZ.y, r, centerDepth, totalAO, totalW); + } +} + +vec2 ComputeBlur(vec2 deltaUV) +{ + vec2 aoZ = texture(AODepthTexture, TexCoord).xy; + + float totalAO = aoZ.x; + float totalW = 1.0; + + ProcessRadius(deltaUV, aoZ.y, totalAO, totalW); + ProcessRadius(-deltaUV, aoZ.y, totalAO, totalW); + + return vec2(totalAO / totalW, aoZ.y); +} + +vec2 BlurX() +{ + return ComputeBlur(vec2(InvFullResolution.x, 0.0)); +} + +float BlurY() +{ + return pow(clamp(ComputeBlur(vec2(0.0, InvFullResolution.y)).x, 0.0, 1.0), PowExponent); +} + +void main() +{ +#if defined(BLUR_HORIZONTAL) + FragColor = vec4(BlurX(), 0.0, 1.0); +#else + FragColor = vec4(BlurY(), 0.0, 0.0, 1.0); +#endif +} diff --git a/wadsrc/static/shaders/glsl/exposureaverage.fp b/wadsrc/static/shaders/glsl/exposureaverage.fp new file mode 100644 index 000000000..41c0909d2 --- /dev/null +++ b/wadsrc/static/shaders/glsl/exposureaverage.fp @@ -0,0 +1,23 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D ExposureTexture; + +void main() +{ +#if __VERSION__ < 400 + ivec2 size = textureSize(ExposureTexture, 0); + ivec2 tl = max(ivec2(TexCoord * vec2(size) - 0.5), ivec2(0)); + ivec2 br = min(tl + ivec2(1), size - ivec2(1)); + vec4 values = vec4( + texelFetch(ExposureTexture, tl, 0).x, + texelFetch(ExposureTexture, ivec2(tl.x, br.y), 0).x, + texelFetch(ExposureTexture, ivec2(br.x, tl.y), 0).x, + texelFetch(ExposureTexture, br, 0).x); +#else + vec4 values = textureGather(ExposureTexture, TexCoord); +#endif + + FragColor = vec4((values.x + values.y + values.z + values.w) * 0.25, 0.0, 0.0, 1.0); +} diff --git a/wadsrc/static/shaders/glsl/exposurecombine.fp b/wadsrc/static/shaders/glsl/exposurecombine.fp new file mode 100644 index 000000000..f806f8f86 --- /dev/null +++ b/wadsrc/static/shaders/glsl/exposurecombine.fp @@ -0,0 +1,16 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D ExposureTexture; +uniform float ExposureBase; +uniform float ExposureMin; +uniform float ExposureScale; +uniform float ExposureSpeed; + +void main() +{ + float light = texture(ExposureTexture, TexCoord).x; + float exposureAdjustment = 1.0 / max(ExposureBase + light * ExposureScale, ExposureMin); + FragColor = vec4(exposureAdjustment, 0.0, 0.0, ExposureSpeed); +} diff --git a/wadsrc/static/shaders/glsl/exposureextract.fp b/wadsrc/static/shaders/glsl/exposureextract.fp new file mode 100644 index 000000000..f673bf029 --- /dev/null +++ b/wadsrc/static/shaders/glsl/exposureextract.fp @@ -0,0 +1,13 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D SceneTexture; +uniform vec2 Scale; +uniform vec2 Offset; + +void main() +{ + vec4 color = texture(SceneTexture, Offset + TexCoord * Scale); + FragColor = vec4(max(max(color.r, color.g), color.b), 0.0, 0.0, 1.0); +} diff --git a/wadsrc/static/shaders/glsl/fogboundary.fp b/wadsrc/static/shaders/glsl/fogboundary.fp new file mode 100644 index 000000000..d8259c845 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fogboundary.fp @@ -0,0 +1,30 @@ +in vec4 pixelpos; +in vec2 glowdist; +out vec4 FragColor; + +//=========================================================================== +// +// Main shader routine +// +//=========================================================================== + +void main() +{ + float fogdist; + float fogfactor; + + // + // calculate fog factor + // + if (uFogEnabled == -1) + { + fogdist = pixelpos.w; + } + else + { + fogdist = max(16.0, distance(pixelpos.xyz, uCameraPos.xyz)); + } + fogfactor = exp2 (uFogDensity * fogdist); + FragColor = vec4(uFogColor.rgb, 1.0 - fogfactor); +} + diff --git a/wadsrc/static/shaders/glsl/func_brightmap.fp b/wadsrc/static/shaders/glsl/func_brightmap.fp new file mode 100644 index 000000000..8e5f44d04 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_brightmap.fp @@ -0,0 +1,12 @@ +uniform sampler2D texture2; + +vec4 ProcessTexel() +{ + return getTexel(vTexCoord.st); +} + +vec4 ProcessLight(vec4 color) +{ + vec4 brightpix = desaturate(texture(texture2, vTexCoord.st)); + return vec4(min (color.rgb + brightpix.rgb, 1.0), color.a); +} diff --git a/wadsrc/static/shaders/glsl/func_defaultlight.fp b/wadsrc/static/shaders/glsl/func_defaultlight.fp new file mode 100644 index 000000000..227d38c6a --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_defaultlight.fp @@ -0,0 +1,5 @@ + +vec4 ProcessLight(vec4 color) +{ + return color; +} diff --git a/wadsrc/static/shaders/glsl/func_normal.fp b/wadsrc/static/shaders/glsl/func_normal.fp new file mode 100644 index 000000000..184c14851 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_normal.fp @@ -0,0 +1,6 @@ + +vec4 ProcessTexel() +{ + return getTexel(vTexCoord.st); +} + diff --git a/wadsrc/static/shaders/glsl/func_notexture.fp b/wadsrc/static/shaders/glsl/func_notexture.fp new file mode 100644 index 000000000..9337ad6b1 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_notexture.fp @@ -0,0 +1,6 @@ + +vec4 ProcessTexel() +{ + return desaturate(uObjectColor); +} + diff --git a/wadsrc/static/shaders/glsl/func_warp1.fp b/wadsrc/static/shaders/glsl/func_warp1.fp new file mode 100644 index 000000000..891eaa936 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_warp1.fp @@ -0,0 +1,17 @@ +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + + const float pi = 3.14159265358979323846; + vec2 offset = vec2(0,0); + + offset.y = sin(pi * 2.0 * (texCoord.x + timer * 0.125)) * 0.1; + offset.x = sin(pi * 2.0 * (texCoord.y + timer * 0.125)) * 0.1; + + texCoord += offset; + + return getTexel(texCoord); +} + diff --git a/wadsrc/static/shaders/glsl/func_warp2.fp b/wadsrc/static/shaders/glsl/func_warp2.fp new file mode 100644 index 000000000..ee712593d --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_warp2.fp @@ -0,0 +1,17 @@ +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + + const float pi = 3.14159265358979323846; + vec2 offset = vec2(0.0,0.0); + + offset.y = 0.5 + sin(pi * 2.0 * (texCoord.y + timer * 0.61 + 900.0/8192.0)) + sin(pi * 2.0 * (texCoord.x * 2.0 + timer * 0.36 + 300.0/8192.0)); + offset.x = 0.5 + sin(pi * 2.0 * (texCoord.y + timer * 0.49 + 700.0/8192.0)) + sin(pi * 2.0 * (texCoord.x * 2.0 + timer * 0.49 + 1200.0/8192.0)); + + texCoord += offset * 0.025; + + return getTexel(texCoord); +} + diff --git a/wadsrc/static/shaders/glsl/func_warp3.fp b/wadsrc/static/shaders/glsl/func_warp3.fp new file mode 100644 index 000000000..a81969ca6 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_warp3.fp @@ -0,0 +1,18 @@ +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + + const float pi = 3.14159265358979323846; + vec2 offset = vec2(0.0,0.0); + + float siny = sin(pi * 2.0 * (texCoord.y * 2.0 + timer * 0.75)) * 0.03; + offset.y = siny + sin(pi * 2.0 * (texCoord.x + timer * 0.75)) * 0.03; + offset.x = siny + sin(pi * 2.0 * (texCoord.x + timer * 0.45)) * 0.02; + + texCoord += offset; + + return getTexel(texCoord); +} + diff --git a/wadsrc/static/shaders/glsl/func_wavex.fp b/wadsrc/static/shaders/glsl/func_wavex.fp new file mode 100644 index 000000000..e4230ae87 --- /dev/null +++ b/wadsrc/static/shaders/glsl/func_wavex.fp @@ -0,0 +1,13 @@ +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + + const float pi = 3.14159265358979323846; + + texCoord.x += sin(pi * 2.0 * (texCoord.y + timer * 0.125)) * 0.1; + + return getTexel(texCoord); +} + diff --git a/wadsrc/static/shaders/glsl/fuzz_jagged.fp b/wadsrc/static/shaders/glsl/fuzz_jagged.fp new file mode 100644 index 000000000..c088c7b30 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_jagged.fp @@ -0,0 +1,25 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + + vec2 texSplat; + const float pi = 3.14159265358979323846; + texSplat.x = texCoord.x + mod(sin(pi * 2.0 * (texCoord.y + timer * 2.0)),0.1) * 0.1; + texSplat.y = texCoord.y + mod(cos(pi * 2.0 * (texCoord.x + timer * 2.0)),0.1) * 0.1; + + vec4 basicColor = getTexel(texSplat); + + float texX = sin(texCoord.x * 100.0 + timer*5.0); + float texY = cos(texCoord.x * 100.0 + timer*5.0); + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + + float test = mod(timer*2.0+(vX + vY), 0.5); + + basicColor.a = basicColor.a * test; + + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_noise.fp b/wadsrc/static/shaders/glsl/fuzz_noise.fp new file mode 100644 index 000000000..17f15d03b --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_noise.fp @@ -0,0 +1,22 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + ivec2 texSize = textureSize(tex, 0); + + texCoord.x = float( int(texCoord.x * texSize.x) ) / texSize.x; + texCoord.y = float( int(texCoord.y * texSize.y) ) / texSize.y; + + float texX = sin(mod(texCoord.x * 100.0 + timer*5.0, 3.489)) + texCoord.x / 4.0; + float texY = cos(mod(texCoord.y * 100.0 + timer*5.0, 3.489)) + texCoord.y / 4.0; + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + + float test = mod(timer*2.0+(vX + vY), 0.5); + basicColor.a = basicColor.a * test; + basicColor.rgb = vec3(0.0,0.0,0.0); + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_smooth.fp b/wadsrc/static/shaders/glsl/fuzz_smooth.fp new file mode 100644 index 000000000..4261d5415 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_smooth.fp @@ -0,0 +1,19 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + + float texX = texCoord.x / 3.0 + 0.66; + float texY = 0.34 - texCoord.y / 3.0; + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + float test = mod(timer*2.0+(vX + vY), 0.5); + + basicColor.a = basicColor.a * test; + basicColor.r = basicColor.g = basicColor.b = 0.0; + + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_smoothnoise.fp b/wadsrc/static/shaders/glsl/fuzz_smoothnoise.fp new file mode 100644 index 000000000..bfe04ec16 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_smoothnoise.fp @@ -0,0 +1,20 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + + float texX = sin(mod(texCoord.x * 100.0 + timer*5.0, 3.489)) + texCoord.x / 4.0; + float texY = cos(mod(texCoord.y * 100.0 + timer*5.0, 3.489)) + texCoord.y / 4.0; + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + + + float test = mod(timer*2.0+(vX + vY), 0.5); + basicColor.a = basicColor.a * test; + + basicColor.rgb = vec3(0.0,0.0,0.0); + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_smoothtranslucent.fp b/wadsrc/static/shaders/glsl/fuzz_smoothtranslucent.fp new file mode 100644 index 000000000..75bee0330 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_smoothtranslucent.fp @@ -0,0 +1,19 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + + float texX = sin(texCoord.x * 100.0 + timer*5.0); + float texY = cos(texCoord.x * 100.0 + timer*5.0); + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + + float test = mod(timer*2.0+(vX + vY), 0.5); + + basicColor.a = basicColor.a * test; + + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_standard.fp b/wadsrc/static/shaders/glsl/fuzz_standard.fp new file mode 100644 index 000000000..95ba52431 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_standard.fp @@ -0,0 +1,23 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + ivec2 texSize = textureSize(tex, 0); + + texCoord.x = float( int(texCoord.x * texSize.x) ) / texSize.x; + texCoord.y = float( int(texCoord.y * texSize.y) ) / texSize.y; + + float texX = texCoord.x / 3.0 + 0.66; + float texY = 0.34 - texCoord.y / 3.0; + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + float test = mod(timer*2.0+(vX + vY), 0.5); + + basicColor.a = basicColor.a * test; + basicColor.r = basicColor.g = basicColor.b = 0.0; + + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fuzz_swirly.fp b/wadsrc/static/shaders/glsl/fuzz_swirly.fp new file mode 100644 index 000000000..86a66ac8e --- /dev/null +++ b/wadsrc/static/shaders/glsl/fuzz_swirly.fp @@ -0,0 +1,19 @@ +//created by Evil Space Tomato +uniform float timer; + +vec4 ProcessTexel() +{ + vec2 texCoord = vTexCoord.st; + vec4 basicColor = getTexel(texCoord); + + float texX = sin(texCoord.x * 100.0 + timer*5.0); + float texY = cos(texCoord.x * 100.0 + timer*5.0); + float vX = (texX/texY)*21.0; + float vY = (texY/texX)*13.0; + float test = mod(timer*2.0+(vX + vY), 0.5); + + basicColor.a = basicColor.a * test; + basicColor.r = basicColor.g = basicColor.b = 0.0; + + return basicColor; +} diff --git a/wadsrc/static/shaders/glsl/fxaa.fp b/wadsrc/static/shaders/glsl/fxaa.fp new file mode 100644 index 000000000..7fcdf8c81 --- /dev/null +++ b/wadsrc/static/shaders/glsl/fxaa.fp @@ -0,0 +1,615 @@ +//---------------------------------------------------------------------------------- +// File: es3-kepler\FXAA/FXAA3_11.h +// SDK Version: v3.00 +// Email: gameworks@nvidia.com +// Site: http://developer.nvidia.com/ +// +// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 COPYRIGHT OWNER OR +// CONTRIBUTORS 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. +// +//---------------------------------------------------------------------------------- + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D InputTexture; + +#ifdef FXAA_LUMA_PASS + +void main() +{ + vec3 tex = texture(InputTexture, TexCoord).rgb; + vec3 luma = vec3(0.299, 0.587, 0.114); + FragColor = vec4(tex, dot(tex, luma)); +} + +#else // FXAA itself + +//============================================================================ +// NVIDIA FXAA 3.11 by TIMOTHY LOTTES +//============================================================================ + +#define FXAA_DISCARD 1 + +#define FXAA_GREEN_AS_LUMA 0 + +#define FxaaBool bool +#define FxaaDiscard discard +#define FxaaFloat float +#define FxaaFloat2 vec2 +#define FxaaFloat3 vec3 +#define FxaaFloat4 vec4 +#define FxaaHalf float +#define FxaaHalf2 vec2 +#define FxaaHalf3 vec3 +#define FxaaHalf4 vec4 +#define FxaaInt2 ivec2 +#define FxaaSat(x) clamp(x, 0.0, 1.0) +#define FxaaTex sampler2D + +#define FxaaTexTop(t, p) textureLod(t, p, 0.0) +#define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o) + +#if (FXAA_GATHER4_ALPHA == 1) + #define FxaaTexAlpha4(t, p) textureGather(t, p, 3) + #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3) + #define FxaaTexGreen4(t, p) textureGather(t, p, 1) + #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1) +#endif + +#if (FXAA_GREEN_AS_LUMA == 0) + FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.w; } +#else + FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; } +#endif + +#if (FXAA_QUALITY__PRESET == 10) + #define FXAA_QUALITY__PS 3 + #define FXAA_QUALITY__P0 1.5 + #define FXAA_QUALITY__P1 3.0 + #define FXAA_QUALITY__P2 12.0 +#elif (FXAA_QUALITY__PRESET == 11) + #define FXAA_QUALITY__PS 4 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 3.0 + #define FXAA_QUALITY__P3 12.0 +#elif (FXAA_QUALITY__PRESET == 12) + #define FXAA_QUALITY__PS 5 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 4.0 + #define FXAA_QUALITY__P4 12.0 +#elif (FXAA_QUALITY__PRESET == 13) + #define FXAA_QUALITY__PS 6 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 4.0 + #define FXAA_QUALITY__P5 12.0 +#elif (FXAA_QUALITY__PRESET == 14) + #define FXAA_QUALITY__PS 7 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 4.0 + #define FXAA_QUALITY__P6 12.0 +#elif (FXAA_QUALITY__PRESET == 15) + #define FXAA_QUALITY__PS 8 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 4.0 + #define FXAA_QUALITY__P7 12.0 +#elif (FXAA_QUALITY__PRESET == 20) + #define FXAA_QUALITY__PS 3 + #define FXAA_QUALITY__P0 1.5 + #define FXAA_QUALITY__P1 2.0 + #define FXAA_QUALITY__P2 8.0 +#elif (FXAA_QUALITY__PRESET == 21) + #define FXAA_QUALITY__PS 4 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 8.0 +#elif (FXAA_QUALITY__PRESET == 22) + #define FXAA_QUALITY__PS 5 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 8.0 +#elif (FXAA_QUALITY__PRESET == 23) + #define FXAA_QUALITY__PS 6 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 8.0 +#elif (FXAA_QUALITY__PRESET == 24) + #define FXAA_QUALITY__PS 7 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 3.0 + #define FXAA_QUALITY__P6 8.0 +#elif (FXAA_QUALITY__PRESET == 25) + #define FXAA_QUALITY__PS 8 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 4.0 + #define FXAA_QUALITY__P7 8.0 +#elif (FXAA_QUALITY__PRESET == 26) + #define FXAA_QUALITY__PS 9 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 2.0 + #define FXAA_QUALITY__P7 4.0 + #define FXAA_QUALITY__P8 8.0 +#elif (FXAA_QUALITY__PRESET == 27) + #define FXAA_QUALITY__PS 10 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 2.0 + #define FXAA_QUALITY__P7 2.0 + #define FXAA_QUALITY__P8 4.0 + #define FXAA_QUALITY__P9 8.0 +#elif (FXAA_QUALITY__PRESET == 28) + #define FXAA_QUALITY__PS 11 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 2.0 + #define FXAA_QUALITY__P7 2.0 + #define FXAA_QUALITY__P8 2.0 + #define FXAA_QUALITY__P9 4.0 + #define FXAA_QUALITY__P10 8.0 +#elif (FXAA_QUALITY__PRESET == 29) + #define FXAA_QUALITY__PS 12 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.5 + #define FXAA_QUALITY__P2 2.0 + #define FXAA_QUALITY__P3 2.0 + #define FXAA_QUALITY__P4 2.0 + #define FXAA_QUALITY__P5 2.0 + #define FXAA_QUALITY__P6 2.0 + #define FXAA_QUALITY__P7 2.0 + #define FXAA_QUALITY__P8 2.0 + #define FXAA_QUALITY__P9 2.0 + #define FXAA_QUALITY__P10 4.0 + #define FXAA_QUALITY__P11 8.0 +#elif (FXAA_QUALITY__PRESET == 39) + #define FXAA_QUALITY__PS 12 + #define FXAA_QUALITY__P0 1.0 + #define FXAA_QUALITY__P1 1.0 + #define FXAA_QUALITY__P2 1.0 + #define FXAA_QUALITY__P3 1.0 + #define FXAA_QUALITY__P4 1.0 + #define FXAA_QUALITY__P5 1.5 + #define FXAA_QUALITY__P6 2.0 + #define FXAA_QUALITY__P7 2.0 + #define FXAA_QUALITY__P8 2.0 + #define FXAA_QUALITY__P9 2.0 + #define FXAA_QUALITY__P10 4.0 + #define FXAA_QUALITY__P11 8.0 +#endif + +FxaaFloat4 FxaaPixelShader(FxaaFloat2 pos, FxaaTex tex, FxaaFloat2 fxaaQualityRcpFrame, + FxaaFloat fxaaQualitySubpix, FxaaFloat fxaaQualityEdgeThreshold, FxaaFloat fxaaQualityEdgeThresholdMin) +{ + FxaaFloat2 posM; + posM.x = pos.x; + posM.y = pos.y; + #if (FXAA_GATHER4_ALPHA == 1) + #if (FXAA_DISCARD == 0) + FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); + #if (FXAA_GREEN_AS_LUMA == 0) + #define lumaM rgbyM.w + #else + #define lumaM rgbyM.y + #endif + #endif + #if (FXAA_GREEN_AS_LUMA == 0) + FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM); + FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1)); + #else + FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM); + FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1)); + #endif + #if (FXAA_DISCARD == 1) + #define lumaM luma4A.w + #endif + #define lumaE luma4A.z + #define lumaS luma4A.x + #define lumaSE luma4A.y + #define lumaNW luma4B.w + #define lumaN luma4B.z + #define lumaW luma4B.x + #else + FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); + #if (FXAA_GREEN_AS_LUMA == 0) + #define lumaM rgbyM.w + #else + #define lumaM rgbyM.y + #endif + FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy)); + #endif +/*--------------------------------------------------------------------------*/ + FxaaFloat maxSM = max(lumaS, lumaM); + FxaaFloat minSM = min(lumaS, lumaM); + FxaaFloat maxESM = max(lumaE, maxSM); + FxaaFloat minESM = min(lumaE, minSM); + FxaaFloat maxWN = max(lumaN, lumaW); + FxaaFloat minWN = min(lumaN, lumaW); + FxaaFloat rangeMax = max(maxWN, maxESM); + FxaaFloat rangeMin = min(minWN, minESM); + FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; + FxaaFloat range = rangeMax - rangeMin; + FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); + FxaaBool earlyExit = range < rangeMaxClamped; +/*--------------------------------------------------------------------------*/ + if(earlyExit) + #if (FXAA_DISCARD == 1) + FxaaDiscard; + #else + return rgbyM; + #endif +/*--------------------------------------------------------------------------*/ + #if (FXAA_GATHER4_ALPHA == 0) + FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); + #else + FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy)); + FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); + #endif +/*--------------------------------------------------------------------------*/ + FxaaFloat lumaNS = lumaN + lumaS; + FxaaFloat lumaWE = lumaW + lumaE; + FxaaFloat subpixRcpRange = 1.0/range; + FxaaFloat subpixNSWE = lumaNS + lumaWE; + FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS; + FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE; +/*--------------------------------------------------------------------------*/ + FxaaFloat lumaNESE = lumaNE + lumaSE; + FxaaFloat lumaNWNE = lumaNW + lumaNE; + FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE; + FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE; +/*--------------------------------------------------------------------------*/ + FxaaFloat lumaNWSW = lumaNW + lumaSW; + FxaaFloat lumaSWSE = lumaSW + lumaSE; + FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); + FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); + FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; + FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE; + FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4; + FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4; +/*--------------------------------------------------------------------------*/ + FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE; + FxaaFloat lengthSign = fxaaQualityRcpFrame.x; + FxaaBool horzSpan = edgeHorz >= edgeVert; + FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; +/*--------------------------------------------------------------------------*/ + if(!horzSpan) lumaN = lumaW; + if(!horzSpan) lumaS = lumaE; + if(horzSpan) lengthSign = fxaaQualityRcpFrame.y; + FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM; +/*--------------------------------------------------------------------------*/ + FxaaFloat gradientN = lumaN - lumaM; + FxaaFloat gradientS = lumaS - lumaM; + FxaaFloat lumaNN = lumaN + lumaM; + FxaaFloat lumaSS = lumaS + lumaM; + FxaaBool pairN = abs(gradientN) >= abs(gradientS); + FxaaFloat gradient = max(abs(gradientN), abs(gradientS)); + if(pairN) lengthSign = -lengthSign; + FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); +/*--------------------------------------------------------------------------*/ + FxaaFloat2 posB; + posB.x = posM.x; + posB.y = posM.y; + FxaaFloat2 offNP; + offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; + offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; + if(!horzSpan) posB.x += lengthSign * 0.5; + if( horzSpan) posB.y += lengthSign * 0.5; +/*--------------------------------------------------------------------------*/ + FxaaFloat2 posN; + posN.x = posB.x - offNP.x * FXAA_QUALITY__P0; + posN.y = posB.y - offNP.y * FXAA_QUALITY__P0; + FxaaFloat2 posP; + posP.x = posB.x + offNP.x * FXAA_QUALITY__P0; + posP.y = posB.y + offNP.y * FXAA_QUALITY__P0; + FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0; + FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN)); + FxaaFloat subpixE = subpixC * subpixC; + FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP)); +/*--------------------------------------------------------------------------*/ + if(!pairN) lumaNN = lumaSS; + FxaaFloat gradientScaled = gradient * 1.0/4.0; + FxaaFloat lumaMM = lumaM - lumaNN * 0.5; + FxaaFloat subpixF = subpixD * subpixE; + FxaaBool lumaMLTZero = lumaMM < 0.0; +/*--------------------------------------------------------------------------*/ + lumaEndN -= lumaNN * 0.5; + lumaEndP -= lumaNN * 0.5; + FxaaBool doneN = abs(lumaEndN) >= gradientScaled; + FxaaBool doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P1; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P1; + FxaaBool doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P1; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P1; +/*--------------------------------------------------------------------------*/ + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P2; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P2; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P2; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P2; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 3) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P3; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P3; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P3; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P3; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 4) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P4; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P4; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P4; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P4; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 5) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P5; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P5; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P5; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P5; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 6) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P6; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P6; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P6; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P6; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 7) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P7; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P7; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P7; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P7; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 8) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P8; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P8; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P8; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P8; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 9) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P9; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P9; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P9; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P9; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 10) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P10; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P10; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P10; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P10; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 11) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P11; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P11; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P11; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P11; +/*--------------------------------------------------------------------------*/ + #if (FXAA_QUALITY__PS > 12) + if(doneNP) { + if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; + if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if(!doneN) posN.x -= offNP.x * FXAA_QUALITY__P12; + if(!doneN) posN.y -= offNP.y * FXAA_QUALITY__P12; + doneNP = (!doneN) || (!doneP); + if(!doneP) posP.x += offNP.x * FXAA_QUALITY__P12; + if(!doneP) posP.y += offNP.y * FXAA_QUALITY__P12; +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } + #endif +/*--------------------------------------------------------------------------*/ + } +/*--------------------------------------------------------------------------*/ + FxaaFloat dstN = posM.x - posN.x; + FxaaFloat dstP = posP.x - posM.x; + if(!horzSpan) dstN = posM.y - posN.y; + if(!horzSpan) dstP = posP.y - posM.y; +/*--------------------------------------------------------------------------*/ + FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; + FxaaFloat spanLength = (dstP + dstN); + FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; + FxaaFloat spanLengthRcp = 1.0/spanLength; +/*--------------------------------------------------------------------------*/ + FxaaBool directionN = dstN < dstP; + FxaaFloat dst = min(dstN, dstP); + FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP; + FxaaFloat subpixG = subpixF * subpixF; + FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5; + FxaaFloat subpixH = subpixG * fxaaQualitySubpix; +/*--------------------------------------------------------------------------*/ + FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0; + FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH); + if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign; + if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign; + #if (FXAA_DISCARD == 1) + return FxaaTexTop(tex, posM); + #else + return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM); + #endif +} + +uniform vec2 ReciprocalResolution; + +void main() +{ + FragColor = FxaaPixelShader(TexCoord, InputTexture, ReciprocalResolution, 0.75f, 0.166f, 0.0833f); +} + +#endif // FXAA_LUMA_PASS diff --git a/wadsrc/static/shaders/glsl/lensdistortion.fp b/wadsrc/static/shaders/glsl/lensdistortion.fp new file mode 100644 index 000000000..7facf5a80 --- /dev/null +++ b/wadsrc/static/shaders/glsl/lensdistortion.fp @@ -0,0 +1,58 @@ +/* + Original Lens Distortion Algorithm from SSontech + http://www.ssontech.com/content/lensalg.htm + + If (u,v) are the coordinates of a feature in the undistorted perfect + image plane, then (u', v') are the coordinates of the feature on the + distorted image plate, ie the scanned or captured image from the + camera. The distortion occurs radially away from the image center, + with correction for the image aspect ratio (image_aspect = physical + image width/height), as follows: + + r2 = image_aspect*image_aspect*u*u + v*v + f = 1 + r2*(k + kcube*sqrt(r2)) + u' = f*u + v' = f*v + + The constant k is the distortion coefficient that appears on the lens + panel and through Sizzle. It is generally a small positive or negative + number under 1%. The constant kcube is the cubic distortion value found + on the image preprocessor's lens panel: it can be used to undistort or + redistort images, but it does not affect or get computed by the solver. + When no cubic distortion is needed, neither is the square root, saving + time. + + Chromatic Aberration example, + using red distord channel with green and blue undistord channel: + + k = vec3(-0.15, 0.0, 0.0); + kcube = vec3(0.15, 0.0, 0.0); +*/ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D InputTexture; +uniform float Aspect; // image width/height +uniform float Scale; // 1/max(f) +uniform vec4 k; // lens distortion coefficient +uniform vec4 kcube; // cubic distortion value + +void main() +{ + vec2 position = (TexCoord - vec2(0.5)); + + vec2 p = vec2(position.x * Aspect, position.y); + float r2 = dot(p, p); + vec3 f = vec3(1.0) + r2 * (k.rgb + kcube.rgb * sqrt(r2)); + + vec3 x = f * position.x * Scale + 0.5; + vec3 y = f * position.y * Scale + 0.5; + + vec3 c; + c.r = texture(InputTexture, vec2(x.r, y.r)).r; + c.g = texture(InputTexture, vec2(x.g, y.g)).g; + c.b = texture(InputTexture, vec2(x.b, y.b)).b; + + FragColor = vec4(c, 1.0); +} diff --git a/wadsrc/static/shaders/glsl/lineardepth.fp b/wadsrc/static/shaders/glsl/lineardepth.fp new file mode 100644 index 000000000..3e2b3eb95 --- /dev/null +++ b/wadsrc/static/shaders/glsl/lineardepth.fp @@ -0,0 +1,46 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +#if defined(MULTISAMPLE) +uniform sampler2DMS DepthTexture; +uniform sampler2DMS ColorTexture; +uniform int SampleIndex; +#else +uniform sampler2D DepthTexture; +uniform sampler2D ColorTexture; +#endif + +uniform float LinearizeDepthA; +uniform float LinearizeDepthB; +uniform float InverseDepthRangeA; +uniform float InverseDepthRangeB; +uniform vec2 Scale; +uniform vec2 Offset; + +float normalizeDepth(float depth) +{ + float normalizedDepth = clamp(InverseDepthRangeA * depth + InverseDepthRangeB, 0.0, 1.0); + return 1.0 / (normalizedDepth * LinearizeDepthA + LinearizeDepthB); +} + +void main() +{ + vec2 uv = Offset + TexCoord * Scale; + +#if defined(MULTISAMPLE) + ivec2 texSize = textureSize(DepthTexture); +#else + ivec2 texSize = textureSize(DepthTexture, 0); +#endif + + ivec2 ipos = ivec2(max(uv * vec2(texSize), vec2(0.0))); + +#if defined(MULTISAMPLE) + float depth = normalizeDepth(texelFetch(ColorTexture, ipos, SampleIndex).a != 0.0 ? texelFetch(DepthTexture, ipos, SampleIndex).x : 1.0); +#else + float depth = normalizeDepth(texelFetch(ColorTexture, ipos, 0).a != 0.0 ? texelFetch(DepthTexture, ipos, 0).x : 1.0); +#endif + + FragColor = vec4(depth, 0.0, 0.0, 1.0); +} diff --git a/wadsrc/static/shaders/glsl/main.fp b/wadsrc/static/shaders/glsl/main.fp new file mode 100644 index 000000000..5834dcf5d --- /dev/null +++ b/wadsrc/static/shaders/glsl/main.fp @@ -0,0 +1,419 @@ +in vec4 pixelpos; +in vec2 glowdist; + +in vec4 vWorldNormal; +in vec4 vEyeNormal; +in vec4 vTexCoord; +in vec4 vColor; + +out vec4 FragColor; +#ifdef GBUFFER_PASS +out vec4 FragFog; +out vec4 FragNormal; +#endif + +#ifdef SHADER_STORAGE_LIGHTS + layout(std430, binding = 1) buffer LightBufferSSO + { + vec4 lights[]; + }; +#elif defined NUM_UBO_LIGHTS + /*layout(std140)*/ uniform LightBufferUBO + { + vec4 lights[NUM_UBO_LIGHTS]; + }; +#endif + + +uniform sampler2D tex; + +vec4 Process(vec4 color); +vec4 ProcessTexel(); +vec4 ProcessLight(vec4 color); + + +//=========================================================================== +// +// Desaturate a color +// +//=========================================================================== + +vec4 desaturate(vec4 texel) +{ + if (uDesaturationFactor > 0.0) + { + float gray = (texel.r * 0.3 + texel.g * 0.56 + texel.b * 0.14); + return mix (texel, vec4(gray,gray,gray,texel.a), uDesaturationFactor); + } + else + { + return texel; + } +} + +//=========================================================================== +// +// This function is common for all (non-special-effect) fragment shaders +// +//=========================================================================== + +vec4 getTexel(vec2 st) +{ + vec4 texel = texture(tex, st); + + // + // Apply texture modes + // + switch (uTextureMode) + { + case 1: // TM_MASK + texel.rgb = vec3(1.0,1.0,1.0); + break; + + case 2: // TM_OPAQUE + texel.a = 1.0; + break; + + case 3: // TM_INVERSE + texel = vec4(1.0-texel.r, 1.0-texel.b, 1.0-texel.g, texel.a); + break; + + case 4: // TM_REDTOALPHA + texel = vec4(1.0, 1.0, 1.0, texel.r*texel.a); + break; + + case 5: // TM_CLAMPY + if (st.t < 0.0 || st.t > 1.0) + { + texel.a = 0.0; + } + break; + } + texel *= uObjectColor; + + return desaturate(texel); +} + +//=========================================================================== +// +// Doom lighting equation exactly as calculated by zdoom. +// +//=========================================================================== +float R_DoomLightingEquation(float light) +{ + // Calculated from r_visibility. It differs between walls, floor and sprites. + // + // Wall: globVis = r_WallVisibility + // Floor: r_FloorVisibility / abs(plane.Zat0 - ViewPos.Z) + // Sprite: same as wall + // All are calculated in R_SetVisibility and seem to be decided by the + // aspect ratio amongst other things. + // + // 1706 is the value for walls on 1080p 16:9 displays. + float globVis = 1706.0; + + /* L is the integer light level used in the game */ + float L = light * 255.0; + + /* z is the depth in view/eye space, positive going into the screen */ + float z = pixelpos.w; + + /* The zdoom light equation */ + float vis = globVis / z; + float shade = 64.0 - (L + 12.0) * 32.0/128.0; + float lightscale = clamp((shade - min(24.0, vis)) / 32.0, 0.0, 31.0/32.0); + + // Result is the normalized colormap index (0 bright .. 1 dark) + return lightscale; +} + +//=========================================================================== +// +// Standard lambertian diffuse light calculation +// +//=========================================================================== + +float diffuseContribution(vec3 lightDirection, vec3 normal) +{ + return max(dot(normal, lightDirection), 0.0f); +} + +//=========================================================================== +// +// Calculates the brightness of a dynamic point light +// Todo: Find a better way to define which lighting model to use. +// (Specular mode has been removed for now.) +// +//=========================================================================== + +float pointLightAttenuation(vec4 lightpos, float attenuate) +{ + float attenuation = max(lightpos.w - distance(pixelpos.xyz, lightpos.xyz),0.0) / lightpos.w; + if (attenuate == 0.0) + { + return attenuation; + } + else + { + vec3 lightDirection = normalize(lightpos.xyz - pixelpos.xyz); + float diffuseAmount = diffuseContribution(lightDirection, normalize(vWorldNormal.xyz)); + return attenuation * diffuseAmount; + } +} + +//=========================================================================== +// +// Calculate light +// +// It is important to note that the light color is not desaturated +// due to ZDoom's implementation weirdness. Everything that's added +// on top of it, e.g. dynamic lights and glows are, though, because +// the objects emitting these lights are also. +// +// This is making this a bit more complicated than it needs to +// because we can't just desaturate the final fragment color. +// +//=========================================================================== + +vec4 getLightColor(float fogdist, float fogfactor) +{ + vec4 color = vColor; + + if (uLightLevel >= 0.0) + { + float newlightlevel = 1.0 - R_DoomLightingEquation(uLightLevel); + color.rgb *= newlightlevel; + } + else if (uFogEnabled > 0) + { + // brightening around the player for light mode 2 + if (fogdist < uLightDist) + { + color.rgb *= uLightFactor - (fogdist / uLightDist) * (uLightFactor - 1.0); + } + + // + // apply light diminishing through fog equation + // + color.rgb = mix(vec3(0.0, 0.0, 0.0), color.rgb, fogfactor); + } + + // + // handle glowing walls + // + if (uGlowTopColor.a > 0.0 && glowdist.x < uGlowTopColor.a) + { + color.rgb += desaturate(uGlowTopColor * (1.0 - glowdist.x / uGlowTopColor.a)).rgb; + } + if (uGlowBottomColor.a > 0.0 && glowdist.y < uGlowBottomColor.a) + { + color.rgb += desaturate(uGlowBottomColor * (1.0 - glowdist.y / uGlowBottomColor.a)).rgb; + } + color = min(color, 1.0); + + // + // apply brightmaps (or other light manipulation by custom shaders. + // + color = ProcessLight(color); + + // + // apply dynamic lights (except additive) + // + + vec4 dynlight = uDynLightColor; + +#if defined NUM_UBO_LIGHTS || defined SHADER_STORAGE_LIGHTS + if (uLightIndex >= 0) + { + ivec4 lightRange = ivec4(lights[uLightIndex]) + ivec4(uLightIndex + 1); + if (lightRange.z > lightRange.x) + { + // + // modulated lights + // + for(int i=lightRange.x; i= 0) + { + ivec4 lightRange = ivec4(lights[uLightIndex]) + ivec4(uLightIndex + 1); + if (lightRange.w > lightRange.z) + { + vec4 addlight = vec4(0.0,0.0,0.0,0.0); + + // + // additive lights - these can be done after the alpha test. + // + for(int i=lightRange.z; i -1000000.0) // and for line portals - this will never be active at the same time as the reflective planes clipping so it can use the same hardware clip plane. + { + gl_ClipDistance[0] = -( (worldcoord.z - uClipLine.y) * uClipLine.z + (uClipLine.x - worldcoord.x) * uClipLine.w ) + 1.0/32768.0; // allow a tiny bit of imprecisions for colinear linedefs. + } + + // clip planes used for translucency splitting + gl_ClipDistance[1] = worldcoord.y - uClipSplit.x; + gl_ClipDistance[2] = uClipSplit.y - worldcoord.y; + +} diff --git a/wadsrc/static/shaders/glsl/present.fp b/wadsrc/static/shaders/glsl/present.fp new file mode 100644 index 000000000..31c1217cb --- /dev/null +++ b/wadsrc/static/shaders/glsl/present.fp @@ -0,0 +1,21 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D InputTexture; +uniform float InvGamma; +uniform float Contrast; +uniform float Brightness; + +vec4 ApplyGamma(vec4 c) +{ + vec3 val = c.rgb * Contrast - (Contrast - 1.0) * 0.5; + val += Brightness * 0.5; + val = pow(max(val, vec3(0.0)), vec3(InvGamma)); + return vec4(val, c.a); +} + +void main() +{ + FragColor = ApplyGamma(texture(InputTexture, TexCoord)); +} diff --git a/wadsrc/static/shaders/glsl/present_checker3d.fp b/wadsrc/static/shaders/glsl/present_checker3d.fp new file mode 100644 index 000000000..5247261e0 --- /dev/null +++ b/wadsrc/static/shaders/glsl/present_checker3d.fp @@ -0,0 +1,37 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D LeftEyeTexture; +uniform sampler2D RightEyeTexture; +uniform float InvGamma; +uniform float Contrast; +uniform float Brightness; +uniform int WindowPositionParity; // top-of-window might not be top-of-screen + +vec4 ApplyGamma(vec4 c) +{ + vec3 val = c.rgb * Contrast - (Contrast - 1.0) * 0.5; + val += Brightness * 0.5; + val = pow(max(val, vec3(0.0)), vec3(InvGamma)); + return vec4(val, c.a); +} + +void main() +{ + int thisVerticalPixel = int(gl_FragCoord.y); // Bottom row is typically the right eye, when WindowHeight is even + int thisHorizontalPixel = int(gl_FragCoord.x); // column + bool isLeftEye = (thisVerticalPixel // because we want to alternate eye view on each row + + thisHorizontalPixel // and each column + + WindowPositionParity // because the window might not be aligned to the screen + ) % 2 == 0; + vec4 inputColor; + if (isLeftEye) { + inputColor = texture(LeftEyeTexture, TexCoord); + } + else { + // inputColor = vec4(0, 1, 0, 1); + inputColor = texture(RightEyeTexture, TexCoord); + } + FragColor = ApplyGamma(inputColor); +} diff --git a/wadsrc/static/shaders/glsl/present_column3d.fp b/wadsrc/static/shaders/glsl/present_column3d.fp new file mode 100644 index 000000000..b46246cf0 --- /dev/null +++ b/wadsrc/static/shaders/glsl/present_column3d.fp @@ -0,0 +1,35 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D LeftEyeTexture; +uniform sampler2D RightEyeTexture; +uniform float InvGamma; +uniform float Contrast; +uniform float Brightness; +uniform int WindowPositionParity; // top-of-window might not be top-of-screen + +vec4 ApplyGamma(vec4 c) +{ + vec3 val = c.rgb * Contrast - (Contrast - 1.0) * 0.5; + val += Brightness * 0.5; + val = pow(max(val, vec3(0.0)), vec3(InvGamma)); + return vec4(val, c.a); +} + +void main() +{ + int thisHorizontalPixel = int(gl_FragCoord.x); // zero-based column index from left + bool isLeftEye = (thisHorizontalPixel // because we want to alternate eye view on each column + + WindowPositionParity // because the window might not be aligned to the screen + ) % 2 == 0; + vec4 inputColor; + if (isLeftEye) { + inputColor = texture(LeftEyeTexture, TexCoord); + } + else { + // inputColor = vec4(0, 1, 0, 1); + inputColor = texture(RightEyeTexture, TexCoord); + } + FragColor = ApplyGamma(inputColor); +} diff --git a/wadsrc/static/shaders/glsl/present_row3d.fp b/wadsrc/static/shaders/glsl/present_row3d.fp new file mode 100644 index 000000000..50b27ac26 --- /dev/null +++ b/wadsrc/static/shaders/glsl/present_row3d.fp @@ -0,0 +1,35 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D LeftEyeTexture; +uniform sampler2D RightEyeTexture; +uniform float InvGamma; +uniform float Contrast; +uniform float Brightness; +uniform int WindowPositionParity; // top-of-window might not be top-of-screen + +vec4 ApplyGamma(vec4 c) +{ + vec3 val = c.rgb * Contrast - (Contrast - 1.0) * 0.5; + val += Brightness * 0.5; + val = pow(max(val, vec3(0.0)), vec3(InvGamma)); + return vec4(val, c.a); +} + +void main() +{ + int thisVerticalPixel = int(gl_FragCoord.y); // Bottom row is typically the right eye, when WindowHeight is even + bool isLeftEye = (thisVerticalPixel // because we want to alternate eye view on each row + + WindowPositionParity // because the window might not be aligned to the screen + ) % 2 == 0; + vec4 inputColor; + if (isLeftEye) { + inputColor = texture(LeftEyeTexture, TexCoord); + } + else { + // inputColor = vec4(0, 1, 0, 1); + inputColor = texture(RightEyeTexture, TexCoord); + } + FragColor = ApplyGamma(inputColor); +} diff --git a/wadsrc/static/shaders/glsl/screenquad.vp b/wadsrc/static/shaders/glsl/screenquad.vp new file mode 100644 index 000000000..fea7e25ad --- /dev/null +++ b/wadsrc/static/shaders/glsl/screenquad.vp @@ -0,0 +1,10 @@ + +in vec4 PositionInProjection; +in vec2 UV; +out vec2 TexCoord; + +void main() +{ + gl_Position = PositionInProjection; + TexCoord = UV; +} diff --git a/wadsrc/static/shaders/glsl/screenquadscale.vp b/wadsrc/static/shaders/glsl/screenquadscale.vp new file mode 100644 index 000000000..2d7f505b4 --- /dev/null +++ b/wadsrc/static/shaders/glsl/screenquadscale.vp @@ -0,0 +1,11 @@ + +in vec4 PositionInProjection; +in vec2 UV; +uniform vec2 UVScale; +out vec2 TexCoord; + +void main() +{ + gl_Position = PositionInProjection; + TexCoord = UV * UVScale; +} diff --git a/wadsrc/static/shaders/glsl/shaderdefs.i b/wadsrc/static/shaders/glsl/shaderdefs.i new file mode 100644 index 000000000..8c5697a66 --- /dev/null +++ b/wadsrc/static/shaders/glsl/shaderdefs.i @@ -0,0 +1,62 @@ +// This file contains common data definitions for both vertex and fragment shader + +// these settings are actually pointless but there seem to be some old ATI drivers that fail to compile the shader without setting the precision here. +precision highp int; +precision highp float; + +uniform vec4 uCameraPos; +uniform int uTextureMode; +uniform float uClipHeight, uClipHeightDirection; +uniform vec2 uClipSplit; +uniform vec4 uClipLine; + +uniform float uAlphaThreshold; + + +// colors +uniform vec4 uObjectColor; +uniform vec4 uDynLightColor; +uniform vec4 uFogColor; +uniform float uDesaturationFactor; +uniform float uInterpolationFactor; + +// Fixed colormap stuff +uniform int uFixedColormap; // 0, when no fixed colormap, 1 for a light value, 2 for a color blend, 3 for a fog layer +uniform vec4 uFixedColormapStart; +uniform vec4 uFixedColormapRange; + +// Glowing walls stuff +uniform vec4 uGlowTopPlane; +uniform vec4 uGlowTopColor; +uniform vec4 uGlowBottomPlane; +uniform vec4 uGlowBottomColor; + +uniform vec4 uSplitTopPlane; +uniform vec4 uSplitBottomPlane; + +// Lighting + Fog +uniform vec4 uLightAttr; +#define uLightLevel uLightAttr.a +#define uFogDensity uLightAttr.b +#define uLightFactor uLightAttr.g +#define uLightDist uLightAttr.r +uniform int uFogEnabled; + +// dynamic lights +uniform int uLightIndex; + +// quad drawer stuff +#ifdef USE_QUAD_DRAWER +uniform mat4 uQuadVertices; +uniform mat4 uQuadTexCoords; +uniform int uQuadMode; +#endif + +// matrices +uniform mat4 ProjectionMatrix; +uniform mat4 ViewMatrix; +uniform mat4 ModelMatrix; +uniform mat4 NormalViewMatrix; +uniform mat4 NormalModelMatrix; +uniform mat4 TextureMatrix; + diff --git a/wadsrc/static/shaders/glsl/ssao.fp b/wadsrc/static/shaders/glsl/ssao.fp new file mode 100644 index 000000000..3b2db6005 --- /dev/null +++ b/wadsrc/static/shaders/glsl/ssao.fp @@ -0,0 +1,138 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform vec2 UVToViewA; +uniform vec2 UVToViewB; +uniform vec2 InvFullResolution; + +uniform float NDotVBias; +uniform float NegInvR2; +uniform float RadiusToScreen; +uniform float AOMultiplier; + +uniform float AOStrength; + +uniform vec2 Scale; +uniform vec2 Offset; + +uniform sampler2D DepthTexture; + +#if defined(MULTISAMPLE) +uniform sampler2DMS NormalTexture; +uniform int SampleIndex; +#else +uniform sampler2D NormalTexture; +#endif + +#if defined(USE_RANDOM_TEXTURE) +uniform sampler2D RandomTexture; +#endif + +#define PI 3.14159265358979323846 + +// Calculate eye space position for the specified texture coordinate +vec3 FetchViewPos(vec2 uv) +{ + float z = texture(DepthTexture, uv).x; + return vec3((UVToViewA * uv + UVToViewB) * z, z); +} + +#if defined(MULTISAMPLE) +vec3 SampleNormal(vec2 uv) +{ + ivec2 texSize = textureSize(NormalTexture); + ivec2 ipos = ivec2(uv * vec2(texSize)); + return texelFetch(NormalTexture, ipos, SampleIndex).xyz * 2.0 - 1.0; +} +#else +vec3 SampleNormal(vec2 uv) +{ + ivec2 texSize = textureSize(NormalTexture, 0); + ivec2 ipos = ivec2(uv * vec2(texSize)); + return texelFetch(NormalTexture, ipos, 0).xyz * 2.0 - 1.0; +} +#endif + +// Look up the eye space normal for the specified texture coordinate +vec3 FetchNormal(vec2 uv) +{ + vec3 normal = SampleNormal(Offset + uv * Scale); + if (length(normal) > 0.1) + { + normal = normalize(normal); + normal.z = -normal.z; + return normal; + } + else + { + return vec3(0.0); + } +} + +// Compute normalized 2D direction +vec2 RotateDirection(vec2 dir, vec2 cossin) +{ + return vec2(dir.x * cossin.x - dir.y * cossin.y, dir.x * cossin.y + dir.y * cossin.x); +} + +vec4 GetJitter() +{ +#if !defined(USE_RANDOM_TEXTURE) + return vec4(1,0,1,1); + //vec3 rand = noise3(TexCoord.x + TexCoord.y); + //float angle = 2.0 * PI * rand.x / NUM_DIRECTIONS; + //return vec4(cos(angle), sin(angle), rand.y, rand.z); +#else + return texture(RandomTexture, gl_FragCoord.xy / RANDOM_TEXTURE_WIDTH); +#endif +} + +// Calculates the ambient occlusion of a sample +float ComputeSampleAO(vec3 kernelPos, vec3 normal, vec3 samplePos) +{ + vec3 v = samplePos - kernelPos; + float distanceSquare = dot(v, v); + float nDotV = dot(normal, v) * inversesqrt(distanceSquare); + return clamp(nDotV - NDotVBias, 0.0, 1.0) * clamp(distanceSquare * NegInvR2 + 1.0, 0.0, 1.0); +} + +// Calculates the total ambient occlusion for the entire fragment +float ComputeAO(vec3 viewPosition, vec3 viewNormal) +{ + vec4 rand = GetJitter(); + + float radiusPixels = RadiusToScreen / viewPosition.z; + float stepSizePixels = radiusPixels / (NUM_STEPS + 1.0); + + const float directionAngleStep = 2.0 * PI / NUM_DIRECTIONS; + float ao = 0.0; + + for (float directionIndex = 0.0; directionIndex < NUM_DIRECTIONS; ++directionIndex) + { + float angle = directionAngleStep * directionIndex; + + vec2 direction = RotateDirection(vec2(cos(angle), sin(angle)), rand.xy); + float rayPixels = (rand.z * stepSizePixels + 1.0); + + for (float StepIndex = 0.0; StepIndex < NUM_STEPS; ++StepIndex) + { + vec2 sampleUV = round(rayPixels * direction) * InvFullResolution + TexCoord; + vec3 samplePos = FetchViewPos(sampleUV); + ao += ComputeSampleAO(viewPosition, viewNormal, samplePos); + rayPixels += stepSizePixels; + } + } + + ao *= AOMultiplier / (NUM_DIRECTIONS * NUM_STEPS); + return clamp(1.0 - ao * 2.0, 0.0, 1.0); +} + +void main() +{ + vec3 viewPosition = FetchViewPos(TexCoord); + vec3 viewNormal = FetchNormal(TexCoord); + float occlusion = viewNormal != vec3(0.0) ? ComputeAO(viewPosition, viewNormal) * AOStrength + (1.0 - AOStrength) : 1.0; + + FragColor = vec4(occlusion, viewPosition.z, 0.0, 1.0); +} diff --git a/wadsrc/static/shaders/glsl/ssaocombine.fp b/wadsrc/static/shaders/glsl/ssaocombine.fp new file mode 100644 index 000000000..4ca64421b --- /dev/null +++ b/wadsrc/static/shaders/glsl/ssaocombine.fp @@ -0,0 +1,39 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D AODepthTexture; + +#if defined(MULTISAMPLE) +uniform sampler2DMS SceneFogTexture; +uniform int SampleCount; +#else +uniform sampler2D SceneFogTexture; +#endif + +uniform vec2 Scale; +uniform vec2 Offset; + +void main() +{ + vec2 uv = Offset + TexCoord * Scale; + +#if defined(MULTISAMPLE) + ivec2 texSize = textureSize(SceneFogTexture); +#else + ivec2 texSize = textureSize(SceneFogTexture, 0); +#endif + ivec2 ipos = ivec2(uv * vec2(texSize)); + +#if defined(MULTISAMPLE) + vec3 fogColor = vec3(0.0); + for (int i = 0; i < SampleCount; i++) + fogColor += texelFetch(SceneFogTexture, ipos, i).rgb; + fogColor /= float(SampleCount); +#else + vec3 fogColor = texelFetch(SceneFogTexture, ipos, 0).rgb; +#endif + + float attenutation = texture(AODepthTexture, TexCoord).x; + FragColor = vec4(fogColor, 1.0 - attenutation); +} diff --git a/wadsrc/static/shaders/glsl/stencil.fp b/wadsrc/static/shaders/glsl/stencil.fp new file mode 100644 index 000000000..65f12b405 --- /dev/null +++ b/wadsrc/static/shaders/glsl/stencil.fp @@ -0,0 +1,8 @@ +in vec4 pixelpos; +out vec4 FragColor; + +void main() +{ + FragColor = vec4(1.0, 1.0, 1.0, 0.0); +} + diff --git a/wadsrc/static/shaders/glsl/swshader.fp b/wadsrc/static/shaders/glsl/swshader.fp new file mode 100644 index 000000000..01d539c88 --- /dev/null +++ b/wadsrc/static/shaders/glsl/swshader.fp @@ -0,0 +1,146 @@ + +in vec4 PixelColor0; +in vec4 PixelColor1; +in vec4 PixelTexCoord0; + +out vec4 FragColor; + +uniform sampler2D Image; +uniform sampler2D Palette; +uniform sampler2D NewScreen; +uniform sampler2D Burn; + +uniform vec4 Desaturation; // { Desat, 1 - Desat } +uniform vec4 PaletteMod; +uniform vec4 Weights; // RGB->Gray weighting { 77/256.0, 143/256.0, 37/256.0, 1 } +uniform vec4 Gamma; + +vec4 TextureLookup(vec2 tex_coord) +{ +#if defined(PALTEX) + float index = texture(Image, tex_coord).x; + index = index * PaletteMod.x + PaletteMod.y; + return texture(Palette, vec2(index, 0.5)); +#else + return texture(Image, tex_coord); +#endif +} + +vec4 Invert(vec4 rgb) +{ +#if defined(INVERT) + rgb.rgb = Weights.www - rgb.xyz; +#endif + return rgb; +} + +float Grayscale(vec4 rgb) +{ + return dot(rgb.rgb, Weights.rgb); +} + +vec4 SampleTexture(vec2 tex_coord) +{ + return Invert(TextureLookup(tex_coord)); +} + +// Normal color calculation for most drawing modes. + +vec4 NormalColor(vec2 tex_coord, vec4 Flash, vec4 InvFlash) +{ + return Flash + SampleTexture(tex_coord) * InvFlash; +} + +// Copy the red channel to the alpha channel. Pays no attention to palettes. + +vec4 RedToAlpha(vec2 tex_coord, vec4 Flash, vec4 InvFlash) +{ + vec4 color = Invert(texture(Image, tex_coord)); + color.a = color.r; + return Flash + color * InvFlash; +} + +// Just return the value of c0. + +vec4 VertexColor(vec4 color) +{ + return color; +} + +// Emulate one of the special colormaps. (Invulnerability, gold, etc.) + +vec4 SpecialColormap(vec2 tex_coord, vec4 start, vec4 end) +{ + vec4 color = SampleTexture(tex_coord); + vec4 range = end - start; + // We can't store values greater than 1.0 in a color register, so we multiply + // the final result by 2 and expect the caller to divide the start and end by 2. + color.rgb = 2 * (start + Grayscale(color) * range).rgb; + // Duplicate alpha semantics of NormalColor. + color.a = start.a + color.a * end.a; + return color; +} + +// In-game colormap effect: fade to a particular color and multiply by another, with +// optional desaturation of the original color. Desaturation is stored in c1. +// Fade level is packed int fade.a. Fade.rgb has been premultiplied by alpha. +// Overall alpha is in color.a. +vec4 InGameColormap(vec2 tex_coord, vec4 color, vec4 fade) +{ + vec4 rgb = SampleTexture(tex_coord); + + // Desaturate +#if defined(DESAT) + vec3 intensity; + intensity.rgb = vec3(Grayscale(rgb) * Desaturation.x); + rgb.rgb = intensity.rgb + rgb.rgb * Desaturation.y; +#endif + + // Fade + rgb.rgb = rgb.rgb * fade.aaa + fade.rgb; + + // Shade and Alpha + rgb = rgb * color; + + return rgb; +} + +// Windowed gamma correction. + +vec4 GammaCorrection(vec2 tex_coord) +{ + vec4 color = texture(Image, tex_coord); + color.rgb = pow(color.rgb, Gamma.rgb); + return color; +} + +// The burn wipe effect. + +vec4 BurnWipe(vec4 coord) +{ + vec4 color = texture(NewScreen, coord.xy); + vec4 alpha = texture(Burn, coord.zw); + color.a = alpha.r * 2; + return color; +} + +void main() +{ +#if defined(ENORMALCOLOR) + FragColor = NormalColor(PixelTexCoord0.xy, PixelColor0, PixelColor1); +#elif defined(EREDTOALPHA) + FragColor = RedToAlpha(PixelTexCoord0.xy, PixelColor0, PixelColor1); +#elif defined(EVERTEXCOLOR) + FragColor = VertexColor(PixelColor0); +#elif defined(ESPECIALCOLORMAP) + FragColor = SpecialColormap(PixelTexCoord0.xy, PixelColor0, PixelColor1); +#elif defined(EINGAMECOLORMAP) + FragColor = InGameColormap(PixelTexCoord0.xy, PixelColor0, PixelColor1); +#elif defined(EBURNWIPE) + FragColor = BurnWipe(PixelTexCoord0); +#elif defined(EGAMMACORRECTION) + FragColor = GammaCorrection(PixelTexCoord0.xy); +#else + #error Entry point define is missing +#endif +} diff --git a/wadsrc/static/shaders/glsl/swshader.vp b/wadsrc/static/shaders/glsl/swshader.vp new file mode 100644 index 000000000..a317025aa --- /dev/null +++ b/wadsrc/static/shaders/glsl/swshader.vp @@ -0,0 +1,22 @@ + +in vec4 AttrPosition; +in vec4 AttrColor0; +in vec4 AttrColor1; +in vec4 AttrTexCoord0; + +out vec4 PixelColor0; +out vec4 PixelColor1; +out vec4 PixelTexCoord0; + +uniform vec4 ScreenSize; + +void main() +{ + gl_Position = vec4(AttrPosition.xy / ScreenSize.xy * 2.0 - 1.0, 1.0, 1.0); +#if defined(EGAMMACORRECTION) + gl_Position.y = -gl_Position.y; +#endif + PixelColor0 = AttrColor0.bgra; + PixelColor1 = AttrColor1.bgra; + PixelTexCoord0 = AttrTexCoord0; +} diff --git a/wadsrc/static/shaders/glsl/tonemap.fp b/wadsrc/static/shaders/glsl/tonemap.fp new file mode 100644 index 000000000..5cb7cf8bd --- /dev/null +++ b/wadsrc/static/shaders/glsl/tonemap.fp @@ -0,0 +1,92 @@ + +in vec2 TexCoord; +out vec4 FragColor; + +uniform sampler2D InputTexture; +uniform sampler2D ExposureTexture; + +vec3 Linear(vec3 c) +{ + //c = max(c, vec3(0.0)); + //return pow(c, 2.2); + return c * c; // cheaper, but assuming gamma of 2.0 instead of 2.2 +} + +vec3 sRGB(vec3 c) +{ + c = max(c, vec3(0.0)); + //return pow(c, vec3(1.0 / 2.2)); + return sqrt(c); // cheaper, but assuming gamma of 2.0 instead of 2.2 +} + +#if defined(LINEAR) + +vec3 Tonemap(vec3 color) +{ + return sRGB(color); +} + +#elif defined(REINHARD) + +vec3 Tonemap(vec3 color) +{ + color = color / (1 + color); + return sRGB(color); +} + +#elif defined(HEJLDAWSON) + +vec3 Tonemap(vec3 color) +{ + vec3 x = max(vec3(0), color - 0.004); + return (x * (6.2 * x + 0.5)) / (x * (6.2 * x + 1.7) + 0.06); // no sRGB needed +} + +#elif defined(UNCHARTED2) + +vec3 Uncharted2Tonemap(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 Tonemap(vec3 color) +{ + float W = 11.2; + vec3 curr = Uncharted2Tonemap(color); + vec3 whiteScale = vec3(1) / Uncharted2Tonemap(vec3(W)); + return sRGB(curr * whiteScale); +} + +#elif defined(PALETTE) + +uniform sampler2D PaletteLUT; + +vec3 Tonemap(vec3 color) +{ + ivec3 c = ivec3(clamp(color.rgb, vec3(0.0), vec3(1.0)) * 63.0 + 0.5); + int index = (c.r * 64 + c.g) * 64 + c.b; + int tx = index % 512; + int ty = index / 512; + return texelFetch(PaletteLUT, ivec2(tx, ty), 0).rgb; +} + +#else +#error Tonemap mode define is missing +#endif + +void main() +{ + vec3 color = texture(InputTexture, TexCoord).rgb; +#ifndef PALETTE + float exposureAdjustment = texture(ExposureTexture, vec2(0.5)).x; + color = color * exposureAdjustment; + color = Linear(color); // needed because gzdoom's scene texture is not linear at the moment +#endif + FragColor = vec4(Tonemap(color), 1.0); +} diff --git a/wadsrc/static/zscript.txt b/wadsrc/static/zscript.txt index 24fd1b068..d9e60f248 100644 --- a/wadsrc/static/zscript.txt +++ b/wadsrc/static/zscript.txt @@ -36,6 +36,7 @@ #include "zscript/shared/ice.txt" #include "zscript/shared/dog.txt" #include "zscript/shared/fastprojectile.txt" +#include "zscript/shared/dynlights.txt" #include "zscript/compatibility.txt" diff --git a/wadsrc/static/zscript/doom/doomarmor.txt b/wadsrc/static/zscript/doom/doomarmor.txt index 8c3d52cc9..30ff9a140 100644 --- a/wadsrc/static/zscript/doom/doomarmor.txt +++ b/wadsrc/static/zscript/doom/doomarmor.txt @@ -8,7 +8,7 @@ class ArmorBonus : BasicArmorBonus Radius 20; Height 16; Inventory.Pickupmessage "$GOTARMBONUS"; - Inventory.Icon "ARM1A0"; + Inventory.Icon "BON2A0"; Armor.Savepercent 33.335; Armor.Saveamount 1; Armor.Maxsaveamount 200; diff --git a/wadsrc/static/zscript/shared/dynlights.txt b/wadsrc/static/zscript/shared/dynlights.txt new file mode 100644 index 000000000..f851d88d0 --- /dev/null +++ b/wadsrc/static/zscript/shared/dynlights.txt @@ -0,0 +1,201 @@ +class DynamicLight : Actor native +{ + Default + { + Height 0; + Radius 0.1; + FloatBobPhase 0; + RenderRadius -1; + +NOBLOCKMAP + +NOGRAVITY + +FIXMAPTHINGPOS + +INVISIBLE + } +} + + +class PointLight : DynamicLight +{ + Default + { + DynamicLight.Type "Point"; + } +} + +class PointLightPulse : PointLight +{ + Default + { + DynamicLight.Type "Pulse"; + } +} + +class PointLightFlicker : PointLight +{ + Default + { + DynamicLight.Type "Flicker"; + } +} + +class SectorPointLight : PointLight +{ + Default + { + DynamicLight.Type "Sector"; + } +} + +class PointLightFlickerRandom : PointLight +{ + Default + { + DynamicLight.Type "RandomFlicker"; + } +} + +// MISSILEMORE and MISSILEEVENMORE are used by the lights for additive and subtractive lights + +class PointLightAdditive : PointLight +{ + Default + { + +MISSILEMORE + } +} + +class PointLightPulseAdditive : PointLightPulse +{ + Default + { + +MISSILEMORE + } +} + +class PointLightFlickerAdditive : PointLightFlicker +{ + Default + { + +MISSILEMORE + } +} + +class SectorPointLightAdditive : SectorPointLight +{ + Default + { + +MISSILEMORE + } +} + +class PointLightFlickerRandomAdditive :PointLightFlickerRandom +{ + Default + { + +MISSILEMORE + } +} + +class PointLightSubtractive : PointLight +{ + Default + { + +MISSILEEVENMORE + } +} + +class PointLightPulseSubtractive : PointLightPulse +{ + Default + { + +MISSILEEVENMORE + } +} + +class PointLightFlickerSubtractive : PointLightFlicker +{ + Default + { + +MISSILEEVENMORE + } +} + +class SectorPointLightSubtractive : SectorPointLight +{ + Default + { + +MISSILEEVENMORE + } +} + +class PointLightFlickerRandomSubtractive : PointLightFlickerRandom +{ + Default + { + +MISSILEEVENMORE + } +} + + +class VavoomLight : DynamicLight native +{ + Default + { + } +} + +class VavoomLightWhite : VavoomLight native +{ + Default + { + } +} + +class VavoomLightColor : VavoomLight native +{ + Default + { + } +} + + +class PointLightAttenuated : PointLight +{ + Default + { + +INCOMBAT + } +} + +class PointLightPulseAttenuated : PointLightPulse +{ + Default + { + +INCOMBAT + } +} + +class PointLightFlickerAttenuated : PointLightFlicker +{ + Default + { + +INCOMBAT + } +} + +class SectorPointLightAttenuated : SectorPointLight +{ + Default + { + +INCOMBAT + } +} + +class PointLightFlickerRandomAttenuated :PointLightFlickerRandom +{ + Default + { + +INCOMBAT + } +} + diff --git a/wadsrc_bm/CMakeLists.txt b/wadsrc_bm/CMakeLists.txt new file mode 100644 index 000000000..a76c5dc36 --- /dev/null +++ b/wadsrc_bm/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required( VERSION 2.4 ) + +add_pk3(brightmaps.pk3 ${CMAKE_CURRENT_SOURCE_DIR}/static) diff --git a/wadsrc_bm/static/brightmaps/doom/BON2B0.png b/wadsrc_bm/static/brightmaps/doom/BON2B0.png new file mode 100644 index 000000000..ef16358e5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BON2B0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BON2C0.png b/wadsrc_bm/static/brightmaps/doom/BON2C0.png new file mode 100644 index 000000000..f55f93bf4 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BON2C0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BON2D0.png b/wadsrc_bm/static/brightmaps/doom/BON2D0.png new file mode 100644 index 000000000..a08679f6e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BON2D0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2A6C4.png b/wadsrc_bm/static/brightmaps/doom/BOS2A6C4.png new file mode 100644 index 000000000..9e866d11e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2A6C4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2A7C3.png b/wadsrc_bm/static/brightmaps/doom/BOS2A7C3.png new file mode 100644 index 000000000..2e0c7c592 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2A7C3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2A8C2.png b/wadsrc_bm/static/brightmaps/doom/BOS2A8C2.png new file mode 100644 index 000000000..f11facd1b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2A8C2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2B6D4.png b/wadsrc_bm/static/brightmaps/doom/BOS2B6D4.png new file mode 100644 index 000000000..8c3d09be2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2B6D4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2B7D3.png b/wadsrc_bm/static/brightmaps/doom/BOS2B7D3.png new file mode 100644 index 000000000..6d78193f5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2B7D3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOS2B8D2.png b/wadsrc_bm/static/brightmaps/doom/BOS2B8D2.png new file mode 100644 index 000000000..9af1ca025 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOS2B8D2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSA1.png b/wadsrc_bm/static/brightmaps/doom/BOSSA1.png new file mode 100644 index 000000000..a0f08cbb5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSA1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSA2A8.png b/wadsrc_bm/static/brightmaps/doom/BOSSA2A8.png new file mode 100644 index 000000000..2d07518de Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSA2A8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSA3A7.png b/wadsrc_bm/static/brightmaps/doom/BOSSA3A7.png new file mode 100644 index 000000000..7c48d51e7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSA3A7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSA4A6.png b/wadsrc_bm/static/brightmaps/doom/BOSSA4A6.png new file mode 100644 index 000000000..a76d9635c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSA4A6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSA5.png b/wadsrc_bm/static/brightmaps/doom/BOSSA5.png new file mode 100644 index 000000000..80dca3199 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSA5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSB1.png b/wadsrc_bm/static/brightmaps/doom/BOSSB1.png new file mode 100644 index 000000000..7ef1147cc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSB1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSB2B8.png b/wadsrc_bm/static/brightmaps/doom/BOSSB2B8.png new file mode 100644 index 000000000..bb31928df Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSB2B8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSB3B7.png b/wadsrc_bm/static/brightmaps/doom/BOSSB3B7.png new file mode 100644 index 000000000..dd8da7d8a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSB3B7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSB4B6.png b/wadsrc_bm/static/brightmaps/doom/BOSSB4B6.png new file mode 100644 index 000000000..112b5186c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSB4B6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSB5.png b/wadsrc_bm/static/brightmaps/doom/BOSSB5.png new file mode 100644 index 000000000..1bc1154c3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSB5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSC1.png b/wadsrc_bm/static/brightmaps/doom/BOSSC1.png new file mode 100644 index 000000000..c1bb118fa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSC1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSC2C8.png b/wadsrc_bm/static/brightmaps/doom/BOSSC2C8.png new file mode 100644 index 000000000..c9fee8d0d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSC2C8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSC3C7.png b/wadsrc_bm/static/brightmaps/doom/BOSSC3C7.png new file mode 100644 index 000000000..b93cacc81 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSC3C7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSC4C6.png b/wadsrc_bm/static/brightmaps/doom/BOSSC4C6.png new file mode 100644 index 000000000..6b3ff0cdf Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSC4C6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSC5.png b/wadsrc_bm/static/brightmaps/doom/BOSSC5.png new file mode 100644 index 000000000..0f1d38618 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSC5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSD1.png b/wadsrc_bm/static/brightmaps/doom/BOSSD1.png new file mode 100644 index 000000000..8ed579c9c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSD1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSD2D8.png b/wadsrc_bm/static/brightmaps/doom/BOSSD2D8.png new file mode 100644 index 000000000..afa335e0c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSD2D8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSD3D7.png b/wadsrc_bm/static/brightmaps/doom/BOSSD3D7.png new file mode 100644 index 000000000..7fafce06e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSD3D7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSD4D6.png b/wadsrc_bm/static/brightmaps/doom/BOSSD4D6.png new file mode 100644 index 000000000..296b5a80a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSD4D6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSD5.png b/wadsrc_bm/static/brightmaps/doom/BOSSD5.png new file mode 100644 index 000000000..0468e12e2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSD5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE1.png b/wadsrc_bm/static/brightmaps/doom/BOSSE1.png new file mode 100644 index 000000000..cc3c407c6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE2.png b/wadsrc_bm/static/brightmaps/doom/BOSSE2.png new file mode 100644 index 000000000..31837cc6c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE3.png b/wadsrc_bm/static/brightmaps/doom/BOSSE3.png new file mode 100644 index 000000000..6dde651c7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE4.png b/wadsrc_bm/static/brightmaps/doom/BOSSE4.png new file mode 100644 index 000000000..8ffaed4bd Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE5.png b/wadsrc_bm/static/brightmaps/doom/BOSSE5.png new file mode 100644 index 000000000..e5bca33a3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE6.png b/wadsrc_bm/static/brightmaps/doom/BOSSE6.png new file mode 100644 index 000000000..fd6b669da Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE7.png b/wadsrc_bm/static/brightmaps/doom/BOSSE7.png new file mode 100644 index 000000000..4a9e0a653 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSE8.png b/wadsrc_bm/static/brightmaps/doom/BOSSE8.png new file mode 100644 index 000000000..d8be17d60 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSE8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF1.png b/wadsrc_bm/static/brightmaps/doom/BOSSF1.png new file mode 100644 index 000000000..7667a456a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF2.png b/wadsrc_bm/static/brightmaps/doom/BOSSF2.png new file mode 100644 index 000000000..1884c9cb9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF3.png b/wadsrc_bm/static/brightmaps/doom/BOSSF3.png new file mode 100644 index 000000000..f6b72649a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF4.png b/wadsrc_bm/static/brightmaps/doom/BOSSF4.png new file mode 100644 index 000000000..10c4a6e4b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF5.png b/wadsrc_bm/static/brightmaps/doom/BOSSF5.png new file mode 100644 index 000000000..8719121f8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF6.png b/wadsrc_bm/static/brightmaps/doom/BOSSF6.png new file mode 100644 index 000000000..7bc73a47e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF7.png b/wadsrc_bm/static/brightmaps/doom/BOSSF7.png new file mode 100644 index 000000000..71826d440 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSF8.png b/wadsrc_bm/static/brightmaps/doom/BOSSF8.png new file mode 100644 index 000000000..70af4c02b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSF8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG1.png b/wadsrc_bm/static/brightmaps/doom/BOSSG1.png new file mode 100644 index 000000000..f3ee59a1c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG2.png b/wadsrc_bm/static/brightmaps/doom/BOSSG2.png new file mode 100644 index 000000000..fc735a9cb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG3.png b/wadsrc_bm/static/brightmaps/doom/BOSSG3.png new file mode 100644 index 000000000..8d74f0cdf Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG4.png b/wadsrc_bm/static/brightmaps/doom/BOSSG4.png new file mode 100644 index 000000000..4cb2a3f96 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG5.png b/wadsrc_bm/static/brightmaps/doom/BOSSG5.png new file mode 100644 index 000000000..cc9150430 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG6.png b/wadsrc_bm/static/brightmaps/doom/BOSSG6.png new file mode 100644 index 000000000..df682c071 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG7.png b/wadsrc_bm/static/brightmaps/doom/BOSSG7.png new file mode 100644 index 000000000..90010e2df Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSG8.png b/wadsrc_bm/static/brightmaps/doom/BOSSG8.png new file mode 100644 index 000000000..d2a412042 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSG8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH1.png b/wadsrc_bm/static/brightmaps/doom/BOSSH1.png new file mode 100644 index 000000000..bd4fbfe56 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH2.png b/wadsrc_bm/static/brightmaps/doom/BOSSH2.png new file mode 100644 index 000000000..dc93c8f70 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH3.png b/wadsrc_bm/static/brightmaps/doom/BOSSH3.png new file mode 100644 index 000000000..b94e1bb1a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH4.png b/wadsrc_bm/static/brightmaps/doom/BOSSH4.png new file mode 100644 index 000000000..ce03a828f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH5.png b/wadsrc_bm/static/brightmaps/doom/BOSSH5.png new file mode 100644 index 000000000..d3765c7c6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH6.png b/wadsrc_bm/static/brightmaps/doom/BOSSH6.png new file mode 100644 index 000000000..13939f984 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH7.png b/wadsrc_bm/static/brightmaps/doom/BOSSH7.png new file mode 100644 index 000000000..4061dc2e9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSH8.png b/wadsrc_bm/static/brightmaps/doom/BOSSH8.png new file mode 100644 index 000000000..55e98eaf0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSH8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSI0.png b/wadsrc_bm/static/brightmaps/doom/BOSSI0.png new file mode 100644 index 000000000..8626bba21 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSI0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSJ0.png b/wadsrc_bm/static/brightmaps/doom/BOSSJ0.png new file mode 100644 index 000000000..0fd48d816 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSJ0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSK0.png b/wadsrc_bm/static/brightmaps/doom/BOSSK0.png new file mode 100644 index 000000000..0a4809b98 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSK0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSL0.png b/wadsrc_bm/static/brightmaps/doom/BOSSL0.png new file mode 100644 index 000000000..1950c21ff Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSL0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BOSSM0.png b/wadsrc_bm/static/brightmaps/doom/BOSSM0.png new file mode 100644 index 000000000..73f7971c9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BOSSM0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIG1.png b/wadsrc_bm/static/brightmaps/doom/BSPIG1.png new file mode 100644 index 000000000..034ec03d8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIG1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIG2G8.png b/wadsrc_bm/static/brightmaps/doom/BSPIG2G8.png new file mode 100644 index 000000000..937b8b1cb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIG2G8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIH1.png b/wadsrc_bm/static/brightmaps/doom/BSPIH1.png new file mode 100644 index 000000000..4e3625aa2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIH1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIH2H8.png b/wadsrc_bm/static/brightmaps/doom/BSPIH2H8.png new file mode 100644 index 000000000..6e270f2c8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIH2H8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIH3H7.png b/wadsrc_bm/static/brightmaps/doom/BSPIH3H7.png new file mode 100644 index 000000000..4ff61708f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIH3H7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIH4H6.png b/wadsrc_bm/static/brightmaps/doom/BSPIH4H6.png new file mode 100644 index 000000000..1813d9689 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIH4H6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/BSPIH5.png b/wadsrc_bm/static/brightmaps/doom/BSPIH5.png new file mode 100644 index 000000000..a3c97ea8c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/BSPIH5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CELLA0.png b/wadsrc_bm/static/brightmaps/doom/CELLA0.png new file mode 100644 index 000000000..f06e3d3d7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CELLA0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CELPA0.png b/wadsrc_bm/static/brightmaps/doom/CELPA0.png new file mode 100644 index 000000000..5b6486c8b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CELPA0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE1.png b/wadsrc_bm/static/brightmaps/doom/CPOSE1.png new file mode 100644 index 000000000..437c2a463 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE2.png b/wadsrc_bm/static/brightmaps/doom/CPOSE2.png new file mode 100644 index 000000000..9597368cf Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE3.png b/wadsrc_bm/static/brightmaps/doom/CPOSE3.png new file mode 100644 index 000000000..c443441c1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE5.png b/wadsrc_bm/static/brightmaps/doom/CPOSE5.png new file mode 100644 index 000000000..a01147e6e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE6.png b/wadsrc_bm/static/brightmaps/doom/CPOSE6.png new file mode 100644 index 000000000..61eda1af7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE7.png b/wadsrc_bm/static/brightmaps/doom/CPOSE7.png new file mode 100644 index 000000000..587d4f62f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSE8.png b/wadsrc_bm/static/brightmaps/doom/CPOSE8.png new file mode 100644 index 000000000..692601735 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSE8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF1.png b/wadsrc_bm/static/brightmaps/doom/CPOSF1.png new file mode 100644 index 000000000..a445fff92 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF2.png b/wadsrc_bm/static/brightmaps/doom/CPOSF2.png new file mode 100644 index 000000000..4a5eb267c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF3.png b/wadsrc_bm/static/brightmaps/doom/CPOSF3.png new file mode 100644 index 000000000..b545edbb2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF4.png b/wadsrc_bm/static/brightmaps/doom/CPOSF4.png new file mode 100644 index 000000000..50c3c135d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF5.png b/wadsrc_bm/static/brightmaps/doom/CPOSF5.png new file mode 100644 index 000000000..f9e53d24f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF6.png b/wadsrc_bm/static/brightmaps/doom/CPOSF6.png new file mode 100644 index 000000000..574378a25 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF7.png b/wadsrc_bm/static/brightmaps/doom/CPOSF7.png new file mode 100644 index 000000000..14e4c5681 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CPOSF8.png b/wadsrc_bm/static/brightmaps/doom/CPOSF8.png new file mode 100644 index 000000000..e80c306a1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CPOSF8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF1.png b/wadsrc_bm/static/brightmaps/doom/CYBRF1.png new file mode 100644 index 000000000..e97a94f17 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF2.png b/wadsrc_bm/static/brightmaps/doom/CYBRF2.png new file mode 100644 index 000000000..886e5b20d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF3.png b/wadsrc_bm/static/brightmaps/doom/CYBRF3.png new file mode 100644 index 000000000..ea6ccde8e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF4.png b/wadsrc_bm/static/brightmaps/doom/CYBRF4.png new file mode 100644 index 000000000..d53db24cd Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF5.png b/wadsrc_bm/static/brightmaps/doom/CYBRF5.png new file mode 100644 index 000000000..959741072 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF6.png b/wadsrc_bm/static/brightmaps/doom/CYBRF6.png new file mode 100644 index 000000000..bd4574a19 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF7.png b/wadsrc_bm/static/brightmaps/doom/CYBRF7.png new file mode 100644 index 000000000..78dcba173 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRF8.png b/wadsrc_bm/static/brightmaps/doom/CYBRF8.png new file mode 100644 index 000000000..549050d2b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRF8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRJ0.png b/wadsrc_bm/static/brightmaps/doom/CYBRJ0.png new file mode 100644 index 000000000..40845cc73 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRJ0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRK0.png b/wadsrc_bm/static/brightmaps/doom/CYBRK0.png new file mode 100644 index 000000000..5eabd6c17 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRK0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRL0.png b/wadsrc_bm/static/brightmaps/doom/CYBRL0.png new file mode 100644 index 000000000..2a542c685 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRL0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRM0.png b/wadsrc_bm/static/brightmaps/doom/CYBRM0.png new file mode 100644 index 000000000..ffe528adb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRM0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRN0.png b/wadsrc_bm/static/brightmaps/doom/CYBRN0.png new file mode 100644 index 000000000..0b5760b4a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRN0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/CYBRO0.png b/wadsrc_bm/static/brightmaps/doom/CYBRO0.png new file mode 100644 index 000000000..8b52093c3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/CYBRO0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTG1.png b/wadsrc_bm/static/brightmaps/doom/FATTG1.png new file mode 100644 index 000000000..bce6010b7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTG1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTG2G8.png b/wadsrc_bm/static/brightmaps/doom/FATTG2G8.png new file mode 100644 index 000000000..06b82243f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTG2G8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTH1.png b/wadsrc_bm/static/brightmaps/doom/FATTH1.png new file mode 100644 index 000000000..e22d536f9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTH1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTH2H8.png b/wadsrc_bm/static/brightmaps/doom/FATTH2H8.png new file mode 100644 index 000000000..c6a763f1a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTH2H8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTH3H7.png b/wadsrc_bm/static/brightmaps/doom/FATTH3H7.png new file mode 100644 index 000000000..1b7ca4c67 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTH3H7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTH4H6.png b/wadsrc_bm/static/brightmaps/doom/FATTH4H6.png new file mode 100644 index 000000000..82fb052a1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTH4H6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FATTH5.png b/wadsrc_bm/static/brightmaps/doom/FATTH5.png new file mode 100644 index 000000000..00ab9b984 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FATTH5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FCANA0.png b/wadsrc_bm/static/brightmaps/doom/FCANA0.png new file mode 100644 index 000000000..3cb6b9d5b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FCANA0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FCANB0.png b/wadsrc_bm/static/brightmaps/doom/FCANB0.png new file mode 100644 index 000000000..c4ad1484f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FCANB0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/FCANC0.png b/wadsrc_bm/static/brightmaps/doom/FCANC0.png new file mode 100644 index 000000000..7b430607c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/FCANC0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADC1.png b/wadsrc_bm/static/brightmaps/doom/HEADC1.png new file mode 100644 index 000000000..81fe3e7c6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADC1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADC2C8.png b/wadsrc_bm/static/brightmaps/doom/HEADC2C8.png new file mode 100644 index 000000000..d4fe4df87 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADC2C8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADC3C7.png b/wadsrc_bm/static/brightmaps/doom/HEADC3C7.png new file mode 100644 index 000000000..4dd996ca3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADC3C7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADD1.png b/wadsrc_bm/static/brightmaps/doom/HEADD1.png new file mode 100644 index 000000000..43c2b9820 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADD1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADD2D8.png b/wadsrc_bm/static/brightmaps/doom/HEADD2D8.png new file mode 100644 index 000000000..5bd6655bb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADD2D8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/HEADD3D7.png b/wadsrc_bm/static/brightmaps/doom/HEADD3D7.png new file mode 100644 index 000000000..12862b89e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/HEADD3D7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PAINF1.png b/wadsrc_bm/static/brightmaps/doom/PAINF1.png new file mode 100644 index 000000000..26e4486c8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PAINF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PAINF2F8.png b/wadsrc_bm/static/brightmaps/doom/PAINF2F8.png new file mode 100644 index 000000000..dbb5277eb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PAINF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PAINF3F7.png b/wadsrc_bm/static/brightmaps/doom/PAINF3F7.png new file mode 100644 index 000000000..044b88aa9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PAINF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PLAYF1.png b/wadsrc_bm/static/brightmaps/doom/PLAYF1.png new file mode 100644 index 000000000..f3f83fe8e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PLAYF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PLAYF2F8.png b/wadsrc_bm/static/brightmaps/doom/PLAYF2F8.png new file mode 100644 index 000000000..d7e948c55 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PLAYF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PLAYF3F7.png b/wadsrc_bm/static/brightmaps/doom/PLAYF3F7.png new file mode 100644 index 000000000..8e1616cf6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PLAYF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PLAYF4F6.png b/wadsrc_bm/static/brightmaps/doom/PLAYF4F6.png new file mode 100644 index 000000000..9def391d7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PLAYF4F6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/PLAYF5.png b/wadsrc_bm/static/brightmaps/doom/PLAYF5.png new file mode 100644 index 000000000..520a9abfa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/PLAYF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSE1.png b/wadsrc_bm/static/brightmaps/doom/POSSE1.png new file mode 100644 index 000000000..5983ef59d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSE1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSE2E8.png b/wadsrc_bm/static/brightmaps/doom/POSSE2E8.png new file mode 100644 index 000000000..65c4056ae Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSE2E8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSE3E7.png b/wadsrc_bm/static/brightmaps/doom/POSSE3E7.png new file mode 100644 index 000000000..464bb94dc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSE3E7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSF1.png b/wadsrc_bm/static/brightmaps/doom/POSSF1.png new file mode 100644 index 000000000..fe2a07221 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSF2F8.png b/wadsrc_bm/static/brightmaps/doom/POSSF2F8.png new file mode 100644 index 000000000..0ecd256bc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSF3F7.png b/wadsrc_bm/static/brightmaps/doom/POSSF3F7.png new file mode 100644 index 000000000..07d202c18 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSF4F6.png b/wadsrc_bm/static/brightmaps/doom/POSSF4F6.png new file mode 100644 index 000000000..bc5fb14f9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSF4F6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/POSSF5.png b/wadsrc_bm/static/brightmaps/doom/POSSF5.png new file mode 100644 index 000000000..5ca4b3169 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/POSSF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ1.png b/wadsrc_bm/static/brightmaps/doom/SKELJ1.png new file mode 100644 index 000000000..82db405af Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ2.png b/wadsrc_bm/static/brightmaps/doom/SKELJ2.png new file mode 100644 index 000000000..8bef7b58a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ3.png b/wadsrc_bm/static/brightmaps/doom/SKELJ3.png new file mode 100644 index 000000000..ac551476b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ4.png b/wadsrc_bm/static/brightmaps/doom/SKELJ4.png new file mode 100644 index 000000000..84d839a06 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ5.png b/wadsrc_bm/static/brightmaps/doom/SKELJ5.png new file mode 100644 index 000000000..bdc5efc3f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ6.png b/wadsrc_bm/static/brightmaps/doom/SKELJ6.png new file mode 100644 index 000000000..a16d9853b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ7.png b/wadsrc_bm/static/brightmaps/doom/SKELJ7.png new file mode 100644 index 000000000..9e8e4912d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SKELJ8.png b/wadsrc_bm/static/brightmaps/doom/SKELJ8.png new file mode 100644 index 000000000..333bd678b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SKELJ8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SMRTA0.png b/wadsrc_bm/static/brightmaps/doom/SMRTA0.png new file mode 100644 index 000000000..49867963e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SMRTA0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SMRTB0.png b/wadsrc_bm/static/brightmaps/doom/SMRTB0.png new file mode 100644 index 000000000..e6291b8f5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SMRTB0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SMRTC0.png b/wadsrc_bm/static/brightmaps/doom/SMRTC0.png new file mode 100644 index 000000000..4b7bb5f51 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SMRTC0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SMRTD0.png b/wadsrc_bm/static/brightmaps/doom/SMRTD0.png new file mode 100644 index 000000000..f6d611491 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SMRTD0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDG1.png b/wadsrc_bm/static/brightmaps/doom/SPIDG1.png new file mode 100644 index 000000000..5bee5c0b7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDG1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDG2G8.png b/wadsrc_bm/static/brightmaps/doom/SPIDG2G8.png new file mode 100644 index 000000000..0075bc06b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDG2G8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDH1.png b/wadsrc_bm/static/brightmaps/doom/SPIDH1.png new file mode 100644 index 000000000..e7d0756fa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDH1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDH2H8.png b/wadsrc_bm/static/brightmaps/doom/SPIDH2H8.png new file mode 100644 index 000000000..1a36d14bc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDH2H8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDH3H7.png b/wadsrc_bm/static/brightmaps/doom/SPIDH3H7.png new file mode 100644 index 000000000..654313cfa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDH3H7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDL0.png b/wadsrc_bm/static/brightmaps/doom/SPIDL0.png new file mode 100644 index 000000000..53c899c38 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDL0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDM0.png b/wadsrc_bm/static/brightmaps/doom/SPIDM0.png new file mode 100644 index 000000000..d9fbea53f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDM0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDN0.png b/wadsrc_bm/static/brightmaps/doom/SPIDN0.png new file mode 100644 index 000000000..3d40b9a09 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDN0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDO0.png b/wadsrc_bm/static/brightmaps/doom/SPIDO0.png new file mode 100644 index 000000000..0273fe6aa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDO0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDP0.png b/wadsrc_bm/static/brightmaps/doom/SPIDP0.png new file mode 100644 index 000000000..addf14464 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDP0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDQ0.png b/wadsrc_bm/static/brightmaps/doom/SPIDQ0.png new file mode 100644 index 000000000..954f6061f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDQ0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPIDR0.png b/wadsrc_bm/static/brightmaps/doom/SPIDR0.png new file mode 100644 index 000000000..02b299b15 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPIDR0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSE1.png b/wadsrc_bm/static/brightmaps/doom/SPOSE1.png new file mode 100644 index 000000000..5983ef59d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSE1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSE2E8.png b/wadsrc_bm/static/brightmaps/doom/SPOSE2E8.png new file mode 100644 index 000000000..ddbb00da2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSE2E8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSE3E7.png b/wadsrc_bm/static/brightmaps/doom/SPOSE3E7.png new file mode 100644 index 000000000..527486c47 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSE3E7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSF1.png b/wadsrc_bm/static/brightmaps/doom/SPOSF1.png new file mode 100644 index 000000000..ba6a74c07 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSF1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSF2F8.png b/wadsrc_bm/static/brightmaps/doom/SPOSF2F8.png new file mode 100644 index 000000000..e42e83b01 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSF3F7.png b/wadsrc_bm/static/brightmaps/doom/SPOSF3F7.png new file mode 100644 index 000000000..ff1e66f9f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSF4F6.png b/wadsrc_bm/static/brightmaps/doom/SPOSF4F6.png new file mode 100644 index 000000000..d8445c71d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSF4F6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/SPOSF5.png b/wadsrc_bm/static/brightmaps/doom/SPOSF5.png new file mode 100644 index 000000000..2fdf53286 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/SPOSF5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TREDA0.png b/wadsrc_bm/static/brightmaps/doom/TREDA0.png new file mode 100644 index 000000000..d7318f94a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TREDA0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TREDB0.png b/wadsrc_bm/static/brightmaps/doom/TREDB0.png new file mode 100644 index 000000000..15ba5a665 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TREDB0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TREDC0.png b/wadsrc_bm/static/brightmaps/doom/TREDC0.png new file mode 100644 index 000000000..47842aa3f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TREDC0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TREDD0.png b/wadsrc_bm/static/brightmaps/doom/TREDD0.png new file mode 100644 index 000000000..f4cb483b8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TREDD0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TbluB0.png b/wadsrc_bm/static/brightmaps/doom/TbluB0.png new file mode 100644 index 000000000..6d020512c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TbluB0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/TbluC0.png b/wadsrc_bm/static/brightmaps/doom/TbluC0.png new file mode 100644 index 000000000..e1771d71c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/TbluC0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/sswvg0.png b/wadsrc_bm/static/brightmaps/doom/sswvg0.png new file mode 100644 index 000000000..904092f8d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/sswvg0.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg1.png b/wadsrc_bm/static/brightmaps/doom/vileg1.png new file mode 100644 index 000000000..c02f31d78 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg2.png b/wadsrc_bm/static/brightmaps/doom/vileg2.png new file mode 100644 index 000000000..979863d54 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg3.png b/wadsrc_bm/static/brightmaps/doom/vileg3.png new file mode 100644 index 000000000..3646c90bc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg4.png b/wadsrc_bm/static/brightmaps/doom/vileg4.png new file mode 100644 index 000000000..26bac2477 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg5.png b/wadsrc_bm/static/brightmaps/doom/vileg5.png new file mode 100644 index 000000000..1f0b75a99 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg6.png b/wadsrc_bm/static/brightmaps/doom/vileg6.png new file mode 100644 index 000000000..7412bf595 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg7.png b/wadsrc_bm/static/brightmaps/doom/vileg7.png new file mode 100644 index 000000000..b98488d1f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileg8.png b/wadsrc_bm/static/brightmaps/doom/vileg8.png new file mode 100644 index 000000000..440e189c0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileg8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh1.png b/wadsrc_bm/static/brightmaps/doom/vileh1.png new file mode 100644 index 000000000..713a2204a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh2.png b/wadsrc_bm/static/brightmaps/doom/vileh2.png new file mode 100644 index 000000000..606f1dc2e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh3.png b/wadsrc_bm/static/brightmaps/doom/vileh3.png new file mode 100644 index 000000000..cf5d27d53 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh4.png b/wadsrc_bm/static/brightmaps/doom/vileh4.png new file mode 100644 index 000000000..60bd8a14b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh5.png b/wadsrc_bm/static/brightmaps/doom/vileh5.png new file mode 100644 index 000000000..db2dd8d2a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh6.png b/wadsrc_bm/static/brightmaps/doom/vileh6.png new file mode 100644 index 000000000..3c776f987 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh7.png b/wadsrc_bm/static/brightmaps/doom/vileh7.png new file mode 100644 index 000000000..e8818101a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileh8.png b/wadsrc_bm/static/brightmaps/doom/vileh8.png new file mode 100644 index 000000000..9078b7fe2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileh8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei1.png b/wadsrc_bm/static/brightmaps/doom/vilei1.png new file mode 100644 index 000000000..ca8d54001 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei2.png b/wadsrc_bm/static/brightmaps/doom/vilei2.png new file mode 100644 index 000000000..a76359f33 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei3.png b/wadsrc_bm/static/brightmaps/doom/vilei3.png new file mode 100644 index 000000000..5ec97664a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei4.png b/wadsrc_bm/static/brightmaps/doom/vilei4.png new file mode 100644 index 000000000..99fa6dbb3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei5.png b/wadsrc_bm/static/brightmaps/doom/vilei5.png new file mode 100644 index 000000000..34b260006 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei6.png b/wadsrc_bm/static/brightmaps/doom/vilei6.png new file mode 100644 index 000000000..435fe6f31 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei7.png b/wadsrc_bm/static/brightmaps/doom/vilei7.png new file mode 100644 index 000000000..b362c411f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilei8.png b/wadsrc_bm/static/brightmaps/doom/vilei8.png new file mode 100644 index 000000000..6dd3d603f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilei8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej1.png b/wadsrc_bm/static/brightmaps/doom/vilej1.png new file mode 100644 index 000000000..3a8b234a9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej2.png b/wadsrc_bm/static/brightmaps/doom/vilej2.png new file mode 100644 index 000000000..ed42c147d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej3.png b/wadsrc_bm/static/brightmaps/doom/vilej3.png new file mode 100644 index 000000000..f9e45f1ce Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej4.png b/wadsrc_bm/static/brightmaps/doom/vilej4.png new file mode 100644 index 000000000..2c35d4aa0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej5.png b/wadsrc_bm/static/brightmaps/doom/vilej5.png new file mode 100644 index 000000000..40da621d2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej6.png b/wadsrc_bm/static/brightmaps/doom/vilej6.png new file mode 100644 index 000000000..ba3620ef6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej7.png b/wadsrc_bm/static/brightmaps/doom/vilej7.png new file mode 100644 index 000000000..1b98db0c2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilej8.png b/wadsrc_bm/static/brightmaps/doom/vilej8.png new file mode 100644 index 000000000..1c4fc05e2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilej8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek1.png b/wadsrc_bm/static/brightmaps/doom/vilek1.png new file mode 100644 index 000000000..204b6963f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek2.png b/wadsrc_bm/static/brightmaps/doom/vilek2.png new file mode 100644 index 000000000..34dc1c6e3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek3.png b/wadsrc_bm/static/brightmaps/doom/vilek3.png new file mode 100644 index 000000000..c24152dc6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek4.png b/wadsrc_bm/static/brightmaps/doom/vilek4.png new file mode 100644 index 000000000..268241dd6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek5.png b/wadsrc_bm/static/brightmaps/doom/vilek5.png new file mode 100644 index 000000000..a2d742dee Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek6.png b/wadsrc_bm/static/brightmaps/doom/vilek6.png new file mode 100644 index 000000000..025d95c3a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek7.png b/wadsrc_bm/static/brightmaps/doom/vilek7.png new file mode 100644 index 000000000..cadd45a67 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilek8.png b/wadsrc_bm/static/brightmaps/doom/vilek8.png new file mode 100644 index 000000000..f3a79e724 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilek8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel1.png b/wadsrc_bm/static/brightmaps/doom/vilel1.png new file mode 100644 index 000000000..fbfd4fe44 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel2.png b/wadsrc_bm/static/brightmaps/doom/vilel2.png new file mode 100644 index 000000000..7e5b9946e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel3.png b/wadsrc_bm/static/brightmaps/doom/vilel3.png new file mode 100644 index 000000000..f949c0812 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel4.png b/wadsrc_bm/static/brightmaps/doom/vilel4.png new file mode 100644 index 000000000..3d8912874 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel5.png b/wadsrc_bm/static/brightmaps/doom/vilel5.png new file mode 100644 index 000000000..93289dcb8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel6.png b/wadsrc_bm/static/brightmaps/doom/vilel6.png new file mode 100644 index 000000000..63efe375f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel7.png b/wadsrc_bm/static/brightmaps/doom/vilel7.png new file mode 100644 index 000000000..d89739cd6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilel8.png b/wadsrc_bm/static/brightmaps/doom/vilel8.png new file mode 100644 index 000000000..eebf5c454 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilel8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem1.png b/wadsrc_bm/static/brightmaps/doom/vilem1.png new file mode 100644 index 000000000..bf90c37ae Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem2.png b/wadsrc_bm/static/brightmaps/doom/vilem2.png new file mode 100644 index 000000000..b99e00cbe Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem3.png b/wadsrc_bm/static/brightmaps/doom/vilem3.png new file mode 100644 index 000000000..8440e7dd6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem4.png b/wadsrc_bm/static/brightmaps/doom/vilem4.png new file mode 100644 index 000000000..c2c5f9e46 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem5.png b/wadsrc_bm/static/brightmaps/doom/vilem5.png new file mode 100644 index 000000000..08fa83dbd Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem6.png b/wadsrc_bm/static/brightmaps/doom/vilem6.png new file mode 100644 index 000000000..436c98271 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem7.png b/wadsrc_bm/static/brightmaps/doom/vilem7.png new file mode 100644 index 000000000..04c3f875a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilem8.png b/wadsrc_bm/static/brightmaps/doom/vilem8.png new file mode 100644 index 000000000..9e4b78505 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilem8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen1.png b/wadsrc_bm/static/brightmaps/doom/vilen1.png new file mode 100644 index 000000000..e69819c77 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen2.png b/wadsrc_bm/static/brightmaps/doom/vilen2.png new file mode 100644 index 000000000..1979d5b76 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen3.png b/wadsrc_bm/static/brightmaps/doom/vilen3.png new file mode 100644 index 000000000..8a9e3c5d9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen4.png b/wadsrc_bm/static/brightmaps/doom/vilen4.png new file mode 100644 index 000000000..1f8dd401f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen5.png b/wadsrc_bm/static/brightmaps/doom/vilen5.png new file mode 100644 index 000000000..616209e86 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen6.png b/wadsrc_bm/static/brightmaps/doom/vilen6.png new file mode 100644 index 000000000..99418df5c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen7.png b/wadsrc_bm/static/brightmaps/doom/vilen7.png new file mode 100644 index 000000000..90fd7c9d0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilen8.png b/wadsrc_bm/static/brightmaps/doom/vilen8.png new file mode 100644 index 000000000..4ba737c78 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilen8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo1.png b/wadsrc_bm/static/brightmaps/doom/vileo1.png new file mode 100644 index 000000000..ec07c2461 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo2.png b/wadsrc_bm/static/brightmaps/doom/vileo2.png new file mode 100644 index 000000000..375580791 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo3.png b/wadsrc_bm/static/brightmaps/doom/vileo3.png new file mode 100644 index 000000000..365592a37 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo4.png b/wadsrc_bm/static/brightmaps/doom/vileo4.png new file mode 100644 index 000000000..ef7d2bf8b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo5.png b/wadsrc_bm/static/brightmaps/doom/vileo5.png new file mode 100644 index 000000000..7c0339697 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo6.png b/wadsrc_bm/static/brightmaps/doom/vileo6.png new file mode 100644 index 000000000..83fb00eed Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo7.png b/wadsrc_bm/static/brightmaps/doom/vileo7.png new file mode 100644 index 000000000..9deff5dcc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vileo8.png b/wadsrc_bm/static/brightmaps/doom/vileo8.png new file mode 100644 index 000000000..e5097856a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vileo8.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep1.png b/wadsrc_bm/static/brightmaps/doom/vilep1.png new file mode 100644 index 000000000..28162cc1d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep1.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep2.png b/wadsrc_bm/static/brightmaps/doom/vilep2.png new file mode 100644 index 000000000..c2dc72c6e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep2.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep3.png b/wadsrc_bm/static/brightmaps/doom/vilep3.png new file mode 100644 index 000000000..20e2d96c3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep3.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep4.png b/wadsrc_bm/static/brightmaps/doom/vilep4.png new file mode 100644 index 000000000..2aaaf49a9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep4.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep5.png b/wadsrc_bm/static/brightmaps/doom/vilep5.png new file mode 100644 index 000000000..8aac2d406 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep5.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep6.png b/wadsrc_bm/static/brightmaps/doom/vilep6.png new file mode 100644 index 000000000..cce3301a9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep6.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep7.png b/wadsrc_bm/static/brightmaps/doom/vilep7.png new file mode 100644 index 000000000..e159aeac0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep7.png differ diff --git a/wadsrc_bm/static/brightmaps/doom/vilep8.png b/wadsrc_bm/static/brightmaps/doom/vilep8.png new file mode 100644 index 000000000..71d88866b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/doom/vilep8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/BEASI1.png b/wadsrc_bm/static/brightmaps/heretic/BEASI1.png new file mode 100644 index 000000000..0a19b43b8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/BEASI1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/BEASI2I8.png b/wadsrc_bm/static/brightmaps/heretic/BEASI2I8.png new file mode 100644 index 000000000..187cbb346 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/BEASI2I8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/BEASI3I7.png b/wadsrc_bm/static/brightmaps/heretic/BEASI3I7.png new file mode 100644 index 000000000..d3d7b8f27 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/BEASI3I7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CHDLA0.png b/wadsrc_bm/static/brightmaps/heretic/CHDLA0.png new file mode 100644 index 000000000..41a0f6a88 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CHDLA0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CHDLB0.png b/wadsrc_bm/static/brightmaps/heretic/CHDLB0.png new file mode 100644 index 000000000..cf551809e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CHDLB0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CHDLC0.png b/wadsrc_bm/static/brightmaps/heretic/CHDLC0.png new file mode 100644 index 000000000..b881e8214 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CHDLC0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKI0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKI0.png new file mode 100644 index 000000000..782dec58f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKI0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKJ0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKJ0.png new file mode 100644 index 000000000..3feb2be43 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKJ0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKK0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKK0.png new file mode 100644 index 000000000..576a03682 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKK0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKL0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKL0.png new file mode 100644 index 000000000..7ba9fbbab Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKL0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKM0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKM0.png new file mode 100644 index 000000000..0cd0fd06b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKM0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/CLNKN0.png b/wadsrc_bm/static/brightmaps/heretic/CLNKN0.png new file mode 100644 index 000000000..89af9c1b5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/CLNKN0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD1.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD1.png new file mode 100644 index 000000000..c96bc6c7d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD2.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD2.png new file mode 100644 index 000000000..1f2befd89 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD3.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD3.png new file mode 100644 index 000000000..db5360e2d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD4.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD4.png new file mode 100644 index 000000000..8f0c4212e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD5.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD5.png new file mode 100644 index 000000000..50fcfcd64 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD6.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD6.png new file mode 100644 index 000000000..395ae0fb6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD7.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD7.png new file mode 100644 index 000000000..e1362d4ff Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXD8.png b/wadsrc_bm/static/brightmaps/heretic/IMPXD8.png new file mode 100644 index 000000000..df216ac7c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXD8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE1.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE1.png new file mode 100644 index 000000000..6adc110ce Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE2.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE2.png new file mode 100644 index 000000000..518f9c1a7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE3.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE3.png new file mode 100644 index 000000000..316c3ecc3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE4.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE4.png new file mode 100644 index 000000000..959a5cfd2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE5.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE5.png new file mode 100644 index 000000000..652b426de Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE6.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE6.png new file mode 100644 index 000000000..b374b7be2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE7.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE7.png new file mode 100644 index 000000000..96608c722 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXE8.png b/wadsrc_bm/static/brightmaps/heretic/IMPXE8.png new file mode 100644 index 000000000..94b5f9507 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXE8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF1.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF1.png new file mode 100644 index 000000000..d6dfaebc9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF2.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF2.png new file mode 100644 index 000000000..ee3934811 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF3.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF3.png new file mode 100644 index 000000000..4ee0cf231 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF4.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF4.png new file mode 100644 index 000000000..9344cf57d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF5.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF5.png new file mode 100644 index 000000000..da598d4be Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF6.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF6.png new file mode 100644 index 000000000..d22bf8942 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF7.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF7.png new file mode 100644 index 000000000..13bc8ebb9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/IMPXF8.png b/wadsrc_bm/static/brightmaps/heretic/IMPXF8.png new file mode 100644 index 000000000..03fc7c236 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/IMPXF8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHB1.png b/wadsrc_bm/static/brightmaps/heretic/LICHB1.png new file mode 100644 index 000000000..fc7d83921 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHB1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHB2B8.png b/wadsrc_bm/static/brightmaps/heretic/LICHB2B8.png new file mode 100644 index 000000000..a5e3565f7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHB2B8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHB3B7.png b/wadsrc_bm/static/brightmaps/heretic/LICHB3B7.png new file mode 100644 index 000000000..0992e0e9a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHB3B7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHC0.png b/wadsrc_bm/static/brightmaps/heretic/LICHC0.png new file mode 100644 index 000000000..cc28951c0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHC0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHD0.png b/wadsrc_bm/static/brightmaps/heretic/LICHD0.png new file mode 100644 index 000000000..76679dbd1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHD0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHE0.png b/wadsrc_bm/static/brightmaps/heretic/LICHE0.png new file mode 100644 index 000000000..c00bf135f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHE0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHF0.png b/wadsrc_bm/static/brightmaps/heretic/LICHF0.png new file mode 100644 index 000000000..065598a9d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHF0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHG0.png b/wadsrc_bm/static/brightmaps/heretic/LICHG0.png new file mode 100644 index 000000000..9d707324e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHG0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/LICHH0.png b/wadsrc_bm/static/brightmaps/heretic/LICHH0.png new file mode 100644 index 000000000..b2e39d506 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/LICHH0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/PLAYF1.png b/wadsrc_bm/static/brightmaps/heretic/PLAYF1.png new file mode 100644 index 000000000..c3c4817da Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/PLAYF1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/PLAYF2F8.png b/wadsrc_bm/static/brightmaps/heretic/PLAYF2F8.png new file mode 100644 index 000000000..e42de9266 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/PLAYF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/PLAYF3F7.png b/wadsrc_bm/static/brightmaps/heretic/PLAYF3F7.png new file mode 100644 index 000000000..8aae224ee Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/PLAYF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/PLAYF4F6.png b/wadsrc_bm/static/brightmaps/heretic/PLAYF4F6.png new file mode 100644 index 000000000..0b893064d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/PLAYF4F6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHA0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHA0.png new file mode 100644 index 000000000..328c0363f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHA0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHB0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHB0.png new file mode 100644 index 000000000..61b111e54 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHB0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHC0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHC0.png new file mode 100644 index 000000000..9bbcffbde Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHC0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHD0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHD0.png new file mode 100644 index 000000000..22a51d62d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHD0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHE0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHE0.png new file mode 100644 index 000000000..acfa9c9a3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHE0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHF0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHF0.png new file mode 100644 index 000000000..68c78cd7a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHF0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHG0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHG0.png new file mode 100644 index 000000000..b43ad9dc2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHG0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SDTHH0.png b/wadsrc_bm/static/brightmaps/heretic/SDTHH0.png new file mode 100644 index 000000000..c6393b551 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SDTHH0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R1.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R1.png new file mode 100644 index 000000000..a60cc15fc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R2.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R2.png new file mode 100644 index 000000000..e369c437f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R3.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R3.png new file mode 100644 index 000000000..81e042385 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R4.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R4.png new file mode 100644 index 000000000..d54a2dbcf Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R5.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R5.png new file mode 100644 index 000000000..4fa0696eb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R6.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R6.png new file mode 100644 index 000000000..7ad493b16 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R7.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R7.png new file mode 100644 index 000000000..ecc3e1cd4 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2R8.png b/wadsrc_bm/static/brightmaps/heretic/SOR2R8.png new file mode 100644 index 000000000..6150dc46c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2R8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S1.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S1.png new file mode 100644 index 000000000..0365f4491 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S2.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S2.png new file mode 100644 index 000000000..a5ab0c3a6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S3.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S3.png new file mode 100644 index 000000000..c793d5712 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S4.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S4.png new file mode 100644 index 000000000..bfc18a04d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S5.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S5.png new file mode 100644 index 000000000..a32e46d6b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S6.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S6.png new file mode 100644 index 000000000..b57ad7117 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S7.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S7.png new file mode 100644 index 000000000..f73a05c19 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2S8.png b/wadsrc_bm/static/brightmaps/heretic/SOR2S8.png new file mode 100644 index 000000000..708f81e25 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2S8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T1.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T1.png new file mode 100644 index 000000000..8c980b09f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T2.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T2.png new file mode 100644 index 000000000..0eaa52c1d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T2.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T3.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T3.png new file mode 100644 index 000000000..4a7519576 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T3.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T4.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T4.png new file mode 100644 index 000000000..a77238767 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T4.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T5.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T5.png new file mode 100644 index 000000000..0a6d72d3e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T6.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T6.png new file mode 100644 index 000000000..3beb542fa Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T7.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T7.png new file mode 100644 index 000000000..186715a3a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/SOR2T8.png b/wadsrc_bm/static/brightmaps/heretic/SOR2T8.png new file mode 100644 index 000000000..58e7e87e2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/SOR2T8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/VLCOE0.png b/wadsrc_bm/static/brightmaps/heretic/VLCOE0.png new file mode 100644 index 000000000..b5058c570 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/VLCOE0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDC1.png b/wadsrc_bm/static/brightmaps/heretic/WZRDC1.png new file mode 100644 index 000000000..d4fb4ab47 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDC1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDC2C8.png b/wadsrc_bm/static/brightmaps/heretic/WZRDC2C8.png new file mode 100644 index 000000000..8abe02262 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDC2C8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDC3C7.png b/wadsrc_bm/static/brightmaps/heretic/WZRDC3C7.png new file mode 100644 index 000000000..139467032 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDC3C7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDC4C6.png b/wadsrc_bm/static/brightmaps/heretic/WZRDC4C6.png new file mode 100644 index 000000000..446272b65 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDC4C6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDC5.png b/wadsrc_bm/static/brightmaps/heretic/WZRDC5.png new file mode 100644 index 000000000..d4fb4ab47 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDC5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDD1.png b/wadsrc_bm/static/brightmaps/heretic/WZRDD1.png new file mode 100644 index 000000000..c516516dc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDD1.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDD2D8.png b/wadsrc_bm/static/brightmaps/heretic/WZRDD2D8.png new file mode 100644 index 000000000..066954491 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDD2D8.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDD3D7.png b/wadsrc_bm/static/brightmaps/heretic/WZRDD3D7.png new file mode 100644 index 000000000..980e7286f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDD3D7.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDD4D6.png b/wadsrc_bm/static/brightmaps/heretic/WZRDD4D6.png new file mode 100644 index 000000000..b1ba1d202 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDD4D6.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDD5.png b/wadsrc_bm/static/brightmaps/heretic/WZRDD5.png new file mode 100644 index 000000000..7394eae62 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDD5.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDF0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDF0.png new file mode 100644 index 000000000..c47019cb0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDF0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDG0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDG0.png new file mode 100644 index 000000000..92bfa5ce1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDG0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDH0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDH0.png new file mode 100644 index 000000000..e6518ce5a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDH0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDI0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDI0.png new file mode 100644 index 000000000..1ccd71e26 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDI0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDJ0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDJ0.png new file mode 100644 index 000000000..43a845620 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDJ0.png differ diff --git a/wadsrc_bm/static/brightmaps/heretic/WZRDK0.png b/wadsrc_bm/static/brightmaps/heretic/WZRDK0.png new file mode 100644 index 000000000..d5d52c473 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/heretic/WZRDK0.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CDLRA0.png b/wadsrc_bm/static/brightmaps/hexen/CDLRA0.png new file mode 100644 index 000000000..b6dba0050 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CDLRA0.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CDLRB0.png b/wadsrc_bm/static/brightmaps/hexen/CDLRB0.png new file mode 100644 index 000000000..fd0a687ff Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CDLRB0.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CDLRC0.png b/wadsrc_bm/static/brightmaps/hexen/CDLRC0.png new file mode 100644 index 000000000..687106816 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CDLRC0.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CENTF1.png b/wadsrc_bm/static/brightmaps/hexen/CENTF1.png new file mode 100644 index 000000000..bce50ffe4 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CENTF1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CENTF2.png b/wadsrc_bm/static/brightmaps/hexen/CENTF2.png new file mode 100644 index 000000000..23ba1876c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CENTF2.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/CENTF8.png b/wadsrc_bm/static/brightmaps/hexen/CENTF8.png new file mode 100644 index 000000000..da9bdf69f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/CENTF8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/ICEYG1.png b/wadsrc_bm/static/brightmaps/hexen/ICEYG1.png new file mode 100644 index 000000000..6a4e2cd01 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/ICEYG1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/ICEYG2G8.png b/wadsrc_bm/static/brightmaps/hexen/ICEYG2G8.png new file mode 100644 index 000000000..3b18f61f9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/ICEYG2G8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/ICEYG3G7.png b/wadsrc_bm/static/brightmaps/hexen/ICEYG3G7.png new file mode 100644 index 000000000..35927e629 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/ICEYG3G7.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/ICEYG4G6.png b/wadsrc_bm/static/brightmaps/hexen/ICEYG4G6.png new file mode 100644 index 000000000..a6f727182 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/ICEYG4G6.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/ICEYG5.png b/wadsrc_bm/static/brightmaps/hexen/ICEYG5.png new file mode 100644 index 000000000..b219d6853 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/ICEYG5.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF1.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF1.png new file mode 100644 index 000000000..fbfd6822e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF2.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF2.png new file mode 100644 index 000000000..b7e617a20 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF2.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF3.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF3.png new file mode 100644 index 000000000..3ca5f9f45 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF3.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF4.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF4.png new file mode 100644 index 000000000..cb67cc179 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF4.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF5.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF5.png new file mode 100644 index 000000000..55dcaf6a4 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF5.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF6.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF6.png new file mode 100644 index 000000000..488808e50 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF6.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF7.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF7.png new file mode 100644 index 000000000..b70f45e94 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF7.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/MAGEF8.png b/wadsrc_bm/static/brightmaps/hexen/MAGEF8.png new file mode 100644 index 000000000..a55c5a0c7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/MAGEF8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHE1.png b/wadsrc_bm/static/brightmaps/hexen/WRTHE1.png new file mode 100644 index 000000000..083ff7c73 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHE1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHE2E8.png b/wadsrc_bm/static/brightmaps/hexen/WRTHE2E8.png new file mode 100644 index 000000000..c9c0e483c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHE2E8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHE3E7.png b/wadsrc_bm/static/brightmaps/hexen/WRTHE3E7.png new file mode 100644 index 000000000..1f9772895 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHE3E7.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHE4E6.png b/wadsrc_bm/static/brightmaps/hexen/WRTHE4E6.png new file mode 100644 index 000000000..264a4c0df Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHE4E6.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHE5.png b/wadsrc_bm/static/brightmaps/hexen/WRTHE5.png new file mode 100644 index 000000000..53d504835 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHE5.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHF1.png b/wadsrc_bm/static/brightmaps/hexen/WRTHF1.png new file mode 100644 index 000000000..d29521070 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHF1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHF2F8.png b/wadsrc_bm/static/brightmaps/hexen/WRTHF2F8.png new file mode 100644 index 000000000..afadf834d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHF2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHF3F7.png b/wadsrc_bm/static/brightmaps/hexen/WRTHF3F7.png new file mode 100644 index 000000000..1e27285ce Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHF3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHF4F6.png b/wadsrc_bm/static/brightmaps/hexen/WRTHF4F6.png new file mode 100644 index 000000000..29111a3fd Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHF4F6.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHF5.png b/wadsrc_bm/static/brightmaps/hexen/WRTHF5.png new file mode 100644 index 000000000..91ec627ca Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHF5.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHG1.png b/wadsrc_bm/static/brightmaps/hexen/WRTHG1.png new file mode 100644 index 000000000..e56d4fea0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHG1.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHG2G8.png b/wadsrc_bm/static/brightmaps/hexen/WRTHG2G8.png new file mode 100644 index 000000000..6bc265bc6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHG2G8.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHG3G7.png b/wadsrc_bm/static/brightmaps/hexen/WRTHG3G7.png new file mode 100644 index 000000000..58efdb75f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHG3G7.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHG4G6.png b/wadsrc_bm/static/brightmaps/hexen/WRTHG4G6.png new file mode 100644 index 000000000..aafc01176 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHG4G6.png differ diff --git a/wadsrc_bm/static/brightmaps/hexen/WRTHG5.png b/wadsrc_bm/static/brightmaps/hexen/WRTHG5.png new file mode 100644 index 000000000..3615bebb2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/hexen/WRTHG5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE1.png b/wadsrc_bm/static/brightmaps/strife/MLDRE1.png new file mode 100644 index 000000000..a7c723d62 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE2.png b/wadsrc_bm/static/brightmaps/strife/MLDRE2.png new file mode 100644 index 000000000..0305db515 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE3.png b/wadsrc_bm/static/brightmaps/strife/MLDRE3.png new file mode 100644 index 000000000..ec6c34db7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE4.png b/wadsrc_bm/static/brightmaps/strife/MLDRE4.png new file mode 100644 index 000000000..22c8db94f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE5.png b/wadsrc_bm/static/brightmaps/strife/MLDRE5.png new file mode 100644 index 000000000..118e48d09 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE6.png b/wadsrc_bm/static/brightmaps/strife/MLDRE6.png new file mode 100644 index 000000000..bed99f89e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE7.png b/wadsrc_bm/static/brightmaps/strife/MLDRE7.png new file mode 100644 index 000000000..f90672e02 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/MLDRE8.png b/wadsrc_bm/static/brightmaps/strife/MLDRE8.png new file mode 100644 index 000000000..94f18ca65 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/MLDRE8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG1.png b/wadsrc_bm/static/brightmaps/strife/PGRDG1.png new file mode 100644 index 000000000..c6e01e28e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG2.png b/wadsrc_bm/static/brightmaps/strife/PGRDG2.png new file mode 100644 index 000000000..45e5414f2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG3.png b/wadsrc_bm/static/brightmaps/strife/PGRDG3.png new file mode 100644 index 000000000..1bf159e4b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG4.png b/wadsrc_bm/static/brightmaps/strife/PGRDG4.png new file mode 100644 index 000000000..610d29ec6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG5.png b/wadsrc_bm/static/brightmaps/strife/PGRDG5.png new file mode 100644 index 000000000..3c437481d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG6.png b/wadsrc_bm/static/brightmaps/strife/PGRDG6.png new file mode 100644 index 000000000..1c36855e7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG7.png b/wadsrc_bm/static/brightmaps/strife/PGRDG7.png new file mode 100644 index 000000000..fa2412f7d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDG8.png b/wadsrc_bm/static/brightmaps/strife/PGRDG8.png new file mode 100644 index 000000000..378feb8c6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDG8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDI0.png b/wadsrc_bm/static/brightmaps/strife/PGRDI0.png new file mode 100644 index 000000000..4a1e3eaff Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDI0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDJ0.png b/wadsrc_bm/static/brightmaps/strife/PGRDJ0.png new file mode 100644 index 000000000..23b915deb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDJ0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDK0.png b/wadsrc_bm/static/brightmaps/strife/PGRDK0.png new file mode 100644 index 000000000..626ec4004 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDK0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDL0.png b/wadsrc_bm/static/brightmaps/strife/PGRDL0.png new file mode 100644 index 000000000..30da82890 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDL0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDM0.png b/wadsrc_bm/static/brightmaps/strife/PGRDM0.png new file mode 100644 index 000000000..cbee2897f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDM0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PGRDN0.png b/wadsrc_bm/static/brightmaps/strife/PGRDN0.png new file mode 100644 index 000000000..f097b1df3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PGRDN0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/PRGRO0.png b/wadsrc_bm/static/brightmaps/strife/PRGRO0.png new file mode 100644 index 000000000..1267140d3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/PRGRO0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/RBB3A0.png b/wadsrc_bm/static/brightmaps/strife/RBB3A0.png new file mode 100644 index 000000000..9c0d07351 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/RBB3A0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/RBB3B0.png b/wadsrc_bm/static/brightmaps/strife/RBB3B0.png new file mode 100644 index 000000000..03a4d8476 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/RBB3B0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1J0.png b/wadsrc_bm/static/brightmaps/strife/ROB1J0.png new file mode 100644 index 000000000..e6f423766 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1J0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1K0.png b/wadsrc_bm/static/brightmaps/strife/ROB1K0.png new file mode 100644 index 000000000..61925a2d5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1K0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1L0.png b/wadsrc_bm/static/brightmaps/strife/ROB1L0.png new file mode 100644 index 000000000..6e51ffa1a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1L0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1M0.png b/wadsrc_bm/static/brightmaps/strife/ROB1M0.png new file mode 100644 index 000000000..13fcabbeb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1M0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1N0.png b/wadsrc_bm/static/brightmaps/strife/ROB1N0.png new file mode 100644 index 000000000..f82245b64 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1N0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1O0.png b/wadsrc_bm/static/brightmaps/strife/ROB1O0.png new file mode 100644 index 000000000..94ac418a5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1O0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB1P0.png b/wadsrc_bm/static/brightmaps/strife/ROB1P0.png new file mode 100644 index 000000000..87c59a15f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB1P0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F1.png b/wadsrc_bm/static/brightmaps/strife/ROB2F1.png new file mode 100644 index 000000000..c6f85b0b2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F2.png b/wadsrc_bm/static/brightmaps/strife/ROB2F2.png new file mode 100644 index 000000000..21ed37563 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F3.png b/wadsrc_bm/static/brightmaps/strife/ROB2F3.png new file mode 100644 index 000000000..ea2917b43 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F4.png b/wadsrc_bm/static/brightmaps/strife/ROB2F4.png new file mode 100644 index 000000000..7c805d97a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F5.png b/wadsrc_bm/static/brightmaps/strife/ROB2F5.png new file mode 100644 index 000000000..ae3669a79 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F6.png b/wadsrc_bm/static/brightmaps/strife/ROB2F6.png new file mode 100644 index 000000000..5bb74e497 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F7.png b/wadsrc_bm/static/brightmaps/strife/ROB2F7.png new file mode 100644 index 000000000..fe11f5476 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2F8.png b/wadsrc_bm/static/brightmaps/strife/ROB2F8.png new file mode 100644 index 000000000..f19350a2a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2F8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2G0.png b/wadsrc_bm/static/brightmaps/strife/ROB2G0.png new file mode 100644 index 000000000..df39f0d16 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2G0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2H0.png b/wadsrc_bm/static/brightmaps/strife/ROB2H0.png new file mode 100644 index 000000000..cb64f9d09 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2H0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2I0.png b/wadsrc_bm/static/brightmaps/strife/ROB2I0.png new file mode 100644 index 000000000..11a6f151e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2I0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2J0.png b/wadsrc_bm/static/brightmaps/strife/ROB2J0.png new file mode 100644 index 000000000..19572c6a3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2J0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2K0.png b/wadsrc_bm/static/brightmaps/strife/ROB2K0.png new file mode 100644 index 000000000..76935bebb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2K0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2L0.png b/wadsrc_bm/static/brightmaps/strife/ROB2L0.png new file mode 100644 index 000000000..c33e51178 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2L0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2M0.png b/wadsrc_bm/static/brightmaps/strife/ROB2M0.png new file mode 100644 index 000000000..d0200d1c8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2M0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2N0.png b/wadsrc_bm/static/brightmaps/strife/ROB2N0.png new file mode 100644 index 000000000..e68aa58cc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2N0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB2O0.png b/wadsrc_bm/static/brightmaps/strife/ROB2O0.png new file mode 100644 index 000000000..3510ca12f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB2O0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F1.png b/wadsrc_bm/static/brightmaps/strife/ROB3F1.png new file mode 100644 index 000000000..8e95df7f6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F2.png b/wadsrc_bm/static/brightmaps/strife/ROB3F2.png new file mode 100644 index 000000000..6a144b7b5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F3.png b/wadsrc_bm/static/brightmaps/strife/ROB3F3.png new file mode 100644 index 000000000..ec92b6c98 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F4.png b/wadsrc_bm/static/brightmaps/strife/ROB3F4.png new file mode 100644 index 000000000..80a9420cd Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F5.png b/wadsrc_bm/static/brightmaps/strife/ROB3F5.png new file mode 100644 index 000000000..4cedbae57 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F6.png b/wadsrc_bm/static/brightmaps/strife/ROB3F6.png new file mode 100644 index 000000000..0773b64e3 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F7.png b/wadsrc_bm/static/brightmaps/strife/ROB3F7.png new file mode 100644 index 000000000..2b8fe006e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3F8.png b/wadsrc_bm/static/brightmaps/strife/ROB3F8.png new file mode 100644 index 000000000..709de86b2 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3F8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H1.png b/wadsrc_bm/static/brightmaps/strife/ROB3H1.png new file mode 100644 index 000000000..d1d2482bf Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H2.png b/wadsrc_bm/static/brightmaps/strife/ROB3H2.png new file mode 100644 index 000000000..75a0cecd8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H3.png b/wadsrc_bm/static/brightmaps/strife/ROB3H3.png new file mode 100644 index 000000000..dd082dddc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H4.png b/wadsrc_bm/static/brightmaps/strife/ROB3H4.png new file mode 100644 index 000000000..32f9d9d76 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H5.png b/wadsrc_bm/static/brightmaps/strife/ROB3H5.png new file mode 100644 index 000000000..d93f8a96e Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H6.png b/wadsrc_bm/static/brightmaps/strife/ROB3H6.png new file mode 100644 index 000000000..6d0171b17 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H7.png b/wadsrc_bm/static/brightmaps/strife/ROB3H7.png new file mode 100644 index 000000000..04ba80e7c Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3H8.png b/wadsrc_bm/static/brightmaps/strife/ROB3H8.png new file mode 100644 index 000000000..a728ced7a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3H8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I1.png b/wadsrc_bm/static/brightmaps/strife/ROB3I1.png new file mode 100644 index 000000000..e76aab455 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I2.png b/wadsrc_bm/static/brightmaps/strife/ROB3I2.png new file mode 100644 index 000000000..9aab11709 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I3.png b/wadsrc_bm/static/brightmaps/strife/ROB3I3.png new file mode 100644 index 000000000..a00229462 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I4.png b/wadsrc_bm/static/brightmaps/strife/ROB3I4.png new file mode 100644 index 000000000..4aade5fcc Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I5.png b/wadsrc_bm/static/brightmaps/strife/ROB3I5.png new file mode 100644 index 000000000..4e39617d7 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I5.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I6.png b/wadsrc_bm/static/brightmaps/strife/ROB3I6.png new file mode 100644 index 000000000..c8a63623b Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I7.png b/wadsrc_bm/static/brightmaps/strife/ROB3I7.png new file mode 100644 index 000000000..7009e2de8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3I8.png b/wadsrc_bm/static/brightmaps/strife/ROB3I8.png new file mode 100644 index 000000000..4880d6242 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3I8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J1.png b/wadsrc_bm/static/brightmaps/strife/ROB3J1.png new file mode 100644 index 000000000..e97f9eec6 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J1.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J2.png b/wadsrc_bm/static/brightmaps/strife/ROB3J2.png new file mode 100644 index 000000000..1e54031e5 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J2.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J3.png b/wadsrc_bm/static/brightmaps/strife/ROB3J3.png new file mode 100644 index 000000000..74392cceb Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J3.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J4.png b/wadsrc_bm/static/brightmaps/strife/ROB3J4.png new file mode 100644 index 000000000..85e324869 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J4.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J6.png b/wadsrc_bm/static/brightmaps/strife/ROB3J6.png new file mode 100644 index 000000000..7a8dc6540 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J6.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J7.png b/wadsrc_bm/static/brightmaps/strife/ROB3J7.png new file mode 100644 index 000000000..08e531958 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J7.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3J8.png b/wadsrc_bm/static/brightmaps/strife/ROB3J8.png new file mode 100644 index 000000000..0aad4ac5f Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3J8.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3M0.png b/wadsrc_bm/static/brightmaps/strife/ROB3M0.png new file mode 100644 index 000000000..8ff876d39 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3M0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3N0.png b/wadsrc_bm/static/brightmaps/strife/ROB3N0.png new file mode 100644 index 000000000..953df2057 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3N0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3O0.png b/wadsrc_bm/static/brightmaps/strife/ROB3O0.png new file mode 100644 index 000000000..dc6e98186 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3O0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3P0.png b/wadsrc_bm/static/brightmaps/strife/ROB3P0.png new file mode 100644 index 000000000..4c15cbd51 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3P0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3Q0.png b/wadsrc_bm/static/brightmaps/strife/ROB3Q0.png new file mode 100644 index 000000000..c66b6d654 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3Q0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3T0.png b/wadsrc_bm/static/brightmaps/strife/ROB3T0.png new file mode 100644 index 000000000..aa2db3891 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3T0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3U0.png b/wadsrc_bm/static/brightmaps/strife/ROB3U0.png new file mode 100644 index 000000000..2faae7cc9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3U0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3V0.png b/wadsrc_bm/static/brightmaps/strife/ROB3V0.png new file mode 100644 index 000000000..9c3af1027 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3V0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3W0.png b/wadsrc_bm/static/brightmaps/strife/ROB3W0.png new file mode 100644 index 000000000..799a8f944 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3W0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3X0.png b/wadsrc_bm/static/brightmaps/strife/ROB3X0.png new file mode 100644 index 000000000..fa45574c8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3X0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3Y0.png b/wadsrc_bm/static/brightmaps/strife/ROB3Y0.png new file mode 100644 index 000000000..c9b50001d Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3Y0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3Z0.png b/wadsrc_bm/static/brightmaps/strife/ROB3Z0.png new file mode 100644 index 000000000..3bcb03248 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3Z0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3[0.png b/wadsrc_bm/static/brightmaps/strife/ROB3[0.png new file mode 100644 index 000000000..7ccf983e0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3[0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3]0.png b/wadsrc_bm/static/brightmaps/strife/ROB3]0.png new file mode 100644 index 000000000..e86a1f1fe Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3]0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/ROB3^0.png b/wadsrc_bm/static/brightmaps/strife/ROB3^0.png new file mode 100644 index 000000000..f67a424b8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/ROB3^0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/SEWRH0.png b/wadsrc_bm/static/brightmaps/strife/SEWRH0.png new file mode 100644 index 000000000..b439f2617 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/SEWRH0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKP0.png b/wadsrc_bm/static/brightmaps/strife/STLKP0.png new file mode 100644 index 000000000..12c44fe99 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKP0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKQ0.png b/wadsrc_bm/static/brightmaps/strife/STLKQ0.png new file mode 100644 index 000000000..5065e9c6a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKQ0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKR0.png b/wadsrc_bm/static/brightmaps/strife/STLKR0.png new file mode 100644 index 000000000..16fa49db0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKR0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKS0.png b/wadsrc_bm/static/brightmaps/strife/STLKS0.png new file mode 100644 index 000000000..5065e9c6a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKS0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKT0.png b/wadsrc_bm/static/brightmaps/strife/STLKT0.png new file mode 100644 index 000000000..a65e78c34 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKT0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKU0.png b/wadsrc_bm/static/brightmaps/strife/STLKU0.png new file mode 100644 index 000000000..c4399848a Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKU0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKV0.png b/wadsrc_bm/static/brightmaps/strife/STLKV0.png new file mode 100644 index 000000000..ce4ea1741 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKV0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKW0.png b/wadsrc_bm/static/brightmaps/strife/STLKW0.png new file mode 100644 index 000000000..b50fcd5c8 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKW0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKX0.png b/wadsrc_bm/static/brightmaps/strife/STLKX0.png new file mode 100644 index 000000000..4ae22cb05 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKX0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKY0.png b/wadsrc_bm/static/brightmaps/strife/STLKY0.png new file mode 100644 index 000000000..417f7fed1 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKY0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLKZ0.png b/wadsrc_bm/static/brightmaps/strife/STLKZ0.png new file mode 100644 index 000000000..acb6a3fa0 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLKZ0.png differ diff --git a/wadsrc_bm/static/brightmaps/strife/STLK[0.png b/wadsrc_bm/static/brightmaps/strife/STLK[0.png new file mode 100644 index 000000000..6b47d56e9 Binary files /dev/null and b/wadsrc_bm/static/brightmaps/strife/STLK[0.png differ diff --git a/wadsrc_bm/static/doomdefs.bm b/wadsrc_bm/static/doomdefs.bm new file mode 100644 index 000000000..78159bddd --- /dev/null +++ b/wadsrc_bm/static/doomdefs.bm @@ -0,0 +1,2181 @@ +brightmap sprite CELLA0 +{ + map "brightmaps/doom/cella0.png" + iwad +} + +brightmap sprite CELPA0 +{ + map "brightmaps/doom/celpa0.png" + iwad +} + +brightmap sprite PLAYF1 +{ + map "brightmaps/doom/PLAYf1.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF2F8 +{ + map "brightmaps/doom/PLAYf2f8.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF3F7 +{ + map "brightmaps/doom/PLAYf3f7.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF4F6 +{ + map "brightmaps/doom/PLAYf4f6.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF5 +{ + map "brightmaps/doom/PLAYf5.png" + iwad + disablefullbright +} + +brightmap sprite POSSF1 +{ + map "brightmaps/doom/possf1.png" + iwad + disablefullbright +} + +brightmap sprite POSSF2F8 +{ + map "brightmaps/doom/possf2f8.png" + iwad + disablefullbright +} + +brightmap sprite POSSF3F7 +{ + map "brightmaps/doom/possf3f7.png" + iwad + disablefullbright +} + +brightmap sprite POSSF4F6 +{ + map "brightmaps/doom/possf4f6.png" + iwad + disablefullbright +} + +brightmap sprite POSSF5 +{ + map "brightmaps/doom/possf5.png" + iwad + disablefullbright +} + +brightmap sprite SPOSF1 +{ + map "brightmaps/doom/SPOSf1.png" + iwad + disablefullbright +} + +brightmap sprite SPOSF2F8 +{ + map "brightmaps/doom/SPOSf2f8.png" + iwad + disablefullbright +} + +brightmap sprite SPOSF3F7 +{ + map "brightmaps/doom/SPOSf3f7.png" + iwad + disablefullbright +} + +brightmap sprite SPOSF4F6 +{ + map "brightmaps/doom/SPOSf4f6.png" + iwad + disablefullbright +} + +brightmap sprite SPOSF5 +{ + iwad + map "brightmaps/doom/SPOSf5.png" + disablefullbright +} + +brightmap sprite CPOSE1 +{ + map "brightmaps/doom/CPOSE1.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE2 +{ + map "brightmaps/doom/CPOSE2.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE3 +{ + map "brightmaps/doom/CPOSE3.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE4 +{ + iwad + disablefullbright +} + +brightmap sprite CPOSE5 +{ + map "brightmaps/doom/CPOSE5.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE6 +{ + map "brightmaps/doom/CPOSE6.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE7 +{ + map "brightmaps/doom/CPOSE7.png" + iwad + disablefullbright +} + +brightmap sprite CPOSE8 +{ + map "brightmaps/doom/CPOSE8.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF1 +{ + map "brightmaps/doom/CPOSF1.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF2 +{ + map "brightmaps/doom/CPOSF2.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF3 +{ + map "brightmaps/doom/CPOSF3.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF4 +{ + map "brightmaps/doom/CPOSF4.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF5 +{ + map "brightmaps/doom/CPOSF5.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF6 +{ + map "brightmaps/doom/CPOSF6.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF7 +{ + map "brightmaps/doom/CPOSF7.png" + iwad + disablefullbright +} + +brightmap sprite CPOSF8 +{ + map "brightmaps/doom/CPOSF8.png" + iwad + disablefullbright +} + +brightmap sprite SSWVG0 +{ + map "brightmaps/doom/sswvg0.png" + iwad + disablefullbright +} + +brightmap sprite BSPIA1D1 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIA2a8 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIA3A7 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIA4A6 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIA5D5 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIG1 +{ + map "brightmaps/doom/bspig1.png" + iwad + disablefullbright +} + +brightmap sprite BSPIG2G8 +{ + map "brightmaps/doom/bspig2g8.png" + iwad + disablefullbright +} + +brightmap sprite BSPIG3G7 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIG4G6 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIG5 +{ + iwad + disablefullbright +} + +brightmap sprite BSPIH1 +{ + map "brightmaps/doom/bspih1.png" + iwad + disablefullbright +} + +brightmap sprite BSPIH2H8 +{ + map "brightmaps/doom/bspih2h8.png" + iwad + disablefullbright +} + +brightmap sprite BSPIH3H7 +{ + map "brightmaps/doom/bspih3h7.png" + iwad + disablefullbright +} + +brightmap sprite BSPIH4H6 +{ + map "brightmaps/doom/bspih4h6.png" + iwad + disablefullbright +} + +brightmap sprite BSPIH5 +{ + map "brightmaps/doom/bspih5.png" + iwad + disablefullbright +} + +brightmap sprite BOSSA1 +{ + map "brightmaps/doom/bossa1.png" + iwad +} + +brightmap sprite BOSSA2A8 +{ + map "brightmaps/doom/bossa2a8.png" + iwad +} + +brightmap sprite BOSSA3A7 +{ + map "brightmaps/doom/bossa3a7.png" + iwad +} + +brightmap sprite BOSSA4A6 +{ + map "brightmaps/doom/bossa4a6.png" + iwad +} + +brightmap sprite BOSSA5 +{ + map "brightmaps/doom/bossa5.png" + iwad +} + +brightmap sprite BOSSb1 +{ + map "brightmaps/doom/bossb1.png" + iwad +} + +brightmap sprite BOSSB2B8 +{ + map "brightmaps/doom/bossb2b8.png" + iwad +} + +brightmap sprite BOSSB3B7 +{ + map "brightmaps/doom/bossb3b7.png" + iwad +} + +brightmap sprite BOSSB4B6 +{ + map "brightmaps/doom/bossb4b6.png" + iwad +} + +brightmap sprite BOSSB5 +{ + map "brightmaps/doom/bossb5.png" + iwad +} + +brightmap sprite BOSSC1 +{ + map "brightmaps/doom/bossc1.png" + iwad +} + +brightmap sprite BOSSC2C8 +{ + map "brightmaps/doom/bossc2c8.png" + iwad +} + +brightmap sprite BOSSC3C7 +{ + map "brightmaps/doom/bossc3c7.png" + iwad +} + +brightmap sprite BOSSC4C6 +{ + map "brightmaps/doom/bossc4c6.png" + iwad +} + +brightmap sprite BOSSC5 +{ + map "brightmaps/doom/bossc5.png" + iwad +} + +brightmap sprite BOSSD1 +{ + map "brightmaps/doom/bossd1.png" + iwad +} + +brightmap sprite BOSSD2D8 +{ + map "brightmaps/doom/bossd2d8.png" + iwad +} + +brightmap sprite BOSSD3D7 +{ + map "brightmaps/doom/bossd3d7.png" + iwad +} + +brightmap sprite BOSSD4D6 +{ + map "brightmaps/doom/bossd4d6.png" + iwad +} + +brightmap sprite BOSSD5 +{ + map "brightmaps/doom/bossd5.png" + iwad +} + +brightmap sprite BOSSE1 +{ + map "brightmaps/doom/bosse1.png" + iwad +} + +brightmap sprite BOSSE2 +{ + map "brightmaps/doom/bosse2.png" + iwad +} + +brightmap sprite BOSSE3 +{ + map "brightmaps/doom/bosse3.png" + iwad +} + +brightmap sprite BOSSE4 +{ + map "brightmaps/doom/bosse4.png" + iwad +} + +brightmap sprite BOSSE5 +{ + map "brightmaps/doom/bosse5.png" + iwad +} + +brightmap sprite BOSSE6 +{ + map "brightmaps/doom/bosse6.png" + iwad +} + +brightmap sprite BOSSE7 +{ + map "brightmaps/doom/bosse7.png" + iwad +} + +brightmap sprite BOSSE8 +{ + map "brightmaps/doom/bosse8.png" + iwad +} + +brightmap sprite BOSSF1 +{ + map "brightmaps/doom/BOSSF1.png" + iwad +} + +brightmap sprite BOSSF2 +{ + map "brightmaps/doom/BOSSF2.png" + iwad +} + +brightmap sprite BOSSF3 +{ + map "brightmaps/doom/BOSSF3.png" + iwad +} + +brightmap sprite BOSSF4 +{ + map "brightmaps/doom/BOSSF4.png" + iwad +} + +brightmap sprite BOSSF5 +{ + map "brightmaps/doom/BOSSF5.png" + iwad +} + +brightmap sprite BOSSF6 +{ + map "brightmaps/doom/BOSSF6.png" + iwad +} + +brightmap sprite BOSSF7 +{ + map "brightmaps/doom/BOSSF7.png" + iwad +} + +brightmap sprite BOSSF8 +{ + map "brightmaps/doom/BOSSF8.png" + iwad +} + +brightmap sprite BOSSG1 +{ + map "brightmaps/doom/BOSSG1.png" + iwad +} + +brightmap sprite BOSSG2 +{ + map "brightmaps/doom/BOSSG2.png" + iwad +} + +brightmap sprite BOSSG3 +{ + map "brightmaps/doom/BOSSG3.png" + iwad +} + +brightmap sprite BOSSG4 +{ + map "brightmaps/doom/BOSSG4.png" + iwad +} + +brightmap sprite BOSSG5 +{ + map "brightmaps/doom/BOSSG5.png" + iwad +} + +brightmap sprite BOSSG6 +{ + map "brightmaps/doom/BOSSG6.png" + iwad +} + +brightmap sprite BOSSG7 +{ + map "brightmaps/doom/BOSSG7.png" + iwad +} + +brightmap sprite BOSSG8 +{ + map "brightmaps/doom/BOSSG8.png" + iwad +} + +brightmap sprite BOSSH1 +{ + map "brightmaps/doom/BOSSH1.png" + iwad +} + +brightmap sprite BOSSH2 +{ + map "brightmaps/doom/BOSSH2.png" + iwad +} + +brightmap sprite BOSSH3 +{ + map "brightmaps/doom/BOSSH3.png" + iwad +} + +brightmap sprite BOSSH4 +{ + map "brightmaps/doom/BOSSH4.png" + iwad +} + +brightmap sprite BOSSH5 +{ + map "brightmaps/doom/BOSSH5.png" + iwad +} + +brightmap sprite BOSSH6 +{ + map "brightmaps/doom/BOSSH6.png" + iwad +} + +brightmap sprite BOSSH7 +{ + map "brightmaps/doom/BOSSH7.png" + iwad +} + +brightmap sprite BOSSH8 +{ + map "brightmaps/doom/BOSSH8.png" + iwad +} + +brightmap sprite BOSSI0 +{ + map "brightmaps/doom/BOSSI0.png" + iwad +} + +brightmap sprite BOSSJ0 +{ + map "brightmaps/doom/BOSSJ0.png" + iwad +} + +brightmap sprite BOSSK0 +{ + map "brightmaps/doom/BOSSK0.png" + iwad +} + +brightmap sprite BOSSL0 +{ + map "brightmaps/doom/BOSSL0.png" + iwad +} + +brightmap sprite BOSSM0 +{ + map "brightmaps/doom/BOSSM0.png" + iwad +} + +brightmap sprite BOS2A1C1 +{ + map "brightmaps/doom/bossa1.png" + iwad +} + +brightmap sprite BOS2A2C8 +{ + map "brightmaps/doom/bossa2a8.png" + iwad +} + +brightmap sprite BOS2A3C7 +{ + map "brightmaps/doom/bossa3a7.png" + iwad +} + +brightmap sprite BOS2A4C6 +{ + map "brightmaps/doom/bossa4a6.png" + iwad +} + +brightmap sprite BOS2A5C5 +{ + map "brightmaps/doom/bossa5.png" + iwad +} + +brightmap sprite BOS2b1D1 +{ + map "brightmaps/doom/bossb1.png" + iwad +} + +brightmap sprite BOS2B2D8 +{ + map "brightmaps/doom/bossb2b8.png" + iwad +} + +brightmap sprite BOS2B3D7 +{ + map "brightmaps/doom/bossb3b7.png" + iwad +} + +brightmap sprite BOS2B4D6 +{ + map "brightmaps/doom/bossb4b6.png" + iwad +} + +brightmap sprite BOS2B5D5 +{ + map "brightmaps/doom/bossb5.png" + iwad +} + +brightmap sprite BOS2E1 +{ + map "brightmaps/doom/bosse1.png" + iwad +} + +brightmap sprite BOS2E2 +{ + map "brightmaps/doom/bosse2.png" + iwad +} + +brightmap sprite BOS2E3 +{ + map "brightmaps/doom/bosse3.png" + iwad +} + +brightmap sprite BOS2E4 +{ + map "brightmaps/doom/bosse4.png" + iwad +} + +brightmap sprite BOS2E5 +{ + map "brightmaps/doom/bosse5.png" + iwad +} + +brightmap sprite BOS2E6 +{ + map "brightmaps/doom/bosse6.png" + iwad +} + +brightmap sprite BOS2E7 +{ + map "brightmaps/doom/bosse7.png" + iwad +} + +brightmap sprite BOS2E8 +{ + map "brightmaps/doom/bosse8.png" + iwad +} + +brightmap sprite BOS2F1 +{ + map "brightmaps/doom/BOSSF1.png" + iwad +} + +brightmap sprite BOS2F2 +{ + map "brightmaps/doom/BOSSF2.png" + iwad +} + +brightmap sprite BOS2F3 +{ + map "brightmaps/doom/BOSSF3.png" + iwad +} + +brightmap sprite BOS2F4 +{ + map "brightmaps/doom/BOSSF4.png" + iwad +} + +brightmap sprite BOS2F5 +{ + map "brightmaps/doom/BOSSF5.png" + iwad +} + +brightmap sprite BOS2F6 +{ + map "brightmaps/doom/BOSSF6.png" + iwad +} + +brightmap sprite BOS2F7 +{ + map "brightmaps/doom/BOSSF7.png" + iwad +} + +brightmap sprite BOS2F8 +{ + map "brightmaps/doom/BOSSF8.png" + iwad +} + +brightmap sprite BOS2G1 +{ + map "brightmaps/doom/BOSSG1.png" + iwad +} + +brightmap sprite BOS2G2 +{ + map "brightmaps/doom/BOSSG2.png" + iwad +} + +brightmap sprite BOS2G3 +{ + map "brightmaps/doom/BOSSG3.png" + iwad +} + +brightmap sprite BOS2G4 +{ + map "brightmaps/doom/BOSSG4.png" + iwad +} + +brightmap sprite BOS2G5 +{ + map "brightmaps/doom/BOSSG5.png" + iwad +} + +brightmap sprite BOS2G6 +{ + map "brightmaps/doom/BOSSG6.png" + iwad +} + +brightmap sprite BOS2G7 +{ + map "brightmaps/doom/BOSSG7.png" + iwad +} + +brightmap sprite BOS2G8 +{ + map "brightmaps/doom/BOSSG8.png" + iwad +} + +brightmap sprite BOS2H1 +{ + map "brightmaps/doom/BOSSH1.png" + iwad +} + +brightmap sprite BOS2H2 +{ + map "brightmaps/doom/BOSSH2.png" + iwad +} + +brightmap sprite BOS2H3 +{ + map "brightmaps/doom/BOSSH3.png" + iwad +} + +brightmap sprite BOS2H4 +{ + map "brightmaps/doom/BOSSH4.png" + iwad +} + +brightmap sprite BOS2H5 +{ + map "brightmaps/doom/BOSSH5.png" + iwad +} + +brightmap sprite BOS2H6 +{ + map "brightmaps/doom/BOSSH6.png" + iwad +} + +brightmap sprite BOS2H7 +{ + map "brightmaps/doom/BOSSH7.png" + iwad +} + +brightmap sprite BOS2H8 +{ + map "brightmaps/doom/BOSSH8.png" + iwad +} + +brightmap sprite BOS2I0 +{ + map "brightmaps/doom/BOSSI0.png" + iwad +} + +brightmap sprite BOS2J0 +{ + map "brightmaps/doom/BOSSJ0.png" + iwad +} + +brightmap sprite BOS2K0 +{ + map "brightmaps/doom/BOSSK0.png" + iwad +} + +brightmap sprite BOS2L0 +{ + map "brightmaps/doom/BOSSL0.png" + iwad +} + +brightmap sprite BOS2M0 +{ + map "brightmaps/doom/BOSSM0.png" + iwad +} + +brightmap sprite BOS2A6C4 +{ + map "brightmaps/doom/BOS2A6C4.png" + iwad +} + +brightmap sprite BOS2A7C3 +{ + map "brightmaps/doom/BOS2A7C3.png" + iwad +} + +brightmap sprite BOS2A8C2 +{ + map "brightmaps/doom/BOS2A8C2.png" + iwad +} + +brightmap sprite BOS2B6D4 +{ + map "brightmaps/doom/BOS2B6D4.png" + iwad +} + +brightmap sprite BOS2B7D3 +{ + map "brightmaps/doom/BOS2B7D3.png" + iwad +} + +brightmap sprite BOS2B8D2 +{ + map "brightmaps/doom/BOS2B8D2.png" + iwad +} + +brightmap sprite SKELJ1 +{ + map "brightmaps/doom/SKELJ1.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ2 +{ + map "brightmaps/doom/SKELJ2.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ3 +{ + map "brightmaps/doom/SKELJ3.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ4 +{ + map "brightmaps/doom/SKELJ4.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ5 +{ + map "brightmaps/doom/SKELJ5.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ6 +{ + map "brightmaps/doom/SKELJ6.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ7 +{ + map "brightmaps/doom/SKELJ7.png" + iwad + disablefullbright +} + +brightmap sprite SKELJ8 +{ + map "brightmaps/doom/SKELJ8.png" + iwad + disablefullbright +} + +brightmap sprite FATTH1 +{ + map "brightmaps/doom/FATTH1.png" + iwad + disablefullbright +} + +brightmap sprite FATTH2H8 +{ + map "brightmaps/doom/FATTH2H8.png" + iwad + disablefullbright +} + +brightmap sprite FATTH3H7 +{ + map "brightmaps/doom/FATTH3H7.png" + iwad + disablefullbright +} + +brightmap sprite FATTH4H6 +{ + map "brightmaps/doom/FATTH4H6.png" + iwad + disablefullbright +} + +brightmap sprite FATTH5 +{ + map "brightmaps/doom/FATTH5.png" + iwad + disablefullbright +} + +brightmap sprite HEADC1 +{ + map "brightmaps/doom/HEADC1.png" + iwad + disablefullbright +} + +brightmap sprite HEADC2C8 +{ + map "brightmaps/doom/HEADC2C8.png" + iwad + disablefullbright +} + +brightmap sprite HEADC3C7 +{ + map "brightmaps/doom/HEADC3C7.png" + iwad + disablefullbright +} + +brightmap sprite HEADD1 +{ + map "brightmaps/doom/HEADD1.png" + iwad + disablefullbright +} + +brightmap sprite HEADD2D8 +{ + map "brightmaps/doom/HEADD2D8.png" + iwad + disablefullbright +} + +brightmap sprite HEADD3D7 +{ + map "brightmaps/doom/HEADD3D7.png" + iwad + disablefullbright +} + +brightmap sprite HEADD4D6 +{ + iwad + disablefullbright +} + +brightmap sprite HEADD5 +{ + iwad + disablefullbright +} + +brightmap sprite PAINF1 +{ + map "brightmaps/doom/PAINf1.png" + iwad + disablefullbright +} + +brightmap sprite PAINF2F8 +{ + map "brightmaps/doom/PAINf2f8.png" + iwad + disablefullbright +} + +brightmap sprite PAINF3F7 +{ + map "brightmaps/doom/PAINf3f7.png" + iwad + disablefullbright +} + +brightmap sprite PAINF4F6 +{ + iwad + disablefullbright +} + +brightmap sprite PAINF5 +{ + iwad + disablefullbright +} + +brightmap sprite CYBRF1 +{ + map "brightmaps/doom/CYBRF1.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF2 +{ + map "brightmaps/doom/CYBRF2.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF3 +{ + map "brightmaps/doom/CYBRF3.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF4 +{ + map "brightmaps/doom/CYBRF4.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF5 +{ + map "brightmaps/doom/CYBRF5.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF6 +{ + map "brightmaps/doom/CYBRF6.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF7 +{ + map "brightmaps/doom/CYBRF7.png" + iwad + disablefullbright +} + +brightmap sprite CYBRF8 +{ + map "brightmaps/doom/CYBRF8.png" + iwad + disablefullbright +} + +brightmap sprite CYBRJ0 +{ + map "brightmaps/doom/CYBRJ0.png" + iwad + disablefullbright +} + +brightmap sprite CYBRK0 +{ + map "brightmaps/doom/CYBRK0.png" + iwad + disablefullbright +} + +brightmap sprite CYBRL0 +{ + map "brightmaps/doom/CYBRL0.png" + iwad + disablefullbright +} + +brightmap sprite CYBRM0 +{ + map "brightmaps/doom/CYBRM0.png" + iwad + disablefullbright +} + +brightmap sprite CYBRN0 +{ + map "brightmaps/doom/CYBRN0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDA1D1 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDA2D8 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDA3D7 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDA4D6 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDA5D5 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDG1 +{ + map "brightmaps/doom/SPIDG1.png" + iwad + disablefullbright +} + +brightmap sprite SPIDG2G8 +{ + map "brightmaps/doom/SPIDG2G8.png" + iwad + disablefullbright +} + +brightmap sprite SPIDG3G7 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDG4G6 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDG5 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDH1 +{ + map "brightmaps/doom/SPIDH1.png" + iwad + disablefullbright +} + +brightmap sprite SPIDG2G8 +{ + map "brightmaps/doom/SPIDH2H8.png" + iwad + disablefullbright +} + +brightmap sprite SPIDH3H7 +{ + map "brightmaps/doom/SPIDH3H7.png" + iwad + disablefullbright +} + +brightmap sprite SPIDH4H6 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDH5 +{ + iwad + disablefullbright +} + +brightmap sprite SPIDH1 +{ + map "brightmaps/doom/SPIDH1.png" + iwad + disablefullbright +} + +brightmap sprite SPIDL0 +{ + map "brightmaps/doom/SPIDL0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDM0 +{ + map "brightmaps/doom/SPIDM0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDN0 +{ + map "brightmaps/doom/SPIDN0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDO0 +{ + map "brightmaps/doom/SPIDO0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDP0 +{ + map "brightmaps/doom/SPIDP0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDQ0 +{ + map "brightmaps/doom/SPIDQ0.png" + iwad + disablefullbright +} + +brightmap sprite SPIDR0 +{ + map "brightmaps/doom/SPIDR0.png" + iwad + disablefullbright +} + +brightmap sprite BON2B0 +{ + map "brightmaps/doom/BON2B0.png" + iwad + disablefullbright +} + +brightmap sprite BON2c0 +{ + map "brightmaps/doom/BON2c0.png" + iwad + disablefullbright +} + +brightmap sprite BON2d0 +{ + map "brightmaps/doom/BON2d0.png" + iwad + disablefullbright +} + +brightmap sprite FCANA0 +{ + map "brightmaps/doom/FCANA0.png" + iwad + disablefullbright +} + +brightmap sprite FCANb0 +{ + map "brightmaps/doom/FCANb0.png" + iwad + disablefullbright +} + +brightmap sprite FCANc0 +{ + map "brightmaps/doom/FCANc0.png" + iwad + disablefullbright +} + +brightmap sprite treda0 +{ + map "brightmaps/doom/treda0.png" + iwad + disablefullbright +} + +brightmap sprite tredb0 +{ + map "brightmaps/doom/tredb0.png" + iwad + disablefullbright +} + +brightmap sprite tredc0 +{ + map "brightmaps/doom/tredc0.png" + iwad + disablefullbright +} + +brightmap sprite tredd0 +{ + map "brightmaps/doom/tredd0.png" + iwad + disablefullbright +} + +brightmap sprite TBLUA0 +{ + map "brightmaps/doom/treda0.png" + iwad + disablefullbright +} + +brightmap sprite TBLUb0 +{ + map "brightmaps/doom/TBLUb0.png" + iwad + disablefullbright +} + +brightmap sprite TBLUc0 +{ + map "brightmaps/doom/TBLUc0.png" + iwad + disablefullbright +} + +brightmap sprite TBLUd0 +{ + map "brightmaps/doom/tredd0.png" + iwad + disablefullbright +} + +brightmap sprite TGRNA0 +{ + map "brightmaps/doom/treda0.png" + iwad + disablefullbright +} + +brightmap sprite TGRNb0 +{ + map "brightmaps/doom/tredb0.png" + iwad + disablefullbright +} + +brightmap sprite TGRNc0 +{ + map "brightmaps/doom/tredc0.png" + iwad + disablefullbright +} + +brightmap sprite TGRNd0 +{ + map "brightmaps/doom/tredd0.png" + iwad + disablefullbright +} + +brightmap sprite SMRTA0 +{ + map "brightmaps/doom/SMRTA0.png" + iwad + disablefullbright +} + +brightmap sprite SMRTb0 +{ + map "brightmaps/doom/SMRTb0.png" + iwad + disablefullbright +} + +brightmap sprite SMRTc0 +{ + map "brightmaps/doom/SMRTc0.png" + iwad + disablefullbright +} + +brightmap sprite SMRTd0 +{ + map "brightmaps/doom/SMRTd0.png" + iwad + disablefullbright +} + +brightmap sprite SMbTA0 +{ + map "brightmaps/doom/SMRTA0.png" + iwad + disablefullbright +} + +brightmap sprite SMbTb0 +{ + map "brightmaps/doom/SMRTb0.png" + iwad + disablefullbright +} + +brightmap sprite SMbTc0 +{ + map "brightmaps/doom/SMRTc0.png" + iwad + disablefullbright +} + +brightmap sprite SMbTd0 +{ + map "brightmaps/doom/SMRTd0.png" + iwad + disablefullbright +} + +brightmap sprite SMgTA0 +{ + map "brightmaps/doom/SMRTA0.png" + iwad + disablefullbright +} + +brightmap sprite SMgTb0 +{ + map "brightmaps/doom/SMRTb0.png" + iwad + disablefullbright +} + +brightmap sprite SMgTc0 +{ + map "brightmaps/doom/SMRTc0.png" + iwad + disablefullbright +} + +brightmap sprite SMgTd0 +{ + map "brightmaps/doom/SMRTd0.png" + iwad + disablefullbright +} + +brightmap sprite vileg1 +{ + map "brightmaps/doom/vileg1.png" + iwad + disablefullbright +} + +brightmap sprite vileg2 +{ + map "brightmaps/doom/vileg2.png" + iwad + disablefullbright +} + +brightmap sprite vileg3 +{ + map "brightmaps/doom/vileg3.png" + iwad + disablefullbright +} + +brightmap sprite vileg4 +{ + map "brightmaps/doom/vileg4.png" + iwad + disablefullbright +} + +brightmap sprite vileg5 +{ + map "brightmaps/doom/vileg5.png" + iwad + disablefullbright +} + +brightmap sprite vileg6 +{ + map "brightmaps/doom/vileg6.png" + iwad + disablefullbright +} + +brightmap sprite vileg7 +{ + map "brightmaps/doom/vileg7.png" + iwad + disablefullbright +} + +brightmap sprite vileg8 +{ + map "brightmaps/doom/vileg8.png" + iwad + disablefullbright +} + +brightmap sprite vileh1 +{ + map "brightmaps/doom/vileh1.png" + iwad + disablefullbright +} + +brightmap sprite vileh2 +{ + map "brightmaps/doom/vileh2.png" + iwad + disablefullbright +} + +brightmap sprite vileh3 +{ + map "brightmaps/doom/vileh3.png" + iwad + disablefullbright +} + +brightmap sprite vileh4 +{ + map "brightmaps/doom/vileh4.png" + iwad + disablefullbright +} + +brightmap sprite vileh5 +{ + map "brightmaps/doom/vileh5.png" + iwad + disablefullbright +} + +brightmap sprite vileh6 +{ + map "brightmaps/doom/vileh6.png" + iwad + disablefullbright +} + +brightmap sprite vileh7 +{ + map "brightmaps/doom/vileh7.png" + iwad + disablefullbright +} + +brightmap sprite vileh8 +{ + map "brightmaps/doom/vileh8.png" + iwad + disablefullbright +} + +brightmap sprite vilei1 +{ + map "brightmaps/doom/vilei1.png" + iwad + disablefullbright +} + +brightmap sprite vilei2 +{ + map "brightmaps/doom/vilei2.png" + iwad + disablefullbright +} + +brightmap sprite vilei3 +{ + map "brightmaps/doom/vilei3.png" + iwad + disablefullbright +} + +brightmap sprite vilei4 +{ + map "brightmaps/doom/vilei4.png" + iwad + disablefullbright +} + +brightmap sprite vilei5 +{ + map "brightmaps/doom/vilei5.png" + iwad + disablefullbright +} + +brightmap sprite vilei6 +{ + map "brightmaps/doom/vilei6.png" + iwad + disablefullbright +} + +brightmap sprite vilei7 +{ + map "brightmaps/doom/vilei7.png" + iwad + disablefullbright +} + +brightmap sprite vilei8 +{ + map "brightmaps/doom/vilei8.png" + iwad + disablefullbright +} + +brightmap sprite vilej1 +{ + map "brightmaps/doom/vilej1.png" + iwad + disablefullbright +} + +brightmap sprite vilej2 +{ + map "brightmaps/doom/vilej2.png" + iwad + disablefullbright +} + +brightmap sprite vilej3 +{ + map "brightmaps/doom/vilej3.png" + iwad + disablefullbright +} + +brightmap sprite vilej4 +{ + map "brightmaps/doom/vilej4.png" + iwad + disablefullbright +} + +brightmap sprite vilej5 +{ + map "brightmaps/doom/vilej5.png" + iwad + disablefullbright +} + +brightmap sprite vilej6 +{ + map "brightmaps/doom/vilej6.png" + iwad + disablefullbright +} + +brightmap sprite vilej7 +{ + map "brightmaps/doom/vilej7.png" + iwad + disablefullbright +} + +brightmap sprite vilej8 +{ + map "brightmaps/doom/vilej8.png" + iwad + disablefullbright +} + +brightmap sprite vilek1 +{ + map "brightmaps/doom/vilek1.png" + iwad + disablefullbright +} + +brightmap sprite vilek2 +{ + map "brightmaps/doom/vilek2.png" + iwad + disablefullbright +} + +brightmap sprite vilek3 +{ + map "brightmaps/doom/vilek3.png" + iwad + disablefullbright +} + +brightmap sprite vilek4 +{ + map "brightmaps/doom/vilek4.png" + iwad + disablefullbright +} + +brightmap sprite vilek5 +{ + map "brightmaps/doom/vilek5.png" + iwad + disablefullbright +} + +brightmap sprite vilek6 +{ + map "brightmaps/doom/vilek6.png" + iwad + disablefullbright +} + +brightmap sprite vilek7 +{ + map "brightmaps/doom/vilek7.png" + iwad + disablefullbright +} + +brightmap sprite vilek8 +{ + map "brightmaps/doom/vilek8.png" + iwad + disablefullbright +} + +brightmap sprite vilel1 +{ + map "brightmaps/doom/vilel1.png" + iwad + disablefullbright +} + +brightmap sprite vilel2 +{ + map "brightmaps/doom/vilel2.png" + iwad + disablefullbright +} + +brightmap sprite vilel3 +{ + map "brightmaps/doom/vilel3.png" + iwad + disablefullbright +} + +brightmap sprite vilel4 +{ + map "brightmaps/doom/vilel4.png" + iwad + disablefullbright +} + +brightmap sprite vilel5 +{ + map "brightmaps/doom/vilel5.png" + iwad + disablefullbright +} + +brightmap sprite vilel6 +{ + map "brightmaps/doom/vilel6.png" + iwad + disablefullbright +} + +brightmap sprite vilel7 +{ + map "brightmaps/doom/vilel7.png" + iwad + disablefullbright +} + +brightmap sprite vilel8 +{ + map "brightmaps/doom/vilel8.png" + iwad + disablefullbright +} + +brightmap sprite vilem1 +{ + map "brightmaps/doom/vilem1.png" + iwad + disablefullbright +} + +brightmap sprite vilem2 +{ + map "brightmaps/doom/vilem2.png" + iwad + disablefullbright +} + +brightmap sprite vilem3 +{ + map "brightmaps/doom/vilem3.png" + iwad + disablefullbright +} + +brightmap sprite vilem4 +{ + map "brightmaps/doom/vilem4.png" + iwad + disablefullbright +} + +brightmap sprite vilem5 +{ + map "brightmaps/doom/vilem5.png" + iwad + disablefullbright +} + +brightmap sprite vilem6 +{ + map "brightmaps/doom/vilem6.png" + iwad + disablefullbright +} + +brightmap sprite vilem7 +{ + map "brightmaps/doom/vilem7.png" + iwad + disablefullbright +} + +brightmap sprite vilem8 +{ + map "brightmaps/doom/vilem8.png" + iwad + disablefullbright +} + +brightmap sprite vilen1 +{ + map "brightmaps/doom/vilen1.png" + iwad + disablefullbright +} + +brightmap sprite vilen2 +{ + map "brightmaps/doom/vilen2.png" + iwad + disablefullbright +} + +brightmap sprite vilen3 +{ + map "brightmaps/doom/vilen3.png" + iwad + disablefullbright +} + +brightmap sprite vilen4 +{ + map "brightmaps/doom/vilen4.png" + iwad + disablefullbright +} + +brightmap sprite vilen5 +{ + map "brightmaps/doom/vilen5.png" + iwad + disablefullbright +} + +brightmap sprite vilen6 +{ + map "brightmaps/doom/vilen6.png" + iwad + disablefullbright +} + +brightmap sprite vilen7 +{ + map "brightmaps/doom/vilen7.png" + iwad + disablefullbright +} + +brightmap sprite vilen8 +{ + map "brightmaps/doom/vilen8.png" + iwad + disablefullbright +} + +brightmap sprite vileo1 +{ + map "brightmaps/doom/vileo1.png" + iwad + disablefullbright +} + +brightmap sprite vileo2 +{ + map "brightmaps/doom/vileo2.png" + iwad + disablefullbright +} + +brightmap sprite vileo3 +{ + map "brightmaps/doom/vileo3.png" + iwad + disablefullbright +} + +brightmap sprite vileo4 +{ + map "brightmaps/doom/vileo4.png" + iwad + disablefullbright +} + +brightmap sprite vileo5 +{ + map "brightmaps/doom/vileo5.png" + iwad + disablefullbright +} + +brightmap sprite vileo6 +{ + map "brightmaps/doom/vileo6.png" + iwad + disablefullbright +} + +brightmap sprite vileo7 +{ + map "brightmaps/doom/vileo7.png" + iwad + disablefullbright +} + +brightmap sprite vileo8 +{ + map "brightmaps/doom/vileo8.png" + iwad + disablefullbright +} + +brightmap sprite vilep1 +{ + map "brightmaps/doom/vilep1.png" + iwad + disablefullbright +} + +brightmap sprite vilep2 +{ + map "brightmaps/doom/vilep2.png" + iwad + disablefullbright +} + +brightmap sprite vilep3 +{ + map "brightmaps/doom/vilep3.png" + iwad + disablefullbright +} + +brightmap sprite vilep4 +{ + map "brightmaps/doom/vilep4.png" + iwad + disablefullbright +} + +brightmap sprite vilep5 +{ + map "brightmaps/doom/vilep5.png" + iwad + disablefullbright +} + +brightmap sprite vilep6 +{ + map "brightmaps/doom/vilep6.png" + iwad + disablefullbright +} + +brightmap sprite vilep7 +{ + map "brightmaps/doom/vilep7.png" + iwad + disablefullbright +} + +brightmap sprite vilep8 +{ + map "brightmaps/doom/vilep8.png" + iwad + disablefullbright +} diff --git a/wadsrc_bm/static/hexndefs.bm b/wadsrc_bm/static/hexndefs.bm new file mode 100644 index 000000000..180f6b15c --- /dev/null +++ b/wadsrc_bm/static/hexndefs.bm @@ -0,0 +1,268 @@ + +brightmap sprite CDLRA0 +{ + map "brightmaps/hexen/CDLRA0.png" + iwad + disablefullbright +} + +brightmap sprite CDLRB0 +{ + map "brightmaps/hexen/CDLRB0.png" + iwad + disablefullbright +} + +brightmap sprite CDLRC0 +{ + map "brightmaps/hexen/CDLRC0.png" + iwad + disablefullbright +} + +brightmap sprite CENTF1 +{ + map "brightmaps/hexen/CENTF1.png" + iwad + disablefullbright +} + +brightmap sprite CENTF2 +{ + map "brightmaps/hexen/CENTF2.png" + iwad + disablefullbright +} + +brightmap sprite CENTF3 +{ + iwad + disablefullbright +} + +brightmap sprite CENTF4 +{ + iwad + disablefullbright +} + +brightmap sprite CENTF5 +{ + iwad + disablefullbright +} + +brightmap sprite CENTF6 +{ + iwad + disablefullbright +} + +brightmap sprite CENTF7 +{ + iwad + disablefullbright +} + +brightmap sprite CENTF8 +{ + map "brightmaps/hexen/CENTF8.png" + iwad + disablefullbright +} + +brightmap sprite ICEYG1 +{ + map "brightmaps/hexen/ICEYG1.png" + iwad + disablefullbright +} + +brightmap sprite ICEYG2G8 +{ + map "brightmaps/hexen/ICEYG2G8.png" + iwad + disablefullbright +} + +brightmap sprite ICEYG3G7 +{ + map "brightmaps/hexen/ICEYG3G7.png" + iwad + disablefullbright +} + +brightmap sprite ICEYG4G6 +{ + map "brightmaps/hexen/ICEYG4G6.png" + iwad + disablefullbright +} + +brightmap sprite ICEYG5 +{ + map "brightmaps/hexen/ICEYG5.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF1 +{ + map "brightmaps/hexen/MAGEF1.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF2 +{ + map "brightmaps/hexen/MAGEF2.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF3 +{ + map "brightmaps/hexen/MAGEF3.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF4 +{ + map "brightmaps/hexen/MAGEF4.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF5 +{ + map "brightmaps/hexen/MAGEF5.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF6 +{ + map "brightmaps/hexen/MAGEF6.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF7 +{ + map "brightmaps/hexen/MAGEF7.png" + iwad + disablefullbright +} + +brightmap sprite MAGEF8 +{ + map "brightmaps/hexen/MAGEF8.png" + iwad + disablefullbright +} + +brightmap sprite WRTHE1 +{ + map "brightmaps/hexen/WRTHE1.png" + iwad + disablefullbright +} + +brightmap sprite WRTHE2E8 +{ + map "brightmaps/hexen/WRTHE2E8.png" + iwad + disablefullbright +} + +brightmap sprite WRTHE3E7 +{ + map "brightmaps/hexen/WRTHE3E7.png" + iwad + disablefullbright +} + +brightmap sprite WRTHE4E6 +{ + map "brightmaps/hexen/WRTHE4E6.png" + iwad + disablefullbright +} + +brightmap sprite WRTHE5 +{ + map "brightmaps/hexen/WRTHE5.png" + iwad + disablefullbright +} + +brightmap sprite WRTHF1 +{ + map "brightmaps/hexen/WRTHF1.png" + iwad + disablefullbright +} + +brightmap sprite WRTHF2F8 +{ + map "brightmaps/hexen/WRTHF2F8.png" + iwad + disablefullbright +} + +brightmap sprite WRTHF3F7 +{ + map "brightmaps/hexen/WRTHF3F7.png" + iwad + disablefullbright +} + +brightmap sprite WRTHF4F6 +{ + map "brightmaps/hexen/WRTHF4F6.png" + iwad + disablefullbright +} + +brightmap sprite WRTHF5 +{ + map "brightmaps/hexen/WRTHF5.png" + iwad + disablefullbright +} + +brightmap sprite WRTHG1 +{ + map "brightmaps/hexen/WRTHG1.png" + iwad + disablefullbright +} + +brightmap sprite WRTHG2G8 +{ + map "brightmaps/hexen/WRTHG2G8.png" + iwad + disablefullbright +} + +brightmap sprite WRTHG3G7 +{ + map "brightmaps/hexen/WRTHG3G7.png" + iwad + disablefullbright +} + +brightmap sprite WRTHG4G6 +{ + map "brightmaps/hexen/WRTHG4G6.png" + iwad + disablefullbright +} + +brightmap sprite WRTHG5 +{ + map "brightmaps/hexen/WRTHG5.png" + iwad + disablefullbright +} diff --git a/wadsrc_bm/static/hticdefs.bm b/wadsrc_bm/static/hticdefs.bm new file mode 100644 index 000000000..a61afcf62 --- /dev/null +++ b/wadsrc_bm/static/hticdefs.bm @@ -0,0 +1,692 @@ +brightmap sprite BEASI1 +{ + map "brightmaps/heretic/BEASI1.png" + iwad + disablefullbright +} + +brightmap sprite BEASI2I8 +{ + map "brightmaps/heretic/BEASI2I8.png" + iwad + disablefullbright +} + +brightmap sprite BEASI3I7 +{ + map "brightmaps/heretic/BEASI3I7.png" + iwad + disablefullbright +} + +brightmap sprite CHDLA0 +{ + map "brightmaps/heretic/CHDLA0.png" + iwad + disablefullbright +} + +brightmap sprite CHDLB0 +{ + map "brightmaps/heretic/CHDLB0.png" + iwad + disablefullbright +} + +brightmap sprite CHDLC0 +{ + map "brightmaps/heretic/CHDLC0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKI0 +{ + map "brightmaps/heretic/CLNKI0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKJ0 +{ + map "brightmaps/heretic/CLNKJ0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKK0 +{ + map "brightmaps/heretic/CLNKK0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKL0 +{ + map "brightmaps/heretic/CLNKL0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKM0 +{ + map "brightmaps/heretic/CLNKM0.png" + iwad + disablefullbright +} + +brightmap sprite CLNKN0 +{ + map "brightmaps/heretic/CLNKN0.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD1 +{ + map "brightmaps/heretic/IMPXD1.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD2 +{ + map "brightmaps/heretic/IMPXD2.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD3 +{ + map "brightmaps/heretic/IMPXD3.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD4 +{ + map "brightmaps/heretic/IMPXD4.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD5 +{ + map "brightmaps/heretic/IMPXD5.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD6 +{ + map "brightmaps/heretic/IMPXD6.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD7 +{ + map "brightmaps/heretic/IMPXD7.png" + iwad + disablefullbright +} + +brightmap sprite IMPXD8 +{ + map "brightmaps/heretic/IMPXD8.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE1 +{ + map "brightmaps/heretic/IMPXE1.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE2 +{ + map "brightmaps/heretic/IMPXE2.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE3 +{ + map "brightmaps/heretic/IMPXE3.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE4 +{ + map "brightmaps/heretic/IMPXE4.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE5 +{ + map "brightmaps/heretic/IMPXE5.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE6 +{ + map "brightmaps/heretic/IMPXE6.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE7 +{ + map "brightmaps/heretic/IMPXE7.png" + iwad + disablefullbright +} + +brightmap sprite IMPXE8 +{ + map "brightmaps/heretic/IMPXE8.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF1 +{ + map "brightmaps/heretic/IMPXF1.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF2 +{ + map "brightmaps/heretic/IMPXF2.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF3 +{ + map "brightmaps/heretic/IMPXF3.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF4 +{ + map "brightmaps/heretic/IMPXF4.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF5 +{ + map "brightmaps/heretic/IMPXF5.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF6 +{ + map "brightmaps/heretic/IMPXF6.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF7 +{ + map "brightmaps/heretic/IMPXF7.png" + iwad + disablefullbright +} + +brightmap sprite IMPXF8 +{ + map "brightmaps/heretic/IMPXF8.png" + iwad + disablefullbright +} + +brightmap sprite LICHB1 +{ + map "brightmaps/heretic/LICHB1.png" + iwad + disablefullbright +} + +brightmap sprite LICHB2B8 +{ + map "brightmaps/heretic/LICHB2B8.png" + iwad + disablefullbright +} + +brightmap sprite LICHB3M7 +{ + map "brightmaps/heretic/LICHB3B7.png" + iwad + disablefullbright +} + +brightmap sprite LICHC0 +{ + map "brightmaps/heretic/LICHC0.png" + iwad + disablefullbright +} + +brightmap sprite LICHD0 +{ + map "brightmaps/heretic/LICHD0.png" + iwad + disablefullbright +} + +brightmap sprite LICHE0 +{ + map "brightmaps/heretic/LICHE0.png" + iwad + disablefullbright +} + +brightmap sprite LICHF0 +{ + map "brightmaps/heretic/LICHF0.png" + iwad + disablefullbright +} + +brightmap sprite LICHG0 +{ + map "brightmaps/heretic/LICHG0.png" + iwad + disablefullbright +} + +brightmap sprite LICHH0 +{ + map "brightmaps/heretic/LICHH0.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF1 +{ + map "brightmaps/heretic/PLAYf1.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF2F8 +{ + map "brightmaps/heretic/PLAYf2f8.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF3F7 +{ + map "brightmaps/heretic/PLAYf3f7.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF4F6 +{ + map "brightmaps/heretic/PLAYf4f6.png" + iwad + disablefullbright +} + +brightmap sprite PLAYF5 +{ + iwad + disablefullbright +} + +brightmap sprite SDTHA0 +{ + map "brightmaps/heretic/SDTHA0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHB0 +{ + map "brightmaps/heretic/SDTHB0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHC0 +{ + map "brightmaps/heretic/SDTHC0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHD0 +{ + map "brightmaps/heretic/SDTHD0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHE0 +{ + map "brightmaps/heretic/SDTHE0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHF0 +{ + map "brightmaps/heretic/SDTHF0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHG0 +{ + map "brightmaps/heretic/SDTHG0.png" + iwad + disablefullbright +} + +brightmap sprite SDTHH0 +{ + map "brightmaps/heretic/SDTHH0.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R1 +{ + map "brightmaps/heretic/SOR2R1.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R2 +{ + map "brightmaps/heretic/SOR2R2.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R3 +{ + map "brightmaps/heretic/SOR2R3.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R4 +{ + map "brightmaps/heretic/SOR2R4.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R5 +{ + map "brightmaps/heretic/SOR2R5.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R6 +{ + map "brightmaps/heretic/SOR2R6.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R7 +{ + map "brightmaps/heretic/SOR2R7.png" + iwad + disablefullbright +} + +brightmap sprite SOR2R8 +{ + map "brightmaps/heretic/SOR2R8.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S1 +{ + map "brightmaps/heretic/SOR2S1.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S2 +{ + map "brightmaps/heretic/SOR2S2.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S3 +{ + map "brightmaps/heretic/SOR2S3.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S4 +{ + map "brightmaps/heretic/SOR2S4.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S5 +{ + map "brightmaps/heretic/SOR2S5.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S6 +{ + map "brightmaps/heretic/SOR2S6.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S7 +{ + map "brightmaps/heretic/SOR2S7.png" + iwad + disablefullbright +} + +brightmap sprite SOR2S8 +{ + map "brightmaps/heretic/SOR2S8.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T1 +{ + map "brightmaps/heretic/SOR2T1.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T2 +{ + map "brightmaps/heretic/SOR2T2.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T3 +{ + map "brightmaps/heretic/SOR2T3.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T4 +{ + map "brightmaps/heretic/SOR2T4.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T5 +{ + map "brightmaps/heretic/SOR2T5.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T6 +{ + map "brightmaps/heretic/SOR2T6.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T7 +{ + map "brightmaps/heretic/SOR2T7.png" + iwad + disablefullbright +} + +brightmap sprite SOR2T8 +{ + map "brightmaps/heretic/SOR2T8.png" + iwad + disablefullbright +} + +brightmap sprite VLCOE0 +{ + map "brightmaps/heretic/VLCOE0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDC1 +{ + map "brightmaps/heretic/WZRDC1.png" + iwad + disablefullbright +} + +brightmap sprite WZRDC2C8 +{ + map "brightmaps/heretic/WZRDC2C8.png" + iwad + disablefullbright +} + +brightmap sprite WZRDC3C7 +{ + map "brightmaps/heretic/WZRDC3C7.png" + iwad + disablefullbright +} + +brightmap sprite WZRDC4C6 +{ + map "brightmaps/heretic/WZRDC4C6.png" + iwad + disablefullbright +} + +brightmap sprite WZRDC5 +{ + map "brightmaps/heretic/WZRDC5.png" + iwad + disablefullbright +} + +brightmap sprite WZRDD1 +{ + map "brightmaps/heretic/WZRDD1.png" + iwad + disablefullbright +} + +brightmap sprite WZRDD2D8 +{ + map "brightmaps/heretic/WZRDD2D8.png" + iwad + disablefullbright +} + +brightmap sprite WZRDD3D7 +{ + map "brightmaps/heretic/WZRDD3D7.png" + iwad + disablefullbright +} + +brightmap sprite WZRDD4D6 +{ + map "brightmaps/heretic/WZRDD4D6.png" + iwad + disablefullbright +} + +brightmap sprite WZRDD5 +{ + map "brightmaps/heretic/WZRDD5.png" + iwad + disablefullbright +} + +brightmap sprite WZRDF0 +{ + map "brightmaps/heretic/WZRDF0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDG0 +{ + map "brightmaps/heretic/WZRDG0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDH0 +{ + map "brightmaps/heretic/WZRDH0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDI0 +{ + map "brightmaps/heretic/WZRDI0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDJ0 +{ + map "brightmaps/heretic/WZRDJ0.png" + iwad + disablefullbright +} + +brightmap sprite WZRDK0 +{ + map "brightmaps/heretic/WZRDK0.png" + iwad + disablefullbright +} + diff --git a/wadsrc_bm/static/strfdefs.bm b/wadsrc_bm/static/strfdefs.bm new file mode 100644 index 000000000..75c2fd9c2 --- /dev/null +++ b/wadsrc_bm/static/strfdefs.bm @@ -0,0 +1,1253 @@ +brightmap sprite HMN1F1 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F2 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F3 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F4 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F5 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F6 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F7 +{ + iwad + disablefullbright +} + +brightmap sprite HMN1F8 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF1 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF2 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF3 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF4 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF5 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF6 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF7 +{ + iwad + disablefullbright +} + +brightmap sprite LEADF8 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRE1 +{ + map "brightmaps/strife/MLDRE1.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE2 +{ + map "brightmaps/strife/MLDRE2.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE3 +{ + map "brightmaps/strife/MLDRE3.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE4 +{ + map "brightmaps/strife/MLDRE4.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE5 +{ + map "brightmaps/strife/MLDRE5.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE6 +{ + map "brightmaps/strife/MLDRE6.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE7 +{ + map "brightmaps/strife/MLDRE7.png" + disablefullbright + iwad +} + +brightmap sprite MLDRE8 +{ + map "brightmaps/strife/MLDRE8.png" + disablefullbright + iwad +} + +brightmap sprite MLDRF1 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF2 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF3 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF4 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF5 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF6 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF7 +{ + iwad + disablefullbright +} + +brightmap sprite MLDRF8 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDG1 +{ + map "brightmaps/strife/PGRDG1.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG2 +{ + map "brightmaps/strife/PGRDG2.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG3 +{ + map "brightmaps/strife/PGRDG3.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG4 +{ + map "brightmaps/strife/PGRDG4.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG5 +{ + map "brightmaps/strife/PGRDG5.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG6 +{ + map "brightmaps/strife/PGRDG6.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG7 +{ + map "brightmaps/strife/PGRDG7.png" + disablefullbright + iwad +} + +brightmap sprite PGRDG8 +{ + map "brightmaps/strife/PGRDG8.png" + disablefullbright + iwad +} + +brightmap sprite PGRDH1 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH2 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH3 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH4 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH5 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH6 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH7 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDH8 +{ + iwad + disablefullbright +} + +brightmap sprite PGRDI0 +{ + map "brightmaps/strife/PGRDI0.png" + disablefullbright + iwad +} + +brightmap sprite PGRDJ0 +{ + map "brightmaps/strife/PGRDJ0.png" + disablefullbright + iwad +} + +brightmap sprite PGRDK0 +{ + map "brightmaps/strife/PGRDK0.png" + disablefullbright + iwad +} + +brightmap sprite PGRDL0 +{ + map "brightmaps/strife/PGRDL0.png" + disablefullbright + iwad +} + +brightmap sprite PGRDM0 +{ + map "brightmaps/strife/PGRDM0.png" + disablefullbright + iwad +} + +brightmap sprite PGRDN0 +{ + map "brightmaps/strife/PGRDN0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1G1 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G2 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G3 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G4 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G5 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G6 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G7 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1G8 +{ + iwad + disablefullbright +} + +brightmap sprite ROB1j0 +{ + map "brightmaps/strife/ROB1J0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1K0 +{ + map "brightmaps/strife/ROB1K0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1L0 +{ + map "brightmaps/strife/ROB1L0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1M0 +{ + map "brightmaps/strife/ROB1M0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1N0 +{ + map "brightmaps/strife/ROB1N0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1O0 +{ + map "brightmaps/strife/ROB1O0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1P0 +{ + map "brightmaps/strife/ROB1P0.png" + disablefullbright + iwad +} + +brightmap sprite ROB1Q0 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E1 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E2 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E3 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E4 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E5 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E6 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E7 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2E8 +{ + iwad + disablefullbright +} + +brightmap sprite ROB2F1 +{ + map "brightmaps/strife/ROB2F1.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F2 +{ + map "brightmaps/strife/ROB2F2.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F3 +{ + map "brightmaps/strife/ROB2F3.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F4 +{ + map "brightmaps/strife/ROB2F4.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F5 +{ + map "brightmaps/strife/ROB2F5.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F6 +{ + map "brightmaps/strife/ROB2F6.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F7 +{ + map "brightmaps/strife/ROB2F7.png" + disablefullbright + iwad +} + +brightmap sprite ROB2F8 +{ + map "brightmaps/strife/ROB2F8.png" + disablefullbright + iwad +} + +brightmap sprite ROB2G0 +{ + map "brightmaps/strife/ROB2G0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2H0 +{ + map "brightmaps/strife/ROB2H0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2I0 +{ + map "brightmaps/strife/ROB2I0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2J0 +{ + map "brightmaps/strife/ROB2J0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2K0 +{ + map "brightmaps/strife/ROB2K0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2L0 +{ + map "brightmaps/strife/ROB2L0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2M0 +{ + map "brightmaps/strife/ROB2M0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2N0 +{ + map "brightmaps/strife/ROB2N0.png" + disablefullbright + iwad +} + +brightmap sprite ROB2O0 +{ + map "brightmaps/strife/ROB2O0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F1 +{ + map "brightmaps/strife/ROB3F1.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F2 +{ + map "brightmaps/strife/ROB3F2.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F3 +{ + map "brightmaps/strife/ROB3F3.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F4 +{ + map "brightmaps/strife/ROB3F4.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F5 +{ + map "brightmaps/strife/ROB3F5.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F6 +{ + map "brightmaps/strife/ROB3F6.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F7 +{ + map "brightmaps/strife/ROB3F7.png" + disablefullbright + iwad +} + +brightmap sprite ROB3F8 +{ + map "brightmaps/strife/ROB3F8.png" + disablefullbright + iwad +} + +brightmap sprite ROB3G1 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G2 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G3 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G4 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G5 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G6 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G7 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3G8 +{ + iwad + disablefullbright +} + +brightmap sprite ROB3H1 +{ + map "brightmaps/strife/ROB3H1.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H2 +{ + map "brightmaps/strife/ROB3H2.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H3 +{ + map "brightmaps/strife/ROB3H3.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H4 +{ + map "brightmaps/strife/ROB3H4.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H5 +{ + map "brightmaps/strife/ROB3H5.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H6 +{ + map "brightmaps/strife/ROB3H6.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H7 +{ + map "brightmaps/strife/ROB3H7.png" + disablefullbright + iwad +} + +brightmap sprite ROB3H8 +{ + map "brightmaps/strife/ROB3H8.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I1 +{ + map "brightmaps/strife/ROB3I1.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I2 +{ + map "brightmaps/strife/ROB3I2.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I3 +{ + map "brightmaps/strife/ROB3I3.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I4 +{ + map "brightmaps/strife/ROB3I4.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I5 +{ + map "brightmaps/strife/ROB3I5.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I6 +{ + map "brightmaps/strife/ROB3I6.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I7 +{ + map "brightmaps/strife/ROB3I7.png" + disablefullbright + iwad +} + +brightmap sprite ROB3I8 +{ + map "brightmaps/strife/ROB3I8.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J1 +{ + map "brightmaps/strife/ROB3J1.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J2 +{ + map "brightmaps/strife/ROB3J2.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J3 +{ + map "brightmaps/strife/ROB3J3.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J4 +{ + map "brightmaps/strife/ROB3J4.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J5 +{ + disablefullbright + iwad +} + +brightmap sprite ROB3J6 +{ + map "brightmaps/strife/ROB3J6.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J7 +{ + map "brightmaps/strife/ROB3J7.png" + disablefullbright + iwad +} + +brightmap sprite ROB3J8 +{ + map "brightmaps/strife/ROB3J8.png" + disablefullbright + iwad +} + +brightmap sprite ROB3M0 +{ + map "brightmaps/strife/ROB3M0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3N0 +{ + map "brightmaps/strife/ROB3N0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3O0 +{ + map "brightmaps/strife/ROB3O0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3P0 +{ + map "brightmaps/strife/ROB3P0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3Q0 +{ + map "brightmaps/strife/ROB3Q0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3R0 +{ + disablefullbright + iwad +} + +brightmap sprite ROB3S0 +{ + disablefullbright + iwad +} + +brightmap sprite ROB3T0 +{ + map "brightmaps/strife/ROB3T0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3U0 +{ + map "brightmaps/strife/ROB3U0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3V0 +{ + map "brightmaps/strife/ROB3V0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3W0 +{ + map "brightmaps/strife/ROB3W0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3X0 +{ + map "brightmaps/strife/ROB3X0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3Y0 +{ + map "brightmaps/strife/ROB3Y0.png" + disablefullbright + iwad +} + +brightmap sprite ROB3Z0 +{ + map "brightmaps/strife/ROB3Z0.png" + disablefullbright + iwad +} + +brightmap sprite "ROB3[0" +{ + map "brightmaps/strife/ROB3[0.png" + disablefullbright + iwad +} + +brightmap sprite "ROB3\0" +{ + map "brightmaps/strife/ROB3^0.png" + disablefullbright + iwad +} + +brightmap sprite "ROB3]0" +{ + map "brightmaps/strife/ROB3]0.png" + disablefullbright + iwad +} + +brightmap sprite RBB3A0 +{ + map "brightmaps/strife/RBB3A0.png" + disablefullbright + iwad +} + +brightmap sprite RBB3B0 +{ + map "brightmaps/strife/RBB3B0.png" + disablefullbright + iwad +} + +brightmap sprite PRGRH0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRI0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRJ0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRK0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRL0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRM0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRO0 +{ + map "brightmaps/strife/prgro0.png" + iwad + disablefullbright +} + +brightmap sprite PRGRP0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRQ0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRR0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRS0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRT0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRU0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRV0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRW0 +{ + iwad + disablefullbright +} + +brightmap sprite PRGRX0 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRC1 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRC8C2 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRC7C3 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRC6C4 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRC5 +{ + disablefullbright +} + +brightmap sprite SEWRE0 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRF0 +{ + iwad + disablefullbright +} + +brightmap sprite SEWRG0 +{ + iwad + disablefullbright +} + +brightmap sprite sewrh0 +{ + map "brightmaps/strife/SEWRH0.png" + disablefullbright + iwad +} + +brightmap sprite STLKP0 +{ + map "brightmaps/strife/STLKP0.png" + disablefullbright + iwad +} + +brightmap sprite STLKQ0 +{ + map "brightmaps/strife/STLKQ0.png" + disablefullbright + iwad +} + +brightmap sprite STLKR0 +{ + map "brightmaps/strife/STLKR0.png" + disablefullbright + iwad +} + +brightmap sprite STLKS0 +{ + map "brightmaps/strife/STLKS0.png" + disablefullbright + iwad +} + +brightmap sprite STLKT0 +{ + map "brightmaps/strife/STLKT0.png" + disablefullbright + iwad +} + +brightmap sprite STLKU0 +{ + map "brightmaps/strife/STLKU0.png" + disablefullbright + iwad +} + +brightmap sprite STLKV0 +{ + map "brightmaps/strife/STLKV0.png" + disablefullbright + iwad +} + +brightmap sprite STLKW0 +{ + map "brightmaps/strife/STLKW0.png" + disablefullbright + iwad +} + +brightmap sprite STLKX0 +{ + map "brightmaps/strife/STLKX0.png" + disablefullbright + iwad +} + +brightmap sprite STLKY0 +{ + map "brightmaps/strife/STLKY0.png" + disablefullbright + iwad +} + +brightmap sprite STLKZ0 +{ + map "brightmaps/strife/STLKZ0.png" + disablefullbright + iwad +} + +brightmap sprite "STLK[0" +{ + map "brightmaps/strife/STLK[0.png" + disablefullbright + iwad +} + diff --git a/wadsrc_lights/CMakeLists.txt b/wadsrc_lights/CMakeLists.txt new file mode 100644 index 000000000..92f89314a --- /dev/null +++ b/wadsrc_lights/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required( VERSION 2.4 ) + +add_pk3(lights.pk3 ${CMAKE_CURRENT_SOURCE_DIR}/static) diff --git a/wadsrc_lights/static/doomdefs.txt b/wadsrc_lights/static/doomdefs.txt new file mode 100644 index 000000000..3690120e3 --- /dev/null +++ b/wadsrc_lights/static/doomdefs.txt @@ -0,0 +1,1258 @@ +// ------------------------------------------------------ +// ------------------ DOOM GAME LIGHTS ------------------ +// ------------------------------------------------------ + +// ------------------ +// -- Doom Weapons -- +// ------------------ + +// Bullet puff +flickerlight BPUFF1 +{ + color 0.5 0.5 0.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight BPUFF2 +{ + color 0.5 0.5 0.0 + size 3 + secondarySize 4 + chance 0.8 +} + +object BulletPuff +{ + frame PUFFA { light BPUFF1 } + frame PUFFB { light BPUFF2 } +} + +// Rocket +pointlight ROCKET +{ + color 1.0 0.7 0.0 + size 56 +} + +flickerlight ROCKET_X1 +{ + color 1.0 0.7 0.5 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight ROCKET_X2 +{ + color 0.5 0.3 0.2 + size 80 + secondarySize 88 + chance 0.3 +} + +flickerlight ROCKET_X3 +{ + color 0.3 0.1 0.1 + size 96 + secondarySize 104 + chance 0.3 +} + +object Rocket +{ + frame MISLA { light ROCKET } + + frame MISLB { light ROCKET_X1 } + frame MISLC { light ROCKET_X2 } + frame MISLD { light ROCKET_X3 } +} + +// Plasma +pointlight PLASMABALL +{ + color 0.5 0.5 1.0 + size 56 +} + +flickerlight PLASMA_X1 +{ + color 0.5 0.5 1.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight PLASMA_X2 +{ + color 0.4 0.4 0.8 + size 80 + secondarySize 88 + chance 0.4 +} + +flickerlight PLASMA_X3 +{ + color 0.25 0.25 0.5 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight PLASMA_X4 +{ + color 0.1 0.1 0.2 + size 8 + secondarySize 16 + chance 0.4 +} + +object PlasmaBall +{ + frame PLSSA { light PLASMABALL } + frame PLSSB { light PLASMABALL } + + frame PLSEA { light PLASMA_X1 } + frame PLSEB { light PLASMA_X2 } + frame PLSEC { light PLASMA_X2 } + frame PLSED { light PLASMA_X3 } + frame PLSEE { light PLASMA_X4 } +} + +// Beta Plasma 1 +pointlight PLASMABALL1 +{ + color 0.1 1.0 0.0 + size 56 +} + +flickerlight PLASMA1_X1 +{ + color 0.2 1.0 0.2 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight PLASMA1_X2 +{ + color 0.2 0.8 0.2 + size 80 + secondarySize 88 + chance 0.4 +} + +flickerlight PLASMA1_X3 +{ + color 0.1 0.5 0.1 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight PLASMA1_X4 +{ + color 0.0 0.2 0.0 + size 8 + secondarySize 16 + chance 0.4 +} + +object PlasmaBall1 +{ + frame PLS1A { light PLASMABALL1 } + frame PLS1B { light PLASMABALL1 } + + frame PLS1C { light PLASMA1_X1 } + frame PLS1D { light PLASMA1_X2 } + frame PLS1E { light PLASMA1_X2 } + frame PLS1F { light PLASMA1_X3 } + frame PLS1G { light PLASMA1_X4 } +} + +// Beta Plasma 2 +pointlight PLASMABALL2 +{ + color 1.0 0.1 0.0 + size 56 +} + +flickerlight PLASMA1_X1 +{ + color 0.9 0.2 0.2 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight PLASMA1_X2 +{ + color 0.6 0.2 0.2 + size 80 + secondarySize 88 + chance 0.4 +} + +flickerlight PLASMA1_X3 +{ + color 0.2 0.0 0.0 + size 8 + secondarySize 16 + chance 0.4 +} + +object PlasmaBall2 +{ + frame PLS2A { light PLASMABALL2 } + frame PLS2B { light PLASMABALL2 } + + frame PLS2C { light PLASMA2_X1 } + frame PLS2D { light PLASMA2_X2 } + frame PLS2E { light PLASMA2_X3 } +} + +// BFG +pointlight BFGBALL +{ + color 0.5 1.0 0.5 + size 80 +} + +flickerlight BFGBALL_X1 +{ + color 0.5 1.0 0.5 + size 80 + secondarySize 88 + chance 0.3 +} + +flickerlight BFGBALL_X2 +{ + color 0.6 1.0 0.6 + size 104 + secondarySize 112 + chance 0.3 +} + +flickerlight BFGBALL_X3 +{ + color 0.7 1.0 0.7 + size 120 + secondarySize 128 + chance 0.3 +} + +flickerlight BFGBALL_X4 +{ + color 0.4 0.7 0.4 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight BFGBALL_X5 +{ + color 0.1 0.3 0.1 + size 48 + secondarySize 56 + chance 0.3 +} + +object BFGBall +{ + frame BFS1A { light BFGBALL } + frame BFS1B { light BFGBALL } + + frame BFE1A { light BFGBALL_X1 } + frame BFE1B { light BFGBALL_X2 } + frame BFE1C { light BFGBALL_X3 } + frame BFE1D { light BFGBALL_X1 } + frame BFE1E { light BFGBALL_X4 } + frame BFE1F { light BFGBALL_X5 } +} + + +object BFGExtra +{ + frame BFE2A { light BFGBALL } + frame BFE2B { light BFGBALL_X1 } + frame BFE2C { light BFGBALL_X4 } + frame BFE2D { light BFGBALL_X5 } +} + + + +// ---------------------- +// -- Doom Decorations -- +// ---------------------- + +// Barrel +pulselight BARREL +{ + color 0.0 0.5 0.0 + size 20 + secondarySize 21 + interval 0.5 + offset 0 36 0 + dontlightself 1 +} + +object ExplosiveBarrel +{ + frame BAR1 { light BARREL } + + frame BEXPC { light ROCKET_X1 } + frame BEXPD { light ROCKET_X2 } + frame BEXPE { light ROCKET_X3 } +} + +// Floor lamp +pointlight LAMP +{ + color 1.0 1.0 0.8 + size 56 + offset 0 44 0 +} + +object Column +{ + frame COLU { light LAMP } +} + +// Short tech lamp +pulselight SMALLLAMP +{ + color 0.8 0.8 1.0 + size 56 + secondarySize 58 + interval 0.4 + offset 0 44 0 +} + +object TechLamp2 +{ + frame TLP2 { light SMALLLAMP } +} + +// Tall tech lamp +pulselight BIGLAMP +{ + color 0.8 0.8 1.0 + size 64 + secondarySize 66 + interval 0.4 + offset 0 72 0 +} + +object TechLamp +{ + frame TLMP { light BIGLAMP } +} + +// Tall red torch +flickerlight2 BIGREDTORCH +{ + color 1.0 0.5 0.2 + size 64 + secondarySize 72 + interval 0.1 + offset 0 60 0 +} + +object RedTorch +{ + frame TRED { light BIGREDTORCH } +} + +// Tall green torch +flickerlight2 BIGGREENTORCH +{ + color 0.3 1.0 0.3 + size 64 + secondarySize 72 + interval 0.1 + offset 0 60 0 +} + +object GreenTorch +{ + frame TGRN { light BIGGREENTORCH } +} + +// Tall blue torch +flickerlight2 BIGBLUETORCH +{ + color 0.3 0.3 1.0 + size 64 + secondarySize 72 + interval 0.1 + offset 0 60 0 +} + +object BlueTorch +{ + frame TBLU { light BIGBLUETORCH } +} + +// Small red torch +flickerlight2 SMALLREDTORCH +{ + color 1.0 0.5 0.2 + size 48 + secondarySize 54 + interval 0.1 + offset 0 35 0 +} + +object ShortRedTorch +{ + frame SMRT { light SMALLREDTORCH } +} + +// Small green torch +flickerlight2 SMALLGREENTORCH +{ + color 0.3 1.0 0.3 + size 48 + secondarySize 54 + interval 0.1 + offset 0 35 0 +} + +object ShortGreenTorch +{ + frame SMGT { light SMALLGREENTORCH } +} + +// Small blue torch +flickerlight2 SMALLBLUETORCH +{ + color 0.3 0.3 1.0 + size 48 + secondarySize 54 + interval 0.1 + offset 0 35 0 +} + +object ShortBlueTorch +{ + frame SMBT { light SMALLBLUETORCH } +} + +// Burning barrel +flickerlight2 FIREBARREL +{ + color 1.0 0.9 0.4 + size 48 + secondarySize 54 + interval 0.1 + offset 0 32 0 +} + +object BurningBarrel +{ + frame FCAN { light FIREBARREL } +} + +// Skulls w/candles +flickerlight2 SKULLCANDLES +{ + color 1.0 1.0 0.3 + size 32 + secondarySize 34 + interval 0.1 + offset 0 24 0 +} + +object HeadCandles +{ + frame POL3 { light SKULLCANDLES } +} + +// Candle +pointlight CANDLE +{ + color 1.0 1.0 0.3 + size 16 + offset 0 16 0 +} + +object Candlestick +{ + frame CAND { light CANDLE } +} + +// Candelabra +pointlight CANDELABRA +{ + color 1.0 1.0 0.3 + size 48 + offset 0 52 0 +} + +object Candelabra +{ + frame CBRA { light CANDELABRA } +} + + + +// ---------------- +// -- Doom Items -- +// ---------------- + +// Soul Sphere +pulselight SOULSPHERE +{ + color 0.3 0.3 1.0 + size 40 + secondarySize 42 + interval 2.0 + offset 0 16 0 +} + +object SoulSphere +{ + frame SOUL { light SOULSPHERE } +} + +// Invulnerability Sphere +pulselight INVULN +{ + color 0.3 1.0 0.3 + size 40 + secondarySize 42 + interval 2.0 + offset 0 16 0 +} + +object InvulnerabilitySphere +{ + frame PINV { light INVULN } +} + +// Blur Sphere +pointlight BLURSPHERE1 +{ + color 1.0 0.0 0.0 + size 40 + offset 0 16 0 +} + +pointlight BLURSPHERE2 +{ + color 0.0 0.0 1.0 + size 32 + offset 0 16 0 +} + +pointlight BLURSPHERE3 +{ + color 0.0 0.0 1.0 + size 24 + offset 0 16 0 +} + +pointlight BLURSPHERE4 +{ + color 0.0 0.0 1.0 + size 16 + offset 0 16 0 +} + +pointlight BLURSPHERE5 +{ + color 0.0 0.0 1.0 + size 8 + offset 0 16 0 +} + +object BlurSphere +{ + frame PINS { light BLURSPHERE1 } + + frame PINSA { light BLURSPHERE2 } + frame PINSB { light BLURSPHERE3 } + frame PINSC { light BLURSPHERE4 } + frame PINSD { light BLURSPHERE5 } +} + +// Health Potion +pulselight HEALTHPOTION +{ + color 0.0 0.0 0.6 + size 16 + secondarySize 18 + interval 2.0 +} + +object HealthBonus +{ + frame BON1 { light HEALTHPOTION } +} + +// Armour Helmet +pulselight ARMORBONUS +{ + color 0.2 0.6 0.2 + size 16 + secondarySize 14 + interval 1.0 + dontlightself 1 +} + +object ArmorBonus +{ + frame BON2 { light ARMORBONUS } +} + +// Blue Keys +object BlueCard +{ + frame BKEY { light HEALTHPOTION } +} + +object BlueSkull +{ + frame BSKU { light HEALTHPOTION } +} + +// Yellow Keys +pulselight YELLOWKEY +{ + color 0.6 0.6 0.0 + size 16 + secondarySize 18 + interval 2.0 +} + +object YellowCard +{ + frame YKEY { light YELLOWKEY } +} + +object YellowSkull +{ + frame YSKU { light YELLOWKEY } +} + +// Red Keys +pulselight REDKEY +{ + color 0.6 0.0 0.0 + size 16 + secondarySize 18 + interval 2.0 +} + +object RedCard +{ + frame RKEY { light REDKEY } +} + +object RedSkull +{ + frame RSKU { light REDKEY } +} + +// Green armour +pointlight GREENARMOR1 +{ + color 0.0 0.6 0.0 + size 48 +} + +pointlight GREENARMOR2 +{ + color 0.0 0.6 0.0 + size 32 +} + +object GreenArmor +{ + frame ARM1A { light GREENARMOR1 } + frame ARM1B { light GREENARMOR2 } +} + +// Blue armour +pointlight BLUEARMOR1 +{ + color 0.0 0.0 0.6 + size 48 +} + +pointlight BLUEARMOR2 +{ + color 0.0 0.0 0.6 + size 32 +} + +object BlueArmor +{ + frame ARM2A { light BLUEARMOR1 } + frame ARM2B { light BLUEARMOR2 } +} + + + +// ------------------ +// -- Doom Enemies -- +// ------------------ + +// Zombies +flickerlight2 ZOMBIEATK +{ + color 1.0 0.8 0.2 + size 48 + secondarySize 56 + interval 1 + offset 0 40 0 +} + +object ZombieMan +{ + frame POSSF { light ZOMBIEATK } +} + +object ShotgunGuy +{ + frame SPOSF { light ZOMBIEATK } +} + +object ChaingunGuy +{ + frame CPOSE { light ZOMBIEATK } + frame CPOSF { light ZOMBIEATK } +} + +object DoomPlayer +{ + frame PLAYF { light ZOMBIEATK } +} + + +// Doom Imp Fireball +pointlight IMPBALL +{ + color 1.0 0.7 0.4 + size 64 +} + +// Doom imp fireball explosion +flickerlight IMPBALL_X1 +{ + color 0.7 0.4 0.25 + size 80 + secondarySize 88 + chance 0.25 +} + +flickerlight IMPBALL_X2 +{ + color 0.4 0.2 0.1 + size 96 + secondarySize 104 + chance 0.25 +} + +flickerlight IMPBALL_X3 +{ + color 0.2 0.1 0.0 + size 112 + secondarySize 120 + chance 0.25 +} + +object DoomImpBall +{ + frame BAL1A { light IMPBALL } + frame BAL1B { light IMPBALL } + + frame BAL1C { light IMPBALL_X1 } + frame BAL1D { light IMPBALL_X2 } + frame BAL1E { light IMPBALL_X3 } +} + +pointlight SPECTRE +{ + color 0.5 0.5 0.5 + size 48 + offset 0 24 0 + subtractive 1 +} + +/* +object Spectre +{ + frame SARG { light SPECTRE } +} +*/ + +// Cacodemon fireball +flickerlight CACOBALL +{ + color 1.0 0.5 0.8 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight CACOBALL_X1 +{ + color 0.9 0.4 0.7 + size 72 + secondarySize 80 + chance 0.25 +} + +flickerlight CACOBALL_X2 +{ + color 0.6 0.3 0.5 + size 88 + secondarySize 96 + chance 0.25 +} + +flickerlight CACOBALL_X3 +{ + color 0.3 0.1 0.1 + size 104 + secondarySize 112 + chance 0.25 +} + +object CacodemonBall +{ + frame BAL2A { light CACOBALL } + frame BAL2B { light CACOBALL } + + frame BAL2C { light CACOBALL_X1 } + frame BAL2D { light CACOBALL_X2 } + frame BAL2E { light CACOBALL_X3 } +} + +// Baron / Hell Knight fireball +pointlight BARONBALL +{ + color 0.0 1.0 0.0 + size 64 +} + +flickerlight BARONBALL_X1 +{ + color 0.6 0.9 0.6 + size 80 + secondarySize 88 + chance 0.25 +} + +flickerlight BARONBALL_X2 +{ + color 0.45 0.6 0.45 + size 96 + secondarySize 104 + chance 0.25 +} + +flickerlight BARONBALL_X3 +{ + color 0.2 0.3 0.2 + size 112 + secondarySize 120 + chance 0.25 +} + +object BaronBall +{ + frame BAL7A { light BARONBALL } + frame BAL7B { light BARONBALL } + + frame BAL7C { light BARONBALL_X1 } + frame BAL7D { light BARONBALL_X2 } + frame BAL7E { light BARONBALL_X3 } +} + +// Lost Soul +flickerlight LOSTSOUL +{ + color 1.0 0.6 0.3 + size 56 + secondarysize 64 + chance 0.1 +} + +flickerlight LOSTSOUL_X1 +{ + color 0.8 0.5 0.3 + size 72 + secondarySize 80 + chance 0.25 +} + +flickerlight LOSTSOUL_X2 +{ + color 0.6 0.3 0.2 + size 88 + secondarySize 96 + chance 0.25 +} + +flickerlight LOSTSOUL_X3 +{ + color 0.4 0.1 0.0 + size 104 + secondarySize 112 + chance 0.25 +} + +flickerlight LOSTSOUL_X4 +{ + color 0.2 0.0 0.0 + size 112 + secondarySize 120 + chance 0.25 +} + +object LostSoul +{ + frame SKULA { light LOSTSOUL } + frame SKULB { light LOSTSOUL } + frame SKULC { light LOSTSOUL } + frame SKULD { light LOSTSOUL } + frame SKULE { light LOSTSOUL } + frame SKULF { light LOSTSOUL } + frame SKULG { light LOSTSOUL } + + frame SKULH { light LOSTSOUL_X1 } + frame SKULI { light LOSTSOUL_X2 } + frame SKULJ { light LOSTSOUL_X3 } + frame SKULK { light LOSTSOUL_X4 } +} + +// Mancubus Fireball +object FatShot +{ + frame MANFA { light IMPBALL } + frame MANFB { light IMPBALL } + + frame MISLB { light ROCKET_X1 } + frame MISLC { light ROCKET_X2 } + frame MISLD { light ROCKET_X3 } +} + +// Arachnotron Fireball +pointlight ARACHPLAS +{ + color 0.6 1.0 0.4 + size 56 +} + +flickerlight ARACHPLAS_X1 +{ + color 0.4 0.8 0.3 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight ARACHPLAS_X2 +{ + color 0.6 0.6 0.3 + size 88 + secondarySize 96 + chance 0.3 +} + +flickerlight ARACHPLAS_X3 +{ + color 0.4 0.4 0.2 + size 48 + secondarySize 32 + chance 0.3 +} + +flickerlight ARACHPLAS_X4 +{ + color 0.2 0.2 0.1 + size 24 + secondarySize 16 + chance 0.3 +} + +object ArachnotronPlasma +{ + frame APLSA { light ARACHPLAS } + frame APLSB { light ARACHPLAS } + + frame APBXA { light ARACHPLAS_X1 } + frame APBXB { light ARACHPLAS_X2 } + frame APBXC { light ARACHPLAS_X2 } + frame APBXD { light ARACHPLAS_X3 } + frame APBXE { light ARACHPLAS_X4 } +} + +// Revenant tracer +pointlight TRACER +{ + color 1.0 0.5 0.3 + size 48 +} + +flickerlight TRACER_X1 +{ + color 1.0 0.5 0.2 + size 64 + secondarySize 72 + chance 0.25 +} + +flickerlight TRACER_X2 +{ + color 0.6 0.3 0.1 + size 80 + secondarySize 88 + chance 0.25 +} + +flickerlight TRACER_X3 +{ + color 0.3 0.1 0.0 + size 96 + secondarySize 104 + chance 0.25 +} + +object RevenantTracer +{ + frame FATBA { light TRACER } + frame FATBB { light TRACER } + + frame FBXPA { light TRACER_X1 } + frame FBXPB { light TRACER_X2 } + frame FBXPC { light TRACER_X3 } +} + +// Arch Vile Fire +flickerlight ARCHFIRE1 +{ + color 1.0 1.0 0.5 + size 24 + secondarySize 32 + chance 0.3 + offset 0 8 0 +} + +flickerlight ARCHFIRE2 +{ + color 1.0 1.0 0.5 + size 40 + secondarySize 48 + chance 0.3 + offset 0 24 0 +} + +flickerlight ARCHFIRE3 +{ + color 1.0 1.0 0.5 + size 64 + secondarySize 72 + chance 0.3 + offset 0 32 0 +} + +flickerlight ARCHFIRE4 +{ + color 0.8 0.8 0.4 + size 64 + secondarySize 72 + chance 0.3 + offset 0 40 0 +} + +flickerlight ARCHFIRE5 +{ + color 0.8 0.8 0.4 + size 64 + secondarySize 72 + chance 0.3 + offset 0 48 0 +} + +flickerlight ARCHFIRE6 +{ + color 0.6 0.6 0.3 + size 48 + secondarySize 56 + chance 0.3 + offset 0 64 0 +} + +flickerlight ARCHFIRE7 +{ + color 0.4 0.4 0.2 + size 32 + secondarySize 40 + chance 0.3 + offset 0 72 0 +} + +flickerlight ARCHFIRE8 +{ + color 0.2 0.2 0.1 + size 16 + secondarySize 24 + chance 0.3 + offset 0 80 0 +} + +object ArchvileFire +{ + frame FIREA { light ARCHFIRE1 } + frame FIREB { light ARCHFIRE2 } + frame FIREC { light ARCHFIRE3 } + frame FIRED { light ARCHFIRE4 } + frame FIREE { light ARCHFIRE5 } + frame FIREF { light ARCHFIRE6 } + frame FIREG { light ARCHFIRE7 } + frame FIREH { light ARCHFIRE8 } +} + +// Arch-vile +flickerlight ARCHATK1 +{ + color 1.0 1.0 0.4 + size 32 + secondarySize 48 + chance 0.3 + offset 0 80 0 +} + +flickerlight ARCHATK2 +{ + color 1.0 1.0 0.4 + size 56 + secondarySize 64 + chance 0.3 + offset 0 80 0 +} + +flickerlight ARCHATK3 +{ + color 1.0 1.0 0.4 + size 56 + secondarySize 64 + chance 0.3 + offset 0 64 0 +} + +flickerlight ARCHATK4 +{ + color 1.0 1.0 0.4 + size 64 + secondarySize 72 + chance 0.3 + offset 0 48 0 +} + +flickerlight ARCHATK5 +{ + color 1.0 1.0 0.4 + size 80 + secondarySize 88 + chance 0.3 + offset 0 40 0 +} + +flickerlight ARCHATK6 +{ + color 0.7 0.7 0.3 + size 96 + secondarySize 104 + chance 0.3 + offset 0 40 0 +} + +flickerlight ARCHATK7 +{ + color 0.3 0.3 0.1 + size 104 + secondarySize 112 + chance 0.3 + offset 0 40 0 +} + +pulselight ARCHRES +{ + color 0.6 0.3 0.3 + size 64 + secondarySize 70 + interval 0.5 + offset 0 36 0 +} + +object Archvile +{ + frame VILEH { light ARCHATK1 } + frame VILEI { light ARCHATK2 } + frame VILEJ { light ARCHATK3 } + frame VILEK { light ARCHATK4 } + frame VILEL { light ARCHATK4 } + frame VILEM { light ARCHATK4 } + frame VILEN { light ARCHATK5 } + frame VILEO { light ARCHATK6 } + frame VILEP { light ARCHATK7 } + + frame VILE[ { light ARCHRES } + frame VILE\ { light ARCHRES } + frame VILE] { light ARCHRES } +} + +// ------------------ +// -- Doom Effects -- +// ------------------ + +// Doom Teleport fog +flickerlight DTFOG1 +{ + color 0.4 1.0 0.4 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight DTFOG2 +{ + color 0.4 1.0 0.4 + size 40 + secondarySize 48 + chance 0.4 +} + +flickerlight DTFOG3 +{ + color 0.4 1.0 0.4 + size 24 + secondarySize 32 + chance 0.4 +} + +flickerlight DTFOG4 +{ + color 0.4 1.0 0.4 + size 10 + secondarySize 16 + chance 0.4 +} + +object TeleportFog +{ + frame TFOGA { light DTFOG1 } + frame TFOGB { light DTFOG2 } + frame TFOGC { light DTFOG2 } + frame TFOGD { light DTFOG2 } + frame TFOGE { light DTFOG3 } + frame TFOGF { light DTFOG4 } + frame TFOGI { light DTFOG4 } + frame TFOGJ { light DTFOG3 } +} diff --git a/wadsrc_lights/static/hexndefs.txt b/wadsrc_lights/static/hexndefs.txt new file mode 100644 index 000000000..6c03da6db --- /dev/null +++ b/wadsrc_lights/static/hexndefs.txt @@ -0,0 +1,1604 @@ +// ------------------------------------------------------ +// ----------------- HEXEN GAME LIGHTS ------------------ +// ------------------------------------------------------ + +// ------------------- +// -- Hexen Weapons -- +// ------------------- + +// Charged Axe Puff +flickerlight CAXEPUFF1 +{ + color 0.4 0.4 1.0 + size 40 + secondarySize 44 + chance 0.5 +} + +flickerlight CAXEPUFF2 +{ + color 0.2 0.2 0.8 + size 48 + secondarySize 52 + chance 0.5 +} + +flickerlight CAXEPUFF3 +{ + color 0.0 0.0 0.5 + size 44 + secondarySize 48 + chance 0.5 +} + +object AxePuffGlow +{ + frame FAXER { light CAXEPUFF1 } + frame FAXES { light CAXEPUFF1 } + frame FAXET { light CAXEPUFF2 } + frame FAXEU { light CAXEPUFF2 } + frame FAXEV { light CAXEPUFF3 } + frame FAXEW { light CAXEPUFF3 } + frame FAXEX { light CAXEPUFF3 } +} + +// Flying Hammer +flickerlight THROWHAMMER +{ + color 1.0 0.2 0.0 + size 48 + secondarySize 52 + chance 0.4 +} + +flickerlight THROWHAMMER_X1 +{ + color 1.0 0.7 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight THROWHAMMER_X2 +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight THROWHAMMER_X3 +{ + color 1.0 0.7 0.0 + size 72 + secondarySize 80 + chance 0.4 +} + +flickerlight THROWHAMMER_X4 +{ + color 0.8 0.8 0.0 + size 80 + secondarySize 84 + chance 0.4 +} + +flickerlight THROWHAMMER_X5 +{ + color 0.5 0.5 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight THROWHAMMER_X6 +{ + color 0.2 0.2 0.0 + size 40 + secondarySize 48 + chance 0.4 +} + +object HammerMissile +{ + frame FHFXA { light THROWHAMMER } + frame FHFXB { light THROWHAMMER } + frame FHFXC { light THROWHAMMER } + frame FHFXD { light THROWHAMMER } + frame FHFXE { light THROWHAMMER } + frame FHFXF { light THROWHAMMER } + frame FHFXG { light THROWHAMMER } + frame FHFXH { light THROWHAMMER } + + frame FHFXI { light THROWHAMMER_X1 } + frame FHFXJ { light THROWHAMMER_X2 } + frame FHFXK { light THROWHAMMER_X3 } + frame FHFXL { light THROWHAMMER_X4 } + frame FHFXM { light THROWHAMMER_X4 } + frame FHFXN { light THROWHAMMER_X4 } + frame FHFXO { light THROWHAMMER_X4 } + frame FHFXP { light THROWHAMMER_X4 } + frame FHFXQ { light THROWHAMMER_X5 } + frame FHFXR { light THROWHAMMER_X6 } +} + +// Fighter sword shot +flickerlight SWORDSHOT +{ + color 0.0 1.0 0.0 + size 48 + secondarySize 44 + chance 0.4 +} + +flickerlight SWORDSHOT_X1 +{ + color 0.0 1.0 0.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight SWORDSHOT_X2 +{ + color 0.0 1.0 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight SWORDSHOT_X3 +{ + color 0.0 0.7 0.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight SWORDSHOT_X4 +{ + color 0.0 0.4 0.0 + size 40 + secondarySize 48 + chance 0.4 +} + +flickerlight SWORDSHOT_X5 +{ + color 0.0 0.2 0.0 + size 32 + secondarySize 40 + chance 0.4 +} + +object FSwordMissile +{ + frame FSFXA { light SWORDSHOT } + frame FSFXB { light SWORDSHOT } + frame FSFXC { light SWORDSHOT } + + frame FSFXD { light SWORDSHOT_X1 } + frame FSFXE { light SWORDSHOT_X2 } + frame FSFXF { light SWORDSHOT_X2 } + frame FSFXG { light SWORDSHOT_X2 } + frame FSFXH { light SWORDSHOT_X3 } + frame FSFXI { light SWORDSHOT_X3 } + frame FSFXJ { light SWORDSHOT_X4 } + frame FSFXK { light SWORDSHOT_X5 } + frame FSFXL { light SWORDSHOT_X5 } +} + +// Cleric Serpent Staff ball +pointlight CSTAFFBALL +{ + color 0.0 1.0 0.0 + size 40 +} + +flickerlight CSTAFFBALL_X1 +{ + color 0.0 1.0 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight CSTAFFBALL_X2 +{ + color 0.0 0.7 0.0 + size 60 + secondarySize 68 + chance 0.3 +} + +flickerlight CSTAFFBALL_X3 +{ + color 0.0 0.5 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight CSTAFFBALL_X4 +{ + color 0.0 0.3 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +object CStaffMissile +{ + frame CSSFD { light CSTAFFBALL } + frame CSSFE { light CSTAFFBALL } + + frame CSSFF { light CSTAFFBALL_X1 } + frame CSSFG { light CSTAFFBALL_X2 } + frame CSSFH { light CSTAFFBALL_X3 } + frame CSSFI { light CSTAFFBALL_X4 } +} + +// Cleric fire hands +flickerlight CFLAMETRAIL +{ + color 1.0 0.8 0.0 + size 40 + secondarySize 44 + chance 0.5 +} + +flickerlight CFLAME1 +{ + color 1.0 0.8 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight CFLAME2 +{ + color 1.0 0.8 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight CFLAME3 +{ + color 0.7 0.4 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight CFLAME4 +{ + color 0.5 0.2 0.0 + size 32 + secondarySize 40 + chance 0.4 +} + +flickerlight CFLAME5 +{ + color 0.2 0.2 0.0 + size 24 + secondarySize 32 + chance 0.4 +} + +object FlamePuff2 +{ + frame CFFXB { light CFLAME1 } + frame CFFXC { light CFLAME2 } + frame CFFXD { light CFLAME2 } + frame CFFXE { light CFLAME2 } + frame CFFXF { light CFLAME2 } + frame CFFXG { light CFLAME2 } + frame CFFXH { light CFLAME2 } + frame CFFXI { light CFLAME2 } + frame CFFXJ { light CFLAME3 } + frame CFFXK { light CFLAME4 } + frame CFFXL { light CFLAME5 } +} + +object CFlameFloor +{ + frame CFFX { light CFLAMETRAIL } +} + +// Wraithverge +flickerlight GHOST +{ + color 1.0 1.0 1.0 + size 56 + secondarySize 52 + chance 0.7 + subtractive 1 +} + +object HolyMissile +{ + frame SPIRP { light GHOST } +} + +object HolySpirit +{ + frame SPIRA { light GHOST } + frame SPIRB { light GHOST } +} + +// Mage wand +pointlight MWAND_X1 +{ + color 0.3 0.3 1.0 + size 32 +} + +pointlight MWAND_X2 +{ + color 0.2 0.2 0.8 + size 40 +} + +pointlight MWAND_X3 +{ + color 0.1 0.1 0.6 + size 48 +} + +pointlight MWAND_X4 +{ + color 0.0 0.0 0.4 + size 56 +} + +object MageWandMissile +{ + frame MWNDE { light MWAND_X1 } + frame MWNDF { light MWAND_X2 } + frame MWNDG { light MWAND_X3 } + frame MWNDH { light MWAND_X4 } +} + +// Frost shards +flickerlight MFROSTSHARD +{ + color 0.3 0.3 1.0 + size 32 + secondarySize 40 + chance 0.3 +} + +flickerlight MFROSTSHARD_X1 +{ + color 0.3 0.3 1.0 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight MFROSTSHARD_X2 +{ + color 0.2 0.2 0.8 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight MFROSTSHARD_X3 +{ + color 0.1 0.1 0.5 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight MFROSTSHARD_X4 +{ + color 0.0 0.0 0.2 + size 64 + secondarySize 68 + chance 0.3 +} + +object FrostMissile +{ + frame SHRD { light MFROSTSHARD } + + frame SHEXA { light MFROSTSHARD_X1 } + frame SHEXB { light MFROSTSHARD_X2 } + frame SHEXC { light MFROSTSHARD_X3 } + frame SHEXD { light MFROSTSHARD_X4 } +} + +// Mage lightning +flickerlight MAGELIGHT +{ + color 0.4 0.4 1.0 + size 48 + secondarySize 52 + chance 0.7 +} + +object LightningCeiling +{ + frame MLFX { light MAGELIGHT } + frame MLF2 { light MAGELIGHT } +} + +object LightningFloor +{ + frame MLFX { light MAGELIGHT } + frame MLF2 { light MAGELIGHT } +} + +object LightningZap +{ + frame MLFX { light MAGELIGHT } + frame MLF2 { light MAGELIGHT } +} + +// BloodScourge +flickerlight BSBALL +{ + color 1.0 0.2 0.0 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight BSBALL_X1 +{ + color 1.0 0.4 0.0 + size 24 + secondarySize 28 + chance 0.3 +} + +flickerlight BSBALL_X2 +{ + color 0.7 0.3 0.0 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight BSBALL_X3 +{ + color 0.5 0.2 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight BSBALL_X4 +{ + color 0.3 0.1 0.0 + size 40 + secondarySize 48 + chance 0.3 +} + +object MageStaffFX2 +{ + frame MSP2A { light BSBALL } + frame MSP2B { light BSBALL } + frame MSP2C { light BSBALL } + frame MSP2D { light BSBALL } + + frame MSP2E { light BSBALL_X1 } + frame MSP2F { light BSBALL_X2 } + frame MSP2G { light BSBALL_X3 } + frame MSP2H { light BSBALL_X4 } +} + +// ------------------- +// -- Hexen Weapons -- +// ------------------- + +// Stalker slimeball +pointlight STALKERSLIME +{ + color 0.0 1.0 0.0 + size 40 +} + +flickerlight STALKERSLIME_X1 +{ + color 0.0 1.0 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight STALKERSLIME_X2 +{ + color 0.0 0.7 0.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight STALKERSLIME_X3 +{ + color 0.0 0.5 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight STALKERSLIME_X4 +{ + color 0.0 0.2 0.0 + size 68 + secondarySize 76 + chance 0.4 +} + +object SerpentFX +{ + frame SSFXA { light STALKERSLIME } + frame SSFXB { light STALKERSLIME } + + frame SSFXC { light STALKERSLIME_X1 } + frame SSFXD { light STALKERSLIME_X2 } + frame SSFXE { light STALKERSLIME_X3 } + frame SSFXF { light STALKERSLIME_X3 } + frame SSFXG { light STALKERSLIME_X4 } + frame SSFXH { light STALKERSLIME_X4 } +} + +// Centaur fireball +pointlight TAURBALL +{ + color 0.2 0.2 1.0 + size 48 +} + +flickerlight TAURBALL_X1 +{ + color 0.2 0.2 1.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight TAURBALL_X2 +{ + color 0.2 0.2 0.7 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight TAURBALL_X3 +{ + color 0.1 0.1 0.5 + size 72 + secondarySize 80 + chance 0.4 +} + +flickerlight TAURBALL_X4 +{ + color 0.0 0.0 0.3 + size 80 + secondarySize 88 + chance 0.4 +} + +object CentaurFX +{ + frame CTFXA { light TAURBALL } + + frame CTFXB { light TAURBALL_X1 } + frame CTFXC { light TAURBALL_X2 } + frame CTFXD { light TAURBALL_X3 } + frame CTFXE { light TAURBALL_X4 } + frame CTFXF { light TAURBALL_X4 } +} + +// Green Chaos Serpent fireball +flickerlight SERPENTBALL +{ + color 1.0 0.95 0.0 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight SERPENTBALL_X1 +{ + color 1.0 0.95 0.0 + size 64 + secondarySize 72 + chance 0.5 +} + +flickerlight SERPENTBALL_X2 +{ + color 0.8 0.8 0.0 + size 72 + secondarySize 80 + chance 0.5 +} + +flickerlight SERPENTBALL_X3 +{ + color 0.5 0.5 0.0 + size 88 + secondarySize 96 + chance 0.5 +} + +flickerlight SERPENTBALL_X4 +{ + color 0.2 0.2 0.0 + size 96 + secondarySize 104 + chance 0.5 +} + +object Demon1FX1 +{ + frame DMFXA { light SERPENTBALL } + frame DMFXB { light SERPENTBALL } + frame DMFXC { light SERPENTBALL } + + frame DMFXD { light SERPENTBALL_X1 } + frame DMFXE { light SERPENTBALL_X2 } + frame DMFXF { light SERPENTBALL_X3 } + frame DMFXG { light SERPENTBALL_X4 } + frame DMFXH { light SERPENTBALL_X4 } +} + +// Brown Chaos Serpent gasball +pointlight CSGASBALL +{ + color 0.0 1.0 0.0 + size 48 +} + +flickerlight CSGASBALL_X1 +{ + color 0.0 1.0 0.0 + size 64 + secondarySize 72 + chance 0.5 +} + +flickerlight CSGASBALL_X2 +{ + color 0.0 0.8 0.0 + size 72 + secondarySize 80 + chance 0.5 +} + +flickerlight CSGASBALL_X3 +{ + color 0.0 0.5 0.0 + size 88 + secondarySize 96 + chance 0.5 +} + +flickerlight CSGASBALL_X4 +{ + color 0.0 0.2 0.0 + size 96 + secondarySize 104 + chance 0.5 +} + +object Demon2FX1 +{ + frame D2FXA { light CSGASBALL } + frame D2FXB { light CSGASBALL } + frame D2FXC { light CSGASBALL } + frame D2FXD { light CSGASBALL } + frame D2FXE { light CSGASBALL } + frame D2FXF { light CSGASBALL } + + frame D2FXG { light CSGASBALL_X1 } + frame D2FXH { light CSGASBALL_X2 } + frame D2FXI { light CSGASBALL_X2 } + frame D2FXJ { light CSGASBALL_X3 } + frame D2FXK { light CSGASBALL_X4 } + frame D2FXL { light CSGASBALL_X4 } +} + +// Reaver fireball +pointlight REAVERBALL +{ + color 1.0 0.5 0.0 + size 48 +} + +flickerlight REAVERBALL_X1 +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 72 +} + +flickerlight REAVERBALL_X2 +{ + color 0.6 0.2 0.0 + size 60 + secondarySize 68 +} + +flickerlight REAVERBALL_X3 +{ + color 0.2 0.0 0.0 + size 56 + secondarySize 64 +} + +object WraithFX1 +{ + frame WRBLA { light REAVERBALL } + frame WRBLB { light REAVERBALL } + frame WRBLC { light REAVERBALL } + + frame WRBLD { light REAVERBALL_X1 } + frame WRBLE { light REAVERBALL_X2 } + frame WRBLF { light REAVERBALL_X3 } +} + +// Dragon Fireball +flickerlight DRAGONBALL +{ + color 1.0 1.0 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +object DragonFireball +{ + frame DRFXA { light DRAGONBALL } + frame DRFXB { light DRAGONBALL } + frame DRFXC { light DRAGONBALL } + frame DRFXD { light DRAGONBALL } + frame DRFXE { light DRAGONBALL } + frame DRFXF { light DRAGONBALL } + + frame DRFXG { light DRAGONBALL_X1 } + frame DRFXH { light DRAGONBALL_X2 } + frame DRFXI { light DRAGONBALL_X2 } + frame DRFXJ { light DRAGONBALL_X3 } + frame DRFXK { light DRAGONBALL_X4 } +} + +flickerlight DRAGONBALL_X1 +{ + color 0.8 0.8 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight DRAGONBALL_X2 +{ + color 0.6 0.6 0.0 + size 96 + secondarySize 104 + chance 0.3 +} + +flickerlight DRAGONBALL_X3 +{ + color 0.4 0.4 0.0 + size 88 + secondarySize 96 + chance 0.3 +} + +flickerlight DRAGONBALL_X4 +{ + color 0.2 0.2 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +object DragonExplosion +{ + frame CFCFQ { light DRAGONBALL_X1 } + frame CFCFR { light DRAGONBALL_X2 } + frame CFCFS { light DRAGONBALL_X2 } + frame CFCFT { light DRAGONBALL_X2 } + frame CFCFU { light DRAGONBALL_X3 } + frame CFCFV { light DRAGONBALL_X3 } + frame CFCFW { light DRAGONBALL_X4 } +} + +// Bishop fireball +pointlight BISHOPBALL +{ + color 0.6 1.0 0.0 + size 48 +} + +flickerlight BISHOPBALL_X1 +{ + color 0.6 1.0 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight BISHOPBALL_X2 +{ + color 0.2 0.8 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight BISHOPBALL_X3 +{ + color 0.1 0.5 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight BISHOPBALL_X4 +{ + color 0.0 0.3 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +object BishopFX +{ + frame BPFXA { light BISHOPBALL } + frame BPFXB { light BISHOPBALL } + + frame BPFXC { light BISHOPBALL_X1 } + frame BPFXD { light BISHOPBALL_X2 } + frame BPFXE { light BISHOPBALL_X2 } + frame BPFXF { light BISHOPBALL_X3 } + frame BPFXG { light BISHOPBALL_X3 } + frame BPFXH { light BISHOPBALL_X4 } +} + +// Fire gargoyle +flickerlight FGARG +{ + color 1.0 1.0 0.0 + size 40 + secondarySize 48 + chance 0.4 +} + +flickerlight FGARGATK +{ + color 1.0 1.0 0.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight FGARGBALL_X1 +{ + color 0.8 0.8 0.0 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight FGARGBALL_X2 +{ + color 0.5 0.5 0.0 + size 50 + secondarySize 54 + chance 0.4 +} + +flickerlight FGARGBALL_X3 +{ + color 0.2 0.2 0.0 + size 44 + secondarySize 48 + chance 0.4 +} + +object FireDemon +{ + frame FDMNA { light FGARG } + frame FDMNB { light FGARG } + frame FDMNC { light FGARG } + frame FDMND { light FGARG } + frame FDMNH { light FGARG } + frame FDMNI { light FGARG } + frame FDMNJ { light FGARG } + + frame FDMNK { light FGARGATK } +} + +object FireDemonMissile +{ + frame FDMBA { light FGARG } + + frame FDMBB { light FGARGBALL_X1 } + frame FDMBC { light FGARGBALL_X2 } + frame FDMBD { light FGARGBALL_X3 } +} + +// Wendigo +pointlight ICEGUYATK +{ + color 0.3 0.3 1.0 + size 64 +} + +pointlight ICEBALL +{ + color 0.3 0.3 1.0 + size 56 +} + +flickerlight ICEBALL_X1 +{ + color 0.3 0.3 1.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight ICEBALL_X2 +{ + color 0.3 0.3 0.7 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight ICEBALL_X3 +{ + color 0.2 0.2 0.4 + size 72 + secondarySize 74 + chance 0.3 +} + +flickerlight ICEBALL_X4 +{ + color 0.0 0.0 0.2 + size 74 + secondarySize 80 + chance 0.3 +} + +pointlight ICESHARD +{ + color 0.3 0.3 1.0 + size 40 +} + +object IceGuyFX +{ + frame ICPRA { light ICEBALL } + frame ICPRB { light ICEBALL } + frame ICPRC { light ICEBALL } + + frame ICPRD { light ICEBALL_X1 } + frame ICPRE { light ICEBALL_X2 } + frame ICPRF { light ICEBALL_X3 } + frame ICPRG { light ICEBALL_X4 } +} + +object IceGuyFX2 +{ + frame ICPRN { light ICESHARD } + frame ICPRO { light ICESHARD } + frame ICPRP { light ICESHARD } +} + +object IceGuy +{ + frame ICEYG { light ICEGUYATK } +} + +// Heresiarch +flickerlight HARCHATK +{ + color 1.0 0.0 1.0 + size 64 + secondarySize 72 + chance 0.4 +} + +pointlight HARCHBLUCUBE +{ + color 0.0 0.0 1.0 + size 32 +} + +pointlight HARCHGRNCUBE +{ + color 0.0 1.0 0.0 + size 32 +} + +pointlight HARCHPURCUBE +{ + color 1.0 0.0 1.0 + size 32 +} + +flickerlight HARCHBALL_X1 +{ + color 0.8 0.0 0.8 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight HARCHBALL_X2 +{ + color 0.5 0.0 0.5 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight HARCHBALL_X3 +{ + color 0.2 0.0 0.2 + size 72 + secondarySize 76 + chance 0.4 +} + +flickerlight HARCHBALL2_X1 +{ + color 0.0 0.8 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight HARCHBALL2_X2 +{ + color 0.0 0.5 0.0 + size 64 + secondarySize 72 + chance 0.4 +} + +flickerlight HARCHBALL2_X3 +{ + color 0.0 0.2 0.0 + size 72 + secondarySize 76 + chance 0.4 +} + +flickerlight HARCHHEAD +{ + color 1.0 0.5 0.0 + size 48 + secondarySize 56 + chance 0.4 +} + +object SorcFX1 +{ + frame SBS1 { light HARCHHEAD } +} + +object SorcFX2 +{ + frame SBS2 { light HARCHPURCUBE } +} + +object SorcFX3 +{ + frame SBS3A { light HARCHGRNCUBE } + frame SBS3B { light HARCHGRNCUBE } + + frame SBS3C { light HARCHBALL2_X1 } + frame SBS3D { light HARCHBALL2_X2 } + frame SBS3E { light HARCHBALL2_X3 } +} + +object SorcFX4 +{ + frame SBS4A { light HARCHPURCUBE } + frame SBS4B { light HARCHPURCUBE } + + frame SBS4C { light HARCHBALL_X1 } + frame SBS4D { light HARCHBALL_X2 } + frame SBS4E { light HARCHBALL_X3 } +} + +object SorcBall1 +{ + frame SBMP { light HARCHPURCUBE } +} + +object SorcBall2 +{ + frame SBMB { light HARCHBLUCUBE } +} + +object SorcBall3 +{ + frame SBMG { light HARCHGRNCUBE } +} + +object Heresiarch +{ + frame SORCE { light HARCHATK } + frame SORCF { light HARCHATK } +} + +// Korax +object Korax +{ + frame KORXF { light HARCHATK } + frame KORXG { light HARCHATK } +} + +// ----------------------- +// -- Hexen Decorations -- +// ----------------------- + +// Candles +flickerlight2 HCANDLES +{ + color 1.0 1.0 0.0 + size 16 + secondarySize 20 + interval 0.1 +} + +object ZCandle +{ + frame CNDL { light HCANDLES } +} + +// Twined torch +flickerlight2 TWINETORCH +{ + color 1.0 0.7 0.0 + size 46 + secondarySize 52 + interval 0.1 + offset 0 64 0 +} + +object ZTwinedTorch +{ + frame TWTRA { light TWINETORCH } + frame TWTRB { light TWINETORCH } + frame TWTRC { light TWINETORCH } + frame TWTRD { light TWINETORCH } + frame TWTRE { light TWINETORCH } + frame TWTRF { light TWINETORCH } + frame TWTRG { light TWINETORCH } + frame TWTRH { light TWINETORCH } +} + +object ZTwinedTorchUnlit +{ + frame TWTRA { light TWINETORCH } + frame TWTRB { light TWINETORCH } + frame TWTRC { light TWINETORCH } + frame TWTRD { light TWINETORCH } + frame TWTRE { light TWINETORCH } + frame TWTRF { light TWINETORCH } + frame TWTRG { light TWINETORCH } + frame TWTRH { light TWINETORCH } +} + + +// Wall torch +flickerlight2 WALLTORCH2 +{ + color 1.0 0.7 0.0 + size 24 + secondarySize 28 + interval 0.1 + offset 0 24 0 +} + +object ZWallTorch +{ + frame WLTRA { light WALLTORCH2 } + frame WLTRB { light WALLTORCH2 } + frame WLTRC { light WALLTORCH2 } + frame WLTRD { light WALLTORCH2 } + frame WLTRE { light WALLTORCH2 } + frame WLTRF { light WALLTORCH2 } + frame WLTRG { light WALLTORCH2 } + frame WLTRH { light WALLTORCH2 } +} + + +object ZWallTorchUnlit +{ + frame WLTRA { light WALLTORCH2 } + frame WLTRB { light WALLTORCH2 } + frame WLTRC { light WALLTORCH2 } + frame WLTRD { light WALLTORCH2 } + frame WLTRE { light WALLTORCH2 } + frame WLTRF { light WALLTORCH2 } + frame WLTRG { light WALLTORCH2 } + frame WLTRH { light WALLTORCH2 } +} + + +// Fire bull +flickerlight2 FIREBULL +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 70 + interval 0.1 + offset 0 40 0 +} + +flickerlight2 FIREBULL2 +{ + color 1.0 0.7 0.0 + size 48 + secondarySize 60 + interval 0.1 + offset 0 40 0 +} + +object ZFireBull +{ + frame FBULA { light FIREBULL } + frame FBULB { light FIREBULL } + frame FBULC { light FIREBULL } + frame FBULD { light FIREBULL } + frame FBULE { light FIREBULL } + frame FBULF { light FIREBULL } + frame FBULG { light FIREBULL } + frame FBULI { light FIREBULL2 } + frame FBULJ { light FIREBULL } +} + +object ZFireBullUnlit +{ + frame FBULA { light FIREBULL } + frame FBULB { light FIREBULL } + frame FBULC { light FIREBULL } + frame FBULD { light FIREBULL } + frame FBULE { light FIREBULL } + frame FBULF { light FIREBULL } + frame FBULG { light FIREBULL } + frame FBULI { light FIREBULL2 } + frame FBULJ { light FIREBULL } +} + + +// Cauldron +flickerlight2 CAULFLAME +{ + color 1.0 0.9 0.0 + size 24 + secondarySize 26 + interval 0.1 +} + +object ZCauldron +{ + frame CDRNB { light CAULFLAME } + frame CDRNC { light CAULFLAME } + frame CDRND { light CAULFLAME } + frame CDRNE { light CAULFLAME } + frame CDRNF { light CAULFLAME } + frame CDRNG { light CAULFLAME } + frame CDRNH { light CAULFLAME } +} + +object ZCauldronUnlit +{ + frame CDRNB { light CAULFLAME } + frame CDRNC { light CAULFLAME } + frame CDRND { light CAULFLAME } + frame CDRNE { light CAULFLAME } + frame CDRNF { light CAULFLAME } + frame CDRNG { light CAULFLAME } + frame CDRNH { light CAULFLAME } +} + +// Blue candle +flickerlight2 BCANDLE +{ + color 0.3 0.3 1.0 + size 14 + secondarySize 16 + interval 0.1 +} + +object ZBlueCandle +{ + frame BCAN { light BCANDLE } +} + +// Small flame +object FlameSmall +{ + frame FFSM { light HCANDLES } +} + +object FlameSmallTemp +{ + frame FFSM { light HCANDLES } +} + +// Large flame +flickerlight2 LARGEFLAME +{ + color 1.0 0.7 0.0 + size 40 + secondarySize 48 + interval 0.1 +} + +object FlameLarge +{ + frame FFLG { light LARGEFLAME } +} + +object FlameLargeTemp +{ + frame FFLG { light LARGEFLAME } +} + +// Chandelier +flickerlight2 CHANDELIER +{ + color 1.0 1.0 0.0 + size 64 + secondarySize 68 + interval 0.1 +} + +object ZChandelier +{ + frame CDLR { light CHANDELIER } +} + +// Brass torch +flickerlight2 BRASSTORCH +{ + color 1.0 0.7 0.0 + size 40 + secondarySize 48 + interval 0.1 + offset 0 32 0 +} + +object BrassTorch +{ + frame BRTR { light BRASSTORCH } +} + +// Skull flame +object FireThing +{ + frame FSKL { light BRASSTORCH } +} + +// Teleport smoke +flickerlight2 TELESMOKE +{ + color 1.0 0.0 0.0 + size 64 + secondarySize 72 + interval 0.1 + offset 0 44 0 +} + +object TeleSmoke +{ + frame TSMK { light TELESMOKE } +} + +// Fireball +pointlight HFIREBALL +{ + color 1.0 0.4 0.0 + size 48 +} + +object FireBall +{ + frame FBL1A { light HFIREBALL } + frame FBL1B { light HFIREBALL } +} + +// ----------------- +// -- Hexen Items -- +// ----------------- + +// Blue mana +pointlight MANA1 +{ + color 0.0 0.0 0.7 + size 24 + offset 0 36 0 +} + +object Mana1 +{ + frame MAN1 { light MANA1 } +} + +// Green mana +pointlight MANA2 +{ + color 0.0 0.6 0.0 + size 24 + offset 0 36 0 +} + +object Mana2 +{ + frame MAN2 { light MANA2 } +} + +// Combined mana +pointlight MANA3 +{ + color 0.7 0.0 0.0 + size 24 + offset 0 36 0 +} + +object Mana3 +{ + frame MAN3 { light MANA3 } +} + +// ZXmasTree +flickerlight2 XMASFIRE1 +{ + color 1.0 0.7 0.0 + size 16 + secondarySize 24 + interval 0.1 + offset 0 48 0 +} + + +flickerlight2 XMASFIRE2 +{ + color 1.0 0.8 0.0 + size 32 + secondarySize 48 + interval 0.1 + offset 0 48 0 +} + + +flickerlight2 XMASFIRE3 +{ + color 1.0 0.9 0.0 + size 48 + secondarySize 64 + interval 0.1 + offset 0 32 0 +} + + +flickerlight2 XMASFIRE4 +{ + color 1.0 0.8 0.0 + size 32 + secondarySize 40 + interval 0.1 + offset 0 120 0 +} + + +flickerlight2 XMASFIRE5 +{ + color 1.0 0.7 0.0 + size 12 + secondarySize 20 + interval 0.1 + offset 0 140 0 +} + + +flickerlight2 XMASFIRE6 +{ + color 1.0 0.8 0.0 + size 10 + secondarySize 14 + interval 0.1 + offset 0 148 0 +} + + +object ZXmasTree +{ + frame XMASB { light XMASFIRE1 } + frame XMASC { light XMASFIRE2 } + frame XMASD { light XMASFIRE3 } + frame XMASE { light XMASFIRE3 } + frame XMASF { light XMASFIRE4 } + frame XMASG { light XMASFIRE5 } + frame XMASH { light XMASFIRE6 } +} + + + + +// TreeDestructible +flickerlight2 TDESTRUCT1 +{ + color 1.0 0.8 0.0 + size 48 + secondarySize 56 + interval 0.1 + offset 0 32 0 +} + + +flickerlight2 TDESTRUCT2 +{ + color 1.0 0.9 0.0 + size 56 + secondarySize 72 + interval 0.1 + offset 0 32 0 +} + + +flickerlight2 TDESTRUCT3 +{ + color 1.0 0.8 0.0 + size 40 + secondarySize 48 + interval 0.1 + offset 0 20 0 +} + + +flickerlight2 TDESTRUCT4 +{ + color 1.0 0.7 0.0 + size 16 + secondarySize 24 + interval 0.1 + offset 0 12 0 +} + +flickerlight2 TDESTRUCT5 +{ + color 1.0 0.7 0.0 + size 8 + secondarySize 12 + interval 0.1 + offset 0 4 0 +} + + + + +object TreeDestructible +{ + frame TRDTH { light TDESTRUCT1 } + frame TRDTI { light TDESTRUCT2 } + frame TRDTJ { light TDESTRUCT2 } + frame TRDTK { light TDESTRUCT2 } + frame TRDTL { light TDESTRUCT2 } + frame TRDTM { light TDESTRUCT3 } + frame TRDTN { light TDESTRUCT4 } + frame TRDTO { light TDESTRUCT4 } + frame TRDTP { light TDESTRUCT5 } +} diff --git a/wadsrc_lights/static/hticdefs.txt b/wadsrc_lights/static/hticdefs.txt new file mode 100644 index 000000000..b8823db66 --- /dev/null +++ b/wadsrc_lights/static/hticdefs.txt @@ -0,0 +1,1854 @@ +// ------------------------------------------------------ +// ---------------- HERETIC GAME LIGHTS ----------------- +// ------------------------------------------------------ + +// --------------------- +// -- Heretic Weapons -- +// --------------------- + +// Wand puffs +pointlight WANDPUFF1 +{ + color 0.9 0.9 0.5 + size 32 +} + +pointlight WANDPUFF2 +{ + color 0.6 0.6 0.35 + size 24 +} + +pointlight WANDPUFF3 +{ + color 0.3 0.3 0.2 + size 16 +} + +pointlight WANDPUFF4 +{ + color 0.15 0.15 0.1 + size 8 +} + +object GoldWandPuff1 +{ + frame PUF2A { light WANDPUFF1 } + frame PUF2B { light WANDPUFF2 } + frame PUF2C { light WANDPUFF3 } + frame PUF2D { light WANDPUFF4 } +} + +object GoldWandPuff2 +{ + frame PUF2C { light WANDPUFF3 } + frame PUF2D { light WANDPUFF4 } +} + +// Tomed wand projectile +pointlight WANDBALL +{ + color 0.9 0.9 0.5 + size 24 +} + +pointlight WANDBALL_X1 +{ + color 0.72 0.72 0.4 + size 32 +} + +pointlight WANDBALL_X2 +{ + color 0.54 0.54 0.3 + size 34 +} + +pointlight WANDBALL_X3 +{ + color 0.36 0.36 0.2 + size 36 +} + +pointlight WANDBALL_X4 +{ + color 0.18 0.18 0.1 + size 38 +} + +object GoldWandFX2 +{ + frame FX01C { light WANDBALL } + frame FX01D { light WANDBALL } + + frame FX01E { light WANDBALL_X1 } + frame FX01F { light WANDBALL_X2 } + frame FX01G { light WANDBALL_X3 } + frame FX01H { light WANDBALL_X4 } +} + +// Crossbow secondary projectile +pointlight SMALLBOWBOLT +{ + color 0.5 1.0 0.5 + size 40 +} + +flickerlight SMALLBOWBOLT_X1 +{ + color 0.35 0.7 0.35 + size 48 + secondarySize 52 + chance 0.3 +} + +flickerlight SMALLBOWBOLT_X2 +{ + color 0.2 0.4 0.2 + size 40 + secondarySize 44 + chance 0.3 +} + +flickerlight SMALLBOWBOLT_X3 +{ + color 0.1 0.2 0.1 + size 32 + secondarySize 36 + chance 0.3 +} + +object CrossbowFX3 +{ + frame FX03A { light SMALLBOWBOLT } + + frame FX03C { light SMALLBOWBOLT_X1 } + frame FX03D { light SMALLBOWBOLT_X2 } + frame FX03E { light SMALLBOWBOLT_X3 } +} + +// Crossbow primary proectile +pointlight BIGBOWBOLT +{ + color 0.8 1.0 0.5 + size 64 +} + +flickerlight BIGBOWBOLT_X1 +{ + color 0.48 0.8 0.4 + size 72 + secondarySize 74 + chance 0.3 +} + +flickerlight BIGBOWBOLT_X2 +{ + color 0.44 0.6 0.3 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight BIGBOWBOLT_X3 +{ + color 0.22 0.4 0.2 + size 32 + secondarySize 40 + chance 0.3 +} + +object CrossbowFX1 +{ + frame FX03B { light BIGBOWBOLT } + + frame FX03H { light BIGBOWBOLT_X1 } + frame FX03I { light BIGBOWBOLT_X2 } + frame FX03J { light BIGBOWBOLT_X3 } +} + +// Tomed crossbow projectile +object CrossbowFX2 +{ + frame FX03B { light BIGBOWBOLT } + + frame FX03H { light BIGBOWBOLT_X1 } + frame FX03I { light BIGBOWBOLT_X2 } + frame FX03J { light BIGBOWBOLT_X3 } +} + +// Tomed crossbow trail (slows down too much :P) +pointlight BOWTRAIL1 +{ + color 0.0 1.0 0.0 + size 24 +} + +pointlight BOWTRAIL2 +{ + color 0.0 0.7 0.0 + size 16 +} + +//object CrossbowFX4 +//{ + //frame FX03F { light BOWTRAIL1 } + //frame FX03G { light BOWTRAIL2 } +//} + +// Claw puff +pointlight CLAWPUFF1 +{ + color 0.4 0.4 1.0 + size 32 +} + +pointlight CLAWPUFF2 +{ + color 0.3 0.3 0.8 + size 24 +} + +pointlight CLAWPUFF3 +{ + color 0.2 0.2 0.6 + size 16 +} + +pointlight CLAWPUFF4 +{ + color 0.1 0.1 0.4 + size 8 +} + +object BlasterPuff +{ + frame FX17A { light CLAWPUFF1 } + frame FX17B { light CLAWPUFF2 } + frame FX17C { light CLAWPUFF3 } + frame FX17D { light CLAWPUFF4 } + frame FX17F { light CLAWPUFF1 } + frame FX17G { light CLAWPUFF2 } + frame FX17H { light CLAWPUFF3 } + frame FX17I { light CLAWPUFF4 } +} + +// Tomed claw puff +pointlight BIGCLAWPUFF1 +{ + color 0.4 0.4 1.0 + size 56 +} + +pointlight BIGCLAWPUFF2 +{ + color 0.3 0.3 0.8 + size 48 +} + +pointlight BIGCLAWPUFF3 +{ + color 0.2 0.2 0.6 + size 40 +} + +pointlight BIGCLAWPUFF4 +{ + color 0.1 0.1 0.4 + size 32 +} + +pointlight BIGCLAWPUFF5 +{ + color 0.0 0.0 0.2 + size 24 +} + +object BlasterFX1 +{ + frame FX18C { light BIGCLAWPUFF1 } + frame FX18D { light BIGCLAWPUFF2 } + frame FX18E { light BIGCLAWPUFF3 } + frame FX18F { light BIGCLAWPUFF4 } + frame FX18G { light BIGCLAWPUFF5 } +} + +// Hellstaff bolt +pointlight HELLSTAFFBALL +{ + color 1.0 0.5 0.5 + size 56 +} + +flickerlight HELLSTAFFBALL_X1 +{ + color 1.0 0.7 0.7 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight HELLSTAFFBALL_X2 +{ + color 0.8 0.5 0.5 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight HELLSTAFFBALL_X3 +{ + color 0.6 0.3 0.3 + size 80 + secondarySize 88 + chance 0.3 +} + +flickerlight HELLSTAFFBALL_X4 +{ + color 0.4 0.2 0.2 + size 88 + secondarySize 96 + chance 0.3 +} + +flickerlight HELLSTAFFBALL_X5 +{ + color 0.2 0.1 0.1 + size 96 + secondarySize 104 + chance 0.3 +} + +object HornRodFX1 +{ + frame FX00A { light HELLSTAFFBALL } + frame FX00B { light HELLSTAFFBALL } + + frame FX00H { light HELLSTAFFBALL_X1 } + frame FX00I { light HELLSTAFFBALL_X2 } + frame FX00J { light HELLSTAFFBALL_X3 } + frame FX00K { light HELLSTAFFBALL_X4 } + frame FX00L { light HELLSTAFFBALL_X5 } +} + +object HornRodFX2 +{ + frame FX00C { light HELLSTAFFBALL } + frame FX00D { light HELLSTAFFBALL } + frame FX00E { light HELLSTAFFBALL } + frame FX00F { light HELLSTAFFBALL } + + frame FX00H { light HELLSTAFFBALL_X1 } + frame FX00I { light HELLSTAFFBALL_X2 } + frame FX00J { light HELLSTAFFBALL_X3 } + frame FX00K { light HELLSTAFFBALL_X4 } + frame FX00L { light HELLSTAFFBALL_X5 } +} + +// Tomed hellstaff rain +pointlight REDRAIN +{ + color 1.0 0.0 0.0 + size 32 +} + +pointlight REDRAIN_X1 +{ + color 1.0 0.4 0.4 + size 48 +} + +pointlight REDRAIN_X2 +{ + color 0.8 0.3 0.3 + size 40 +} + +pointlight REDRAIN_X3 +{ + color 0.5 0.1 0.1 + size 32 +} + +pointlight REDRAIN_X4 +{ + color 0.3 0.0 0.0 + size 24 +} + +object RainPillar +{ + frame FX22A { light REDRAIN } + frame FX22B { light REDRAIN } + + frame FX22C { light REDRAIN_X1 } + frame FX22D { light REDRAIN_X2 } + frame FX22E { light REDRAIN_X3 } + frame FX22F { light REDRAIN_X4 } +} + +// Phoenix rod shot +pointlight PHOENIXSHOT +{ + color 1.0 0.6 0.4 + size 64 +} + +flickerlight PHOENIX_X1 +{ + color 1.0 0.8 0.4 + size 104 + secondarySize 112 + chance 0.3 +} + +flickerlight PHOENIX_X2 +{ + color 1.0 0.6 0.3 + size 88 + secondarySize 96 + chance 0.3 +} + +flickerlight PHOENIX_X3 +{ + color 0.8 0.6 0.25 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight PHOENIX_X4 +{ + color 0.6 0.4 0.2 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight PHOENIX_X5 +{ + color 0.4 0.2 0.1 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight PHOENIX_X6 +{ + color 0.2 0.1 0.0 + size 24 + secondarySize 32 + chance 0.3 +} + +object PhoenixFX1 +{ + frame FX04A { light PHOENIXSHOT } + + frame FX08A { light PHOENIX_X1 } + frame FX08B { light PHOENIX_X2 } + frame FX08C { light PHOENIX_X3 } + frame FX08D { light PHOENIX_X4 } + frame FX08E { light PHOENIX_X5 } + frame FX08F { light PHOENIX_X6 } + frame FX08G { light PHOENIX_X6 } + frame FX08H { light PHOENIX_X6 } +} + +// Phoenix rod flamethrower +flickerlight PHOENIXFLAME +{ + color 0.7 0.4 0.2 + size 48 + secondarySize 56 + chance 0.5 +} + +flickerlight PHOENIXFLAME2 +{ + color 0.5 0.2 0.1 + size 24 + secondarySize 32 + chance 0.5 +} + +flickerlight PHOENIXFLAME3 +{ + color 0.3 0.1 0.0 + size 16 + secondarySize 24 + chance 0.5 +} + +object PhoenixFX2 +{ + frame FX09A { light PHOENIXFLAME } + frame FX09B { light PHOENIXFLAME } + + frame FX09C { light PHOENIXFLAME2 } + frame FX09D { light PHOENIXFLAME3 } +} + +// Mace ball explosion +flickerlight MACEBALL_X1 +{ + color 0.8 0.8 0.4 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight MACEBALL_X2 +{ + color 0.6 0.6 0.3 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight MACEBALL_X3 +{ + color 0.4 0.4 0.2 + size 32 + secondarySize 40 + chance 0.3 +} + +flickerlight MACEBALL_X4 +{ + color 0.2 0.2 0.1 + size 16 + secondarySize 24 + chance 0.3 +} + +object MaceFX1 +{ + frame FX02G { light MACEBALL_X1 } + frame FX02H { light MACEBALL_X2 } + frame FX02I { light MACEBALL_X3 } + frame FX02J { light MACEBALL_X4 } +} + +object MaceFX2 +{ + frame FX02G { light MACEBALL_X1 } + frame FX02H { light MACEBALL_X2 } + frame FX02I { light MACEBALL_X3 } + frame FX02J { light MACEBALL_X4 } +} + +object MaceFX3 +{ + frame FX02G { light MACEBALL_X1 } + frame FX02H { light MACEBALL_X2 } + frame FX02I { light MACEBALL_X3 } + frame FX02J { light MACEBALL_X4 } +} + +object MaceFX4 +{ + frame FX02G { light MACEBALL_X1 } + frame FX02H { light MACEBALL_X2 } + frame FX02I { light MACEBALL_X3 } + frame FX02J { light MACEBALL_X4 } +} + +// --------------------- +// -- Heretic Enemies -- +// --------------------- + +// Heretic imp fireball +pointlight HIMPBALL +{ + color 1.0 0.8 0.4 + size 32 +} + +flickerlight HIMPBALL_X1 +{ + color 0.8 0.5 0.33 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight HIMPBALL_X2 +{ + color 0.6 0.4 0.27 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight HIMPBALL_X3 +{ + color 0.3 0.1 0.0 + size 32 + secondarySize 40 + chance 0.3 +} + +object HereticImpBall +{ + frame FX10A { light HIMPBALL } + frame FX10B { light HIMPBALL } + frame FX10C { light HIMPBALL } + + frame FX10D { light HIMPBALL } + frame FX10E { light HIMPBALL_X1 } + frame FX10F { light HIMPBALL_X2 } + frame FX10G { light HIMPBALL_X3 } +} + +// Mummy +flickerlight MUMMYATK +{ + color 1.0 1.0 0.5 + size 48 + secondarySize 56 + chance 0.4 +} + +object MummyLeader +{ + frame MUMMY { light MUMMYATK } +} + +object MummyLeaderGhost +{ + frame MUMMY { light MUMMYATK } +} + +// Mummy fireball +flickerlight MUMMYBALL +{ + color 1.0 1.0 0.5 + size 40 + secondarySize 48 + chance 0.4 +} + +flickerlight MUMMYBALL_X1 +{ + color 0.7 0.7 0.35 + size 48 + secondarySize 56 + chance 0.4 +} + +flickerlight MUMMYBALL_X2 +{ + color 0.4 0.4 0.2 + size 56 + secondarySize 64 + chance 0.4 +} + +flickerlight MUMMYBALL_X3 +{ + color 0.2 0.2 0.1 + size 64 + secondarySize 72 + chance 0.4 +} + +object MummyFX1 +{ + frame FX15A { light MUMMYBALL } + frame FX15B { light MUMMYBALL } + frame FX15C { light MUMMYBALL } + + frame FX15D { light MUMMYBALL_X1 } + frame FX15E { light MUMMYBALL_X2 } + frame FX15F { light MUMMYBALL_X3 } +} + +// Green flying axe +pointlight GREENAXE +{ + color 0.4 1.0 0.4 + size 32 +} + +flickerlight GREENAXE_X1 +{ + color 0.3 0.7 0.3 + size 32 + secondarySize 48 + chance 0.3 +} + +flickerlight GREENAXE_X2 +{ + color 0.2 0.4 0.2 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight GREENAXE_X3 +{ + color 0.0 0.2 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +object KnightAxe +{ + frame SPAXA { light GREENAXE } + frame SPAXB { light GREENAXE } + frame SPAXC { light GREENAXE } + + frame SPAXD { light GREENAXE_X1 } + frame SPAXE { light GREENAXE_X2 } + frame SPAXF { light GREENAXE_X3 } +} + +// Red flying axe +pointlight REDAXE +{ + color 1.0 0.5 0.5 + size 32 +} + +flickerlight REDAXE_X1 +{ + color 0.7 0.3 0.3 + size 32 + secondarySize 48 + chance 0.3 +} + +flickerlight REDAXE_X2 +{ + color 0.4 0.2 0.2 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight REDAXE_X3 +{ + color 0.2 0.1 0.1 + size 56 + secondarySize 64 + chance 0.3 +} + +object RedAxe +{ + frame RAXEA { light REDAXE } + frame RAXEB { light REDAXE } + + frame RAXEC { light REDAXE_X1 } + frame RAXED { light REDAXE_X2 } + frame RAXEE { light REDAXE_X3 } +} + +// Disciple fireball +flickerlight DISCIPLEBALL +{ + color 1.0 0.5 1.0 + size 32 + secondarySize 40 + chance 0.3 +} + +flickerlight DISCIPLEBALL_X1 +{ + color 0.7 0.3 0.7 + size 16 + secondarySize 24 + chance 0.3 +} + +flickerlight DISCIPLEBALL_X2 +{ + color 0.3 0.17 0.3 + size 8 + secondarySize 16 + chance 0.3 +} + +object WizardFX1 +{ + frame FX11A { light DISCIPLEBALL } + frame FX11B { light DISCIPLEBALL } + frame FX11C { light DISCIPLEBALL } + + frame FX11D { light DISCIPLEBALL } + frame FX11E { light DISCIPLEBALL } + frame FX11F { light DISCIPLEBALL_X1 } + frame FX11G { light DISCIPLEBALL_X2 } +} + +// Iron lich death explosion +flickerlight IRONLICH1 +{ + color 1.0 0.4 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 40 0 +} + +flickerlight IRONLICH2 +{ + color 1.0 0.7 0.0 + size 80 + secondarySize 88 + chance 0.3 + offset 0 44 0 +} + +flickerlight IRONLICH3 +{ + color 0.8 0.4 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 48 0 +} + +flickerlight IRONLICH4 +{ + color 0.4 0.0 0.0 + size 48 + secondarySize 56 + chance 0.3 + offset 0 40 0 +} + +object Ironlich +{ + frame LICHD { light IRONLICH1 } + frame LICHE { light IRONLICH2 } + frame LICHF { light IRONLICH3 } + frame LICHG { light IRONLICH4 } +} + +// IronLich frost ball +pointlight FROSTBALL +{ + color 0.4 0.4 1.0 + size 48 +} + +pointlight FROSTBALL_X1 +{ + color 0.4 0.4 1.0 + size 64 +} + +pointlight FROSTBALL_X2 +{ + color 0.2 0.2 0.7 + size 56 +} + +pointlight FROSTBALL_X3 +{ + color 0.1 0.1 0.4 + size 48 +} + +pointlight FROSTBALL_X4 +{ + color 0.0 0.0 0.2 + size 40 +} + +object HeadFX1 +{ + frame FX05A { light FROSTBALL } + frame FX05B { light FROSTBALL } + frame FX05C { light FROSTBALL } + + frame FX05D { light FROSTBALL_X1 } + frame FX05E { light FROSTBALL_X2 } + frame FX05F { light FROSTBALL_X3 } + frame FX05G { light FROSTBALL_X4 } +} + +// Frost shard (spawned by frost ball) +pointlight FROSTSHARD +{ + color 0.0 0.0 0.5 + size 32 +} + +object HeadFX2 +{ + frame FX05H { light FROSTSHARD } + frame FX05I { light FROSTSHARD } + frame FX05J { light FROSTSHARD } +} + +// Ironlich fire wall +flickerlight LICHFIRE +{ + color 1.0 0.7 0.4 + size 48 + secondarySize 56 + chance 0.5 +} + +flickerlight LICHFIRE_X1 +{ + color 0.9 0.4 0.3 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight LICHFIRE_X2 +{ + color 0.7 0.1 0.2 + size 48 + secondarySize 56 + chance 0.5 +} + +flickerlight LICHFIRE_X3 +{ + color 0.4 0.1 0.1 + size 40 + secondarySize 48 + chance 0.5 +} + +flickerlight LICHFIRE_X4 +{ + color 0.2 0.0 0.0 + size 32 + secondarySize 40 + chance 0.5 +} + +object HeadFX3 +{ + frame FX06A { light LICHFIRE } + frame FX06B { light LICHFIRE } + frame FX06C { light LICHFIRE } + + frame FX06D { light LICHFIRE_X1 } + frame FX06E { light LICHFIRE_X2 } + frame FX06F { light LICHFIRE_X3 } + frame FX06G { light LICHFIRE_X4 } +} + +// Clinker death explosion +flickerlight CLINK_X1 +{ + color 1.0 0.8 0.0 + size 40 + secondarySize 48 + chance 0.5 +} + +flickerlight CLINK_X2 +{ + color 1.0 0.6 0.0 + size 64 + secondarySize 72 + chance 0.5 +} + +flickerlight CLINK_X3 +{ + color 0.6 0.3 0.0 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight CLINK_X4 +{ + color 0.3 0.0 0.0 + size 48 + secondarySize 56 + chance 0.5 +} + +object Clink +{ + frame CLNKK { light CLINK_X1 } + frame CLNKL { light CLINK_X2 } + frame CLNKM { light CLINK_X3 } + frame CLNKN { light CLINK_X4 } +} + +// Weredragon +flickerlight BEASTATK +{ + color 1.0 0.7 0.0 + size 56 + secondarySize 64 + chance 0.5 + offset 0 48 0 +} + +object Beast +{ + frame BEASI { light BEASTATK } +} + +// Weredragon fireball +flickerlight BEASTBALL +{ + color 1.0 0.5 0.3 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight BEASTBALL_X1 +{ + color 0.8 0.4 0.24 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight BEASTBALL_X2 +{ + color 0.6 0.3 0.2 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight BEASTBALL_X3 +{ + color 0.4 0.2 0.1 + size 32 + secondarySize 40 + chance 0.3 +} + +flickerlight BEASTBALL_X4 +{ + color 0.2 0.0 0.0 + size 28 + secondarySize 32 + chance 0.3 +} + +object BeastBall +{ + frame FRB1A { light BEASTBALL } + frame FRB1B { light BEASTBALL } + frame FRB1C { light BEASTBALL } + + frame FRB1D { light BEASTBALL_X1 } + frame FRB1E { light BEASTBALL_X2 } + frame FRB1F { light BEASTBALL_X3 } + frame FRB1G { light BEASTBALL_X4 } +} + +// Small ophidian shot +pointlight SNAKESHOT1 +{ + color 0.5 0.3 1.0 + size 24 +} + +flickerlight SNAKESHOT1_X1 +{ + color 0.5 0.3 1.0 + size 24 + secondarySize 26 + chance 0.3 +} + +flickerlight SNAKESHOT1_X2 +{ + color 0.4 0.2 0.7 + size 24 + secondarySize 26 + chance 0.3 +} + +flickerlight SNAKESHOT1_X3 +{ + color 0.3 0.1 0.5 + size 28 + secondarySize 30 + chance 0.3 +} + +flickerlight SNAKESHOT1_X4 +{ + color 0.3 0.0 0.3 + size 26 + secondarySize 28 + chance 0.3 +} + +object SnakeProjA +{ + frame SNFXA { light SNAKESHOT1 } + frame SNFXB { light SNAKESHOT1 } + frame SNFXC { light SNAKESHOT1 } + frame SNFXD { light SNAKESHOT1 } + + frame SNFXE { light SNAKESHOT1_X1 } + frame SNFXF { light SNAKESHOT1_X2 } + frame SNFXG { light SNAKESHOT1_X3 } + frame SNFXH { light SNAKESHOT1_X4 } +} + +// Large ophidian shot +pointlight SNAKESHOT2 +{ + color 1.0 0.6 0.4 + size 32 +} + +flickerlight SNAKESHOT2_X1 +{ + color 1.0 0.6 0.4 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight SNAKESHOT2_X2 +{ + color 0.6 0.3 0.25 + size 48 + secondarySize 52 + chance 0.3 +} + +flickerlight SNAKESHOT2_X3 +{ + color 0.3 0.1 0.1 + size 44 + secondarySize 48 + chance 0.3 +} + +object SnakeProjB +{ + frame SNFXJ { light SNAKESHOT2 } + frame SNFXK { light SNAKESHOT2 } + + frame SNFXL { light SNAKESHOT2_X1 } + frame SNFXM { light SNAKESHOT2_X2 } + frame SNFXN { light SNAKESHOT2_X3 } +} + +// Maulotaur fireball +flickerlight MAULBALL +{ + color 1.0 0.7 0.5 + size 40 + secondarySize 48 + chance 0.5 +} + +flickerlight MAULBALL_X1 +{ + color 0.8 0.6 0.4 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight MAULBALL_X2 +{ + color 0.8 0.4 0.3 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight MAULBALL_X3 +{ + color 0.6 0.3 0.2 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight MAULBALL_X4 +{ + color 0.4 0.1 0.0 + size 32 + secondarySize 40 + chance 0.3 +} + +object MinotaurFX1 +{ + frame FX12A { light MAULBALL } + frame FX12B { light MAULBALL } + + frame FX12C { light MAULBALL_X1 } + frame FX12D { light MAULBALL_X2 } + frame FX12E { light MAULBALL_X3 } + frame FX12F { light MAULBALL_X3 } + frame FX12G { light MAULBALL_X4 } + frame FX12H { light MAULBALL_X4 } +} + +// Maulotaur ground flame +pulselight MAULFLAME +{ + color 1.0 0.7 0.5 + size 1 + secondarySize 64 + interval 6.0 +} + +flickerlight MAULFLAME_X1 +{ + color 1.0 0.7 0.5 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight MAULFLAME_X2 +{ + color 1.0 0.7 0.5 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight MAULFLAME_X3 +{ + color 0.7 0.4 0.3 + size 64 + secondarySize 68 + chance 0.3 +} + +flickerlight MAULFLAME_X4 +{ + color 0.5 0.3 0.1 + size 68 + secondarySize 72 + chance 0.3 +} + +flickerlight MAULFLAME_X5 +{ + color 0.2 0.0 0.0 + size 72 + secondarySize 76 + chance 0.3 +} + +object MinotaurFX3 +{ + frame FX13B { light MAULFLAME } + frame FX13C { light MAULFLAME } + frame FX13D { light MAULFLAME } + frame FX13E { light MAULFLAME } + frame FX13F { light MAULFLAME } + frame FX13G { light MAULFLAME } + frame FX13H { light MAULFLAME } + + frame FX13I { light MAULFLAME_X1 } + frame FX13J { light MAULFLAME_X2 } + frame FX13K { light MAULFLAME_X3 } + frame FX13L { light MAULFLAME_X4 } + frame FX13M { light MAULFLAME_X5 } +} + +// D'Sparil serpent fireball +flickerlight SERPENTBALL +{ + color 1.0 0.95 0.5 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight SERPENTBALL_X1 +{ + color 1.0 0.95 0.5 + size 64 + secondarySize 72 + chance 0.5 +} + +flickerlight SERPENTBALL_X2 +{ + color 0.8 0.8 0.4 + size 72 + secondarySize 80 + chance 0.5 +} + +flickerlight SERPENTBALL_X3 +{ + color 0.5 0.5 0.25 + size 88 + secondarySize 96 + chance 0.5 +} + +flickerlight SERPENTBALL_X4 +{ + color 0.2 0.2 0.1 + size 96 + secondarySize 104 + chance 0.5 +} + +object SorcererFX1 +{ + frame FX14A { light SERPENTBALL } + frame FX14B { light SERPENTBALL } + frame FX14C { light SERPENTBALL } + + frame FX14D { light SERPENTBALL_X1 } + frame FX14E { light SERPENTBALL_X2 } + frame FX14F { light SERPENTBALL_X3 } + frame FX14G { light SERPENTBALL_X4 } + frame FX14H { light SERPENTBALL_X4 } +} + +// D'Sparil blue bolt +flickerlight DSPARILBALL +{ + color 0.5 0.5 1.0 + size 56 + secondarySize 64 + chance 0.5 +} + +flickerlight DSPARILBALL_X1 +{ + color 0.5 0.5 1.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight DSPARILBALL_X2 +{ + color 0.4 0.4 0.8 + size 80 + secondarySize 88 + chance 0.3 +} + +flickerlight DSPARILBALL_X3 +{ + color 0.3 0.3 0.6 + size 88 + secondarySize 92 + chance 0.3 +} + +flickerlight DSPARILBALL_X4 +{ + color 0.2 0.2 0.4 + size 82 + secondarySize 86 + chance 0.3 +} + +flickerlight DSPARILBALL_X5 +{ + color 0.1 0.1 0.2 + size 82 + secondarySize 86 + chance 0.3 +} + +object Sorcerer2FX1 +{ + frame FX16A { light DSPARILBALL } + frame FX16B { light DSPARILBALL } + frame FX16C { light DSPARILBALL } + + frame FX16G { light DSPARILBALL_X1 } + frame FX16H { light DSPARILBALL_X2 } + frame FX16I { light DSPARILBALL_X3 } + frame FX16J { light DSPARILBALL_X4 } + frame FX16K { light DSPARILBALL_X5 } + frame FX16L { light DSPARILBALL_X5 } +} + +// D'Sparil +flickerlight DSPARILATK +{ + color 0.3 0.3 1.0 + size 64 + secondarySize 72 + chance 0.5 +} + +object Sorcerer2 +{ + frame SOR2R { light DSPARILATK } + frame SOR2S { light DSPARILATK } + frame SOR2T { light DSPARILATK } +} + +// ------------------------- +// -- Heretic Decorations -- +// ------------------------- + +// Wall Torch +flickerlight2 WALLTORCH +{ + color 1.0 0.8 0.0 + size 32 + secondarySize 36 + interval 0.1 + offset 0 70 0 +} + +object WallTorch +{ + frame WTRH { light WALLTORCH } +} + +// Fire Brazier +flickerlight2 FIREBRAZ +{ + color 1.0 0.8 0.0 + size 68 + secondarySize 76 + interval 0.1 + offset 0 48 0 +} + +object FireBrazier +{ + frame KFR1 { light FIREBRAZ } +} + +// Serpent torch +flickerlight2 SERPTORCH +{ + color 1.0 0.8 0.0 + size 48 + secondarySize 56 + interval 0.1 + offset 0 48 0 +} + +object SerpentTorch +{ + frame SRTC { light SERPTORCH } +} + +// Chandelier +flickerlight2 CHANDELIER +{ + color 1.0 1.0 0.0 + size 64 + secondarySize 68 + interval 0.1 +} + +object Chandelier +{ + frame CHDL { light CHANDELIER } +} + +// Pod +flickerlight POD_X1 +{ + color 0.0 1.0 0.0 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight POD_X2 +{ + color 0.0 0.7 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight POD_X3 +{ + color 0.0 0.4 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight POD_X4 +{ + color 0.0 0.2 0.0 + size 80 + secondarySize 88 + chance 0.3 +} + +object Pod +{ + frame PPODC { light POD_X1 } + frame PPODD { light POD_X2 } + frame PPODE { light POD_X3 } + frame PPODF { light POD_X4 } +} + +// Big volcano fireball +flickerlight VOLCANOBALL1 +{ + color 1.0 0.7 0.5 + size 56 + secondarySize 64 + chance 0.5 +} + +object VolcanoBlast +{ + frame VFBL { light VOLCANOBALL1 } +} + +// Small volcano fireball +flickerlight VOLCANOBALL1 +{ + color 1.0 0.5 0.0 + size 40 + secondarySize 48 + chance 0.5 +} + +object VolcanoTBlast +{ + frame VTFB { light VOLCANOBALL1 } +} + +// Blue Key Statue +pointlight BLUESTATUE +{ + color 0.0 0.0 1.0 + size 32 + offset 0 64 0 +} + +object KeyGizmoBlue +{ + frame KGZ1 { light BLUESTATUE } +} + +// Yellow Key Statue +pointlight YELLOWSTATUE +{ + color 1.0 1.0 0.0 + size 32 + offset 0 64 0 +} + +object KeyGizmoYellow +{ + frame KGZ1 { light YELLOWSTATUE } +} + +// Green Key Statue +pointlight GREENSTATUE +{ + color 0.0 1.0 0.0 + size 32 + offset 0 64 0 +} + +object KeyGizmoGreen +{ + frame KGZ1 { light GREENSTATUE } +} + +// ------------------- +// -- Heretic Items -- +// ------------------- + +// Time bomb explosion +flickerlight TIMEBOMB_X1 +{ + color 1.0 0.6 0.4 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight TIMEBOMB_X1 +{ + color 0.8 0.4 0.3 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight TIMEBOMB_X1 +{ + color 0.6 0.3 0.2 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight TIMEBOMB_X1 +{ + color 0.4 0.2 0.1 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight TIMEBOMB_X1 +{ + color 0.2 0.1 0.0 + size 80 + secondarySize 88 + chance 0.3 +} + +object ActivatedTimeBomb +{ + frame XPL1A { light TIMEBOMB_X1 } + frame XPL1B { light TIMEBOMB_X2 } + frame XPL1C { light TIMEBOMB_X3 } + frame XPL1D { light TIMEBOMB_X4 } + frame XPL1E { light TIMEBOMB_X5 } + frame XPL1F { light TIMEBOMB_X5 } +} + +// Small wand ammo +pointlight SWANDAMMO +{ + color 1.0 1.0 0.0 + size 8 +} + +object GoldWandAmmo +{ + frame AMG1 { light SWANDAMMO } +} + +// Large wand ammo +pulselight LWANDAMMO +{ + color 1.0 1.0 0.0 + size 16 + secondarySize 18 + interval 2.0 +} + +object GoldWandHefty +{ + frame AMG2 { light LWANDAMMO } +} + +// Ethereal arrows +pointlight ETHARROWS +{ + color 0.0 1.0 0.0 + size 12 + offset 0 8 0 +} + +object CrossbowAmmo +{ + frame AMC1 { light ETHARROWS } +} + +// Quiver of ethereal arrows +pulselight ETHQUIVER +{ + color 0.0 1.0 0.0 + size 16 + secondarySize 18 + interval 2.0 + offset 0 16 0 +} + +object CrossbowHefty +{ + frame AMC2 { light ETHQUIVER } +} + +// Small claw ammo +pulselight SCLAWAMMO +{ + color 0.0 0.0 1.0 + size 8 + secondarySize 10 + interval 2.0 +} + +object BlasterAmmo +{ + frame AMB1 { light SCLAWAMMO } +} + +// Large claw ammo +pulselight LCLAWAMMO +{ + color 0.0 0.0 1.0 + size 16 + secondarySize 18 + interval 2.0 + offset 0 6 0 +} + +object BlasterHefty +{ + frame AMB2 { light LCLAWAMMO } +} + +// Small hellstaff ammo +pulselight SSTAFFAMMO +{ + color 1.0 0.0 0.0 + size 8 + secondarySize 10 + interval 2.0 +} + +object SkullRodAmmo +{ + frame AMS1 { light SSTAFFAMMO } +} + +// Large hellstaff ammo +pulselight LSTAFFAMMO +{ + color 1.0 0.0 0.0 + size 16 + secondarySize 18 + interval 2.0 +} + +object SkullRodHefty +{ + frame AMS2 { light LSTAFFAMMO } +} + +// Small phoenix rod ammo +pulselight SRODAMMO +{ + color 1.0 0.6 0.0 + size 8 + secondarySize 10 + interval 2.0 +} + +object PhoenixRodAmmo +{ + frame AMP1 { light SRODAMMO } +} + +// Large phoenix rod ammo +pulselight LRODAMMO +{ + color 1.0 0.6 0.0 + size 16 + secondarySize 18 + interval 2.0 +} + +object PhoenixRodHefty +{ + frame AMP2 { light LRODAMMO } +} + +// Yellow Key +pulselight HYELLOWKEY +{ + color 1.0 1.0 0.0 + size 24 + secondarySize 26 + interval 2.0 +} +object KeyYellow +{ + frame CKYY { light HYELLOWKEY } +} + +// Blue Key +pulselight HBLUEKEY +{ + color 0.0 0.0 1.0 + size 24 + secondarySize 26 + interval 2.0 +} + +object KeyBlue +{ + frame BKYY { light HBLUEKEY } +} + +// Green Key +pulselight HGREENKEY +{ + color 0.0 1.0 0.0 + size 24 + secondarySize 26 + interval 2.0 +} + +object KeyGreen +{ + frame AKYY { light HGREENKEY } +} + +// --------------------- +// -- Heretic Effects -- +// --------------------- + +// Heretic Teleport fog +pointlight HTFOG1 +{ + color 0.4 0.4 1.0 + size 64 +} + +pointlight HTFOG2 +{ + color 0.4 0.4 1.0 + size 40 +} + +pointlight HTFOG3 +{ + color 0.4 0.4 1.0 + size 16 +} + +flickerlight HTFOG4 +{ + color 0.5 0.5 1.0 + size 40 + secondarySize 48 + chance 0.4 +} + +flickerlight HTFOG5 +{ + color 0.5 0.5 1.0 + size 56 + secondarySize 64 + chance 0.4 +} + +object TeleportFog +{ + frame TELEA { light HTFOG1 } + frame TELEB { light HTFOG2 } + frame TELEC { light HTFOG3 } + frame TELED { light HTFOG4 } + frame TELEE { light HTFOG4 } + frame TELEF { light HTFOG4 } + frame TELEG { light HTFOG5 } + frame TELEH { light HTFOG5 } +} \ No newline at end of file diff --git a/wadsrc_lights/static/strfdefs.txt b/wadsrc_lights/static/strfdefs.txt new file mode 100644 index 000000000..8a2bdcc5d --- /dev/null +++ b/wadsrc_lights/static/strfdefs.txt @@ -0,0 +1,2874 @@ +// ------------------------------------------------------ +// ---------------- STRIFE GAME LIGHTS ------------------ +// ------------------------------------------------------ +// -------------------- +// -- Strife Weapons -- +// -------------------- + +// Bullet puff +flickerlight SPUFF1 +{ + color 1.0 1.0 0.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight SPUFF2 +{ + color 1.0 0.8 0.0 + size 5 + secondarySize 6 + chance 0.8 +} + +flickerlight SPUFF3 +{ + color 1.0 0.6 0.0 + size 8 + secondarySize 10 + chance 0.8 +} + +flickerlight SPUFF4 +{ + color 0.8 0.8 1.0 + size 2 + secondarySize 4 + chance 0.8 +} + +flickerlight SPUFF5 +{ + color 0.8 0.8 1.0 + size 4 + secondarySize 6 + chance 0.8 +} + +flickerlight SPUFF6 +{ + color 0.6 0.6 1.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight SPUFF7 +{ + color 0.4 0.4 0.8 + size 7 + secondarySize 9 + chance 0.8 +} + +flickerlight SPUFF8 +{ + color 1.0 1.0 0.0 + size 2 + secondarySize 4 + chance 0.8 +} + +flickerlight SPUFF9 +{ + color 1.0 0.8 0.0 + size 3 + secondarySize 4 + chance 0.8 +} + +flickerlight SPUFF10 +{ + color 1.0 0.6 0.0 + size 5 + secondarySize 6 + chance 0.8 +} + +flickerlight SPUFF11 +{ + color 1.0 0.4 0.0 + size 7 + secondarySize 8 + chance 0.8 +} + +object StrifePuff +{ + frame PUFYA { light SPUFF1 } + frame PUFYB { light SPUFF2 } + frame PUFYC { light SPUFF3 } + + frame POW3A { light SPUFF4 } + frame POW3B { light SPUFF5 } + frame POW3C { light SPUFF6 } + frame POW3D { light SPUFF7 } + frame POW3E { light SPUFF8 } + frame POW3F { light SPUFF9 } + frame POW3G { light SPUFF10 } + frame POW3H { light SPUFF11 } +} + +flickerlight SSPARK1 +{ + color 0.5 0.5 1.0 + size 4 + secondarySize 6 + chance 0.8 +} + +flickerlight SSPARK2 +{ + color 0.5 0.5 1.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight SSPARK3 +{ + color 0.4 0.4 1.0 + size 8 + secondarySize 10 + chance 0.8 +} + +flickerlight SSPARK4 +{ + color 0.3 0.3 1.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight SSPARK5 +{ + color 0.2 0.2 1.0 + size 4 + secondarySize 6 + chance 0.8 +} + +object StrifeSpark +{ + frame POW3A { light SPUFF4 } + frame POW3B { light SPUFF5 } + frame POW3C { light SPUFF6 } + frame POW3D { light SPUFF7 } + frame POW3E { light SPUFF8 } + frame POW3F { light SPUFF9 } + frame POW3G { light SPUFF10 } + frame POW3H { light SPUFF11 } + + frame POW2A { light SSPARK5 } + frame POW2B { light SSPARK5 } + frame POW2C { light SSPARK5 } + frame POW2D { light SSPARK5 } + frame POW2E { light SSPARK5 } +} + +// Arrow +flickerlight ARROWZAP1 +{ + color 0.4 0.4 1.0 + size 8 + secondarySize 16 + chance 0.4 +} + +flickerlight ARROWZAP2 +{ + color 0.45 0.45 1.0 + size 16 + secondarySize 24 + chance 0.4 +} + +flickerlight ARROWZAP3 +{ + color 0.5 0.5 1.0 + size 24 + secondarySize 30 + chance 0.4 +} + +flickerlight ARROWZAP4 +{ + color 0.6 0.6 1.0 + size 30 + secondarySize 36 + chance 0.4 +} + +flickerlight ARROWZAP5 +{ + color 0.7 0.7 1.0 + size 36 + secondarySize 40 + chance 0.4 +} + +flickerlight ARROWZAP6 +{ + color 0.8 0.8 1.0 + size 40 + secondarySize 42 + chance 0.4 +} + +object ElectricBolt +{ + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +// Missile +pointlight MISSILE +{ + color 1.0 0.7 0.0 + size 56 + offset -40 0 0 +} + +flickerlight MISSILE_X1 +{ + color 1.0 0.7 0.0 + size 56 + secondarySize 60 + chance 0.3 +} + +flickerlight MISSILE_X2 +{ + color 1.0 0.65 0.0 + size 60 + secondarySize 64 + chance 0.3 +} + +flickerlight MISSILE_X3 +{ + color 1.0 0.6 0.0 + size 64 + secondarySize 68 + chance 0.3 +} + +flickerlight MISSILE_X4 +{ + color 1.0 0.6 0.0 + size 68 + secondarySize 72 + chance 0.3 +} + +flickerlight MISSILE_X5 +{ + color 1.0 0.6 0.0 + size 72 + secondarySize 76 + chance 0.3 +} + +flickerlight MISSILE_X6 +{ + color 1.0 0.6 0.0 + size 76 + secondarySize 80 + chance 0.3 +} + +flickerlight MISSILE_X7 +{ + color 1.0 0.6 0.0 + size 80 + secondarySize 88 + chance 0.3 +} + +object MiniMissile +{ + frame MICRA { light MISSILE } + + frame SMISA { light MISSILE_X1 } + frame SMISB { light MISSILE_X2 } + frame SMISC { light MISSILE_X3 } + frame SMISD { light MISSILE_X4 } + frame SMISE { light MISSILE_X5 } + frame SMISF { light MISSILE_X6 } + frame SMISG { light MISSILE_X7 } +} + +// Flame +pointlight FLMMISSILE +{ + color 1.0 0.7 0.0 + size 56 +} + +pointlight FLMMSL_X1 +{ + color 1.0 0.7 0.0 + size 52 +} + +pointlight FLMMSL_X2 +{ + color 0.8 0.56 0.0 + size 46 +} + +pointlight FLMMSL_X3 +{ + color 0.6 0.42 0.0 + size 38 +} + +pointlight FLMMSL_X4 +{ + color 0.4 0.28 0.0 + size 24 +} + +pointlight FLMMSL_X5 +{ + color 0.2 0.14 0.0 + size 16 +} + +object FlameMissile +{ + frame FRBLA { light FLMMISSILE } + frame FRBLB { light FLMMISSILE } + frame FRBLC { light FLMMISSILE } + + frame FRBLD { light FLMMSL_X1 } + frame FRBLE { light FLMMSL_X2 } + frame FRBLF { light FLMMSL_X3 } + frame FRBLG { light FLMMSL_X4 } + frame FRBLH { light FLMMSL_X5 } +} + +// Mauler +flickerlight MPUFFG +{ + color 0.0 1.0 0.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight MPUFF1 +{ + color 1.0 1.0 1.0 + size 6 + secondarySize 8 + chance 0.8 +} + +flickerlight MPUFF2 +{ + color 1.0 1.0 1.0 + size 8 + secondarySize 10 + chance 0.8 +} + +flickerlight MPUFF3 +{ + color 1.0 1.0 1.0 + size 10 + secondarySize 12 + chance 0.8 +} + +flickerlight MPUFF4 +{ + color 1.0 1.0 1.0 + size 12 + secondarySize 14 + chance 0.8 +} + +flickerlight MPUFF5 +{ + color 1.0 1.0 1.0 + size 14 + secondarySize 16 + chance 0.8 +} + +object MaulerPuff +{ + frame MPUFA { light MPUFFG } + frame MPUFB { light MPUFFG } + frame POW1A { light MPUFF1 } + frame POW1B { light MPUFF2 } + frame POW1C { light MPUFF3 } + frame POW1D { light MPUFF4 } + frame POW1E { light MPUFF5 } +} + +pointlight MTORPEDO +{ + color 0.0 1.0 0.0 + size 80 +} + +flickerlight MTORP_X1 +{ + color 0.5 1.0 0.5 + size 80 + secondarySize 84 + chance 0.3 +} + +flickerlight MTORP_X2 +{ + color 0.4 1.0 0.4 + size 84 + secondarySize 88 + chance 0.3 +} + +flickerlight MTORP_X3 +{ + color 0.2 1.0 0.2 + size 88 + secondarySize 92 + chance 0.3 +} + +flickerlight MTORP_X4 +{ + color 0.125 0.5 0.125 + size 92 + secondarySize 96 + chance 0.3 +} + +flickerlight MTORP_X5 +{ + color 0.0 0.25 0.0 + size 96 + secondarySize 100 + chance 0.3 +} + +object MaulerTorpedo +{ + frame TORP { light MTORPEDO } + + frame THITA { light MTORP_X1 } + frame THITB { light MTORP_X2 } + frame THITC { light MTORP_X3 } + frame THITD { light MTORP_X4 } + frame THITE { light MTORP_X5 } +} + +flickerlight MWAVE_X1 +{ + color 0.0 1.0 0.0 + size 112 + secondarySize 128 + chance 0.3 +} + +flickerlight MWAVE_X2 +{ + color 0.0 0.75 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight MWAVE_X3 +{ + color 0.0 0.5 0.0 + size 24 + secondarySize 32 + chance 0.3 +} + +object MaulerTorpedoWave +{ + frame TWAVA { light MWAVE_X1 } + frame TWAVB { light MWAVE_X2 } + frame TWAVC { light MWAVE_X3 } +} + +// High Explosive Grenade +flickerlight HEGRENADE_X1 +{ + color 1.0 0.30 0.10 + size 80 + secondarySize 84 + chance 0.3 +} + +flickerlight HEGRENADE_X2 +{ + color 1.0 0.28 0.08 + size 72 + secondarySize 76 + chance 0.3 + offset 0 28 0 +} + +flickerlight HEGRENADE_X3 +{ + color 1.0 0.26 0.10 + size 57 + secondarySize 62 + chance 0.3 + offset 0 40 0 +} + +flickerlight HEGRENADE_X4 +{ + color 1.0 0.24 0.08 + size 28 + secondarySize 32 + chance 0.3 + offset 0 64 0 +} + +object HEGrenade +{ + frame BNG4A { light POWCRYS_X1 } + frame BNG4B { light POWCRYS_X2 } + frame BNG4C { light POWCRYS_X3 } + frame BNG4D { light POWCRYS_X4 } + frame BNG4E { light POWCRYS_X5 } + frame BNG4F { light POWCRYS_X6 } + frame BNG4G { light POWCRYS_X7 } + frame BNG4H { light POWCRYS_X8 } + frame BNG4I { light POWCRYS_X9 } + frame BNG4J { light POWCRYS_X10 } + + frame BNG4K { light HEGRENADE_X1 } + frame BNG4L { light HEGRENADE_X2 } + frame BNG4M { light HEGRENADE_X3 } + frame BNG4N { light HEGRENADE_X4 } +} + +// Phosphorous Fire Grenade +flickerlight PHFIRE_FX1 +{ + color 1.0 0.75 0.0 + size 28 + secondarySize 32 + chance 0.3 +} + +flickerlight PHFIRE_FX2 +{ + color 1.0 0.7 0.0 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight PHFIRE_FX3 +{ + color 1.0 0.65 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight PHFIRE_FX4 +{ + color 1.0 0.55 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight PHFIRE_FX5 +{ + color 1.0 0.5 0.0 + size 66 + secondarySize 72 + chance 0.3 +} + +flickerlight PHFIRE_FX6 +{ + color 1.0 0.55 0.0 + size 66 + secondarySize 72 + chance 0.3 +} + +flickerlight PHFIRE_FX7 +{ + color 1.0 0.6 0.0 + size 66 + secondarySize 72 + chance 0.3 +} + +flickerlight PHFIRE_FX8 +{ + color 1.0 0.5 0.0 + size 60 + secondarySize 68 + chance 0.3 +} + +flickerlight PHFIRE_FX9 +{ + color 1.0 0.4 0.0 + size 48 + secondarySize 52 + chance 0.3 +} + +flickerlight PHFIRE_FX10 +{ + color 1.0 0.45 0.0 + size 44 + secondarySize 48 + chance 0.3 +} + +flickerlight PHFIRE_FX11 +{ + color 1.0 0.3 0.0 + size 36 + secondarySize 40 + chance 0.3 +} + +object PhosphorousFire +{ + frame FLBEA { light PHFIRE_FX1 } + frame FLBEB { light PHFIRE_FX2 } + frame FLBEC { light PHFIRE_FX3 } + frame FLBED { light PHFIRE_FX4 } + frame FLBEE { light PHFIRE_FX5 } + frame FLBEF { light PHFIRE_FX6 } + frame FLBEG { light PHFIRE_FX7 } + + frame FLBEH { light PHFIRE_FX8 } + frame FLBEI { light PHFIRE_FX9 } + frame FLBEJ { light PHFIRE_FX10 } + frame FLBEK { light PHFIRE_FX11 } +} + +// ------------------ +// -- Strife Items -- +// ------------------ + +// Degnin Ore +flickerlight DEGORE_X1 +{ + color 1.0 0.6 0.0 + size 32 + secondarySize 40 + chance 0.3 +} + +flickerlight DEGORE_X2 +{ + color 1.0 0.8 0.0 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight DEGORE_X3 +{ + color 1.0 0.8 0.0 + size 44 + secondarySize 52 + chance 0.3 +} + +flickerlight DEGORE_X4 +{ + color 1.0 0.75 0.0 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight DEGORE_X5 +{ + color 1.0 0.7 0.0 + size 52 + secondarySize 60 + chance 0.3 +} + +flickerlight DEGORE_X6 +{ + color 1.0 0.5 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight DEGORE_X7 +{ + color 0.5 0.125 0.0 + size 60 + secondarySize 68 + chance 0.3 +} + +flickerlight DEGORE_X8 +{ + color 0.25 0.05 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +object DegninOre +{ + frame BNG3A { light DEGORE_X1 } + frame BNG3B { light DEGORE_X2 } + frame BNG3C { light DEGORE_X3 } + frame BNG3D { light DEGORE_X4 } + frame BNG3E { light DEGORE_X5 } + frame BNG3F { light DEGORE_X6 } + frame BNG3G { light DEGORE_X7 } + frame BNG3H { light DEGORE_X8 } +} + +// Power Coupling +pointlight POWCOUP1 +{ + color 0.5 0.5 1.0 + size 24 +} + +pointlight POWCOUP2 +{ + color 0.7 0.7 1.0 + size 32 +} + +object PowerCoupling +{ + frame COUPA { light POWCOUP1 } + frame COUPB { light POWCOUP2 } +} + +// Energy Ammo +pointlight ENERGY1 +{ + color 0.4 1.0 0.4 + size 16 +} + +pointlight ENERGY2 +{ + color 0.4 1.0 0.4 + size 32 +} + +object EnergyPod +{ + frame BRY1B { light ENERGY1 } +} + +object EnergyPack +{ + frame CPACB { light ENERGY2 } +} + +// ----------------------- +// -- Strife Characters -- +// ----------------------- + +// Humanoids +flickerlight2 HUMNDATK +{ + color 1.0 0.8 0.2 + size 48 + secondarySize 56 + interval 1 + offset 0 40 0 +} + +object Acolyte +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteTan +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteRed +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteRust +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteGray +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteDGreen +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteGold +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteLGreen +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteBlue +{ + frame AGRDF { light HUMNDATK } +} + +object AcolyteShadow +{ + frame AGRDF { light HUMNDATK } +} + +object Rebel +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel1 +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel2 +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel3 +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel4 +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel5 +{ + frame HMN1F { light HUMNDATK } +} + +object Rebel6 +{ + frame HMN1F { light HUMNDATK } +} + +object Macil1 +{ + frame LEADF { light HUMNDATK } +} + +object Macil2 +{ + frame LEADF { light HUMNDATK } +} + +object StrifePlayer +{ + //frame PLAYF { light HUMNDATK } + + frame BURNA { light PHFIRE_FX1 } + frame BURNB { light PHFIRE_FX2 } + frame BURNC { light PHFIRE_FX3 } + frame BURND { light PHFIRE_FX4 } + frame BURNE { light PHFIRE_FX5 } + frame BURNF { light PHFIRE_FX6 } + frame BURNG { light PHFIRE_FX7 } + frame BURNH { light PHFIRE_FX6 } + frame BURNI { light PHFIRE_FX5 } + frame BURNJ { light PHFIRE_FX4 } + frame BURNK { light PHFIRE_FX3 } + frame BURNL { light PHFIRE_FX2 } + frame BURNM { light PHFIRE_FX1 } + frame BURNN { light PHFIRE_FX2 } + frame BURNO { light PHFIRE_FX3 } + frame BURNP { light PHFIRE_FX4 } + frame BURNQ { light PHFIRE_FX5 } + + frame BURNR { light PHFIRE_FX8 } + frame BURNS { light PHFIRE_FX9 } + frame BURNT { light PHFIRE_FX10 } + frame BURNU { light PHFIRE_FX11 } +} + +// Turret +flickerlight2 CTURRETATK1 +{ + color 1.0 0.8 0.2 + size 40 + secondarySize 48 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETATK2 +{ + color 1.0 0.8 0.2 + size 48 + secondarySize 56 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETDTH1 +{ + color 1.0 1.0 1.0 + size 32 + secondarySize 36 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETDTH2 +{ + color 0.9 0.9 0.9 + size 36 + secondarySize 40 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETDTH3 +{ + color 0.7 0.7 0.7 + size 42 + secondarySize 46 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETDTH4 +{ + color 0.5 0.5 0.5 + size 48 + secondarySize 52 + interval 1 + offset 0 0 0 +} + +flickerlight2 CTURRETDTH5 +{ + color 0.3 0.3 0.3 + size 52 + secondarySize 56 + interval 1 + offset 0 0 0 +} + +object CeilingTurret +{ + frame TURTB { light CTURRETATK1 } + frame TURTD { light CTURRETATK2 } + + frame BALLA { light CTURRETDTH1 } + frame BALLB { light CTURRETDTH2 } + frame BALLC { light CTURRETDTH3 } + frame BALLD { light CTURRETDTH4 } + frame BALLE { light CTURRETDTH5 } +} + +// Stalker +flickerlight2 STLKATK +{ + color 1.0 0.8 0.2 + size 48 + secondarySize 56 + interval 1 + offset 0 10 0 +} + +flickerlight STLKDTH1 +{ + color 0.2 1.0 0.2 + size 32 + secondarySize 36 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH2 +{ + color 0.3 1.0 0.3 + size 36 + secondarySize 40 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH3 +{ + color 0.2 1.0 0.2 + size 40 + secondarySize 48 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH4 +{ + color 0.35 1.0 0.35 + size 44 + secondarySize 52 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH5 +{ + color 0.5 1.0 0.2 + size 40 + secondarySize 44 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH6 +{ + color 1.0 0.2 0.0 + size 32 + secondarySize 40 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH7 +{ + color 0.7 0.3 0.0 + size 40 + secondarySize 48 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH8 +{ + color 0.5 0.15 0.0 + size 36 + secondarySize 44 + chance 0.3 + offset 0 15 0 +} + +flickerlight STLKDTH9 +{ + color 0.35 0.05 0.0 + size 32 + secondarySize 36 + chance 0.3 + offset 0 15 0 +} + +object Stalker +{ + frame STLKM { light STLKATK } // Not used in Strife + + frame STLKQ { light STLKDTH1 } + frame STLKR { light STLKDTH1 } + frame STLKS { light STLKDTH1 } + frame STLKT { light STLKDTH2 } + frame STLKU { light STLKDTH3 } + frame STLKV { light STLKDTH4 } + frame STLKW { light STLKDTH5 } + frame STLKX { light STLKDTH6 } + frame STLKY { light STLKDTH7 } + frame STLKZ { light STLKDTH8 } + frame STLK[ { light STLKDTH9 } +} + +// Sentinel +flickerlight SNTNLDTH1 +{ + color 1.0 0.4 0.0 + size 24 + secondarySize 36 + chance 0.3 + offset 0 12 0 +} + +flickerlight SNTNLDTH2 +{ + color 1.0 0.6 0.0 + size 48 + secondarySize 56 + chance 0.3 + offset 0 12 0 +} + +object Sentinel +{ + frame SEWRG { light SNTNLDTH1 } + frame SEWRH { light SNTNLDTH2 } +} + +pointlight SNTNL_FX1 +{ + color 1.0 0.0 0.0 + size 16 +} + +pointlight SNTNL_FX2 +{ + color 0.5 0.0 0.0 + size 16 +} + +pointlight SNTNL_FX3 +{ + color 1.0 0.0 0.0 + size 18 +} + +pointlight SNTNL_FX4 +{ + color 0.8 0.0 0.0 + size 20 +} + +pointlight SNTNL_FX5 +{ + color 0.6 0.0 0.0 + size 22 +} + +pointlight SNTNL_FX6 +{ + color 0.4 0.0 0.0 + size 24 +} + +pointlight SNTNL_FX7 +{ + color 0.2 0.0 0.0 + size 28 +} + +object SentinelFX1 +{ + frame SHT1A { light SNTNL_FX1 } + frame SHT1B { light SNTNL_FX2 } + + frame POW1F { light SNTNL_FX3 } + frame POW1G { light SNTNL_FX4 } + frame POW1H { light SNTNL_FX5 } + frame POW1I { light SNTNL_FX6 } + frame POW1J { light SNTNL_FX7 } +} + +object SentinelFX2 +{ + frame SHT1A { light SNTNL_FX1 } + frame SHT1B { light SNTNL_FX2 } + + frame POW1F { light SNTNL_FX3 } + frame POW1G { light SNTNL_FX4 } + frame POW1H { light SNTNL_FX5 } + frame POW1I { light SNTNL_FX6 } + frame POW1J { light SNTNL_FX7 } +} + +// Crusader +flickerlight CRSDRDTH1 +{ + color 1.0 0.5 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 80 0 +} + +flickerlight CRSDRDTH2 +{ + color 1.0 0.8 0.0 + size 68 + secondarySize 74 + chance 0.3 + offset 0 40 0 +} + +flickerlight CRSDRDTH3 +{ + color 1.0 0.8 0.0 + size 72 + secondarySize 76 + chance 0.3 + offset 0 40 0 +} + +flickerlight CRSDRDTH4 +{ + color 1.0 0.9 0.0 + size 76 + secondarySize 80 + chance 0.3 + offset 0 40 0 +} + +flickerlight CRSDRDTH5 +{ + color 1.0 0.6 0.0 + size 80 + secondarySize 84 + chance 0.3 + offset 0 40 0 +} + +object Crusader +{ + frame ROB2H { light CRSDRDTH1 } + frame ROB2I { light CRSDRDTH2 } + frame ROB2J { light CRSDRDTH3 } + frame ROB2K { light CRSDRDTH4 } + frame ROB2L { light CRSDRDTH5 } + frame ROB2M { light CRSDRDTH4 } + frame ROB2N { light CRSDRDTH3 } + frame ROB2O { light CRSDRDTH2 } +} + +object FastFlameMissile +{ + frame FRBLA { light FLMMISSILE } + frame FRBLB { light FLMMISSILE } + frame FRBLC { light FLMMISSILE } + + frame FRBLD { light FLMMSL_X1 } + frame FRBLE { light FLMMSL_X2 } + frame FRBLF { light FLMMSL_X3 } + frame FRBLG { light FLMMSL_X4 } + frame FRBLH { light FLMMSL_X5 } +} + +object CrusaderMissile +{ + frame MICRA { light MISSILE } + + frame SMISA { light MISSILE_X1 } + frame SMISB { light MISSILE_X2 } + frame SMISC { light MISSILE_X3 } + frame SMISD { light MISSILE_X4 } + frame SMISE { light MISSILE_X5 } + frame SMISF { light MISSILE_X6 } + frame SMISG { light MISSILE_X7 } +} + +// Reaver +flickerlight REAV_X1 +{ + color 1.0 0.3 0.0 + size 16 + secondarySize 20 + chance 0.3 + offset 0 16 16 +} + +flickerlight REAV_X2 +{ + color 1.0 0.2 0.0 + size 32 + secondarySize 40 + chance 0.3 + offset 0 32 -16 +} + +flickerlight REAV_X3 +{ + color 1.0 0.6 0.0 + size 40 + secondarySize 44 + chance 0.3 + offset 0 12 16 +} + +flickerlight REAV_X4 +{ + color 1.0 0.5 0.0 + size 20 + secondarySize 24 + chance 0.3 + offset 0 10 0 +} + +flickerlight REAV_X5 +{ + color 1.0 0.8 0.0 + size 28 + secondarySize 32 + chance 0.3 + offset 0 18 0 +} + +flickerlight REAV_X6 +{ + color 1.0 0.7 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 20 0 +} + +flickerlight REAV_X7 +{ + color 0.5 0.05 0.0 + size 52 + secondarySize 56 + chance 0.3 + offset 0 20 0 +} + +object Reaver +{ + frame ROB1F { light HUMNDATK } + + frame ROB1K { light REAV_X1 } + frame ROB1L { light REAV_X2 } + frame ROB1M { light REAV_X3 } + frame ROB1N { light REAV_X4 } + frame ROB1O { light REAV_X5 } + frame ROB1P { light REAV_X6 } + frame ROB1Q { light REAV_X7 } +} + +// Templar +flickerlight2 TEMPATK +{ + color 0.2 1.0 0.2 + size 48 + secondarySize 56 + interval 1 + offset 20 40 0 +} + +flickerlight TEMP_X1 +{ + color 1.0 0.8 0.2 + size 8 + secondarySize 12 + chance 0.3 + offset 0 20 32 +} + +flickerlight TEMP_X2 +{ + color 1.0 0.5 0.0 + size 32 + secondarySize 36 + chance 0.3 + offset 0 20 24 +} + +flickerlight TEMP_X3 +{ + color 1.0 0.75 0.1 + size 24 + secondarySize 28 + chance 0.3 + offset 0 20 24 +} + +flickerlight TEMP_X4 +{ + color 1.0 0.65 0.1 + size 28 + secondarySize 32 + chance 0.3 + offset 0 20 16 +} + +flickerlight TEMP_X5 +{ + color 1.0 0.6 0.0 + size 30 + secondarySize 34 + chance 0.3 + offset 0 20 8 +} + +flickerlight TEMP_X6 +{ + color 1.0 0.5 0.0 + size 32 + secondarySize 36 + chance 0.3 + offset 0 20 0 +} + +object Templar +{ + frame PGRDG { light TEMPATK } + + frame PGRDI { light TEMP_X1 } + frame PGRDJ { light TEMP_X2 } + frame PGRDK { light TEMP_X3 } + frame PGRDL { light TEMP_X4 } + frame PGRDM { light TEMP_X5 } + frame PGRDN { light TEMP_X6 } +} + +// Inquisitor +flickerlight2 INQATK1 +{ + color 1.0 0.6 0.0 + size 88 + secondarySize 96 + interval 1 + offset 20 72 -40 +} + +flickerlight2 INQATK2 +{ + color 1.0 0.6 0.0 + size 88 + secondarySize 96 + interval 1 + offset 20 96 0 +} + +flickerlight2 INQFLY1 +{ + color 0.5 0.5 1.0 + size 80 + secondarySize 84 + interval 1 + offset -40 36 0 +} + +flickerlight2 INQFLY2 +{ + color 0.33 0.33 1.0 + size 64 + secondarySize 72 + interval 1 + offset -40 36 0 +} + +flickerlight INQDTH1 +{ + color 1.0 0.4 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 72 0 +} + +flickerlight INQDTH2 +{ + color 1.0 0.7 0.0 + size 84 + secondarySize 96 + chance 0.3 + offset 0 64 0 +} + +flickerlight INQDTH3 +{ + color 1.0 0.6 0.0 + size 92 + secondarySize 100 + chance 0.3 + offset 0 56 0 +} + +flickerlight INQDTH4 +{ + color 0.7 0.07 0.0 + size 72 + secondarySize 80 + chance 0.3 + offset 0 40 0 +} + +flickerlight INQDTH5 +{ + color 0.3 0.0 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 40 0 +} + +flickerlight INQDTH6 +{ + color 0.5 0.3 0.0 + size 32 + secondarySize 40 + chance 0.3 + offset 0 32 0 +} + +flickerlight INQDTH7 +{ + color 1.0 0.6 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 32 0 +} + +flickerlight INQDTH8 +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 32 0 +} + +flickerlight INQDTH9 +{ + color 1.0 0.7 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 56 0 +} + +flickerlight INQDTH10 +{ + color 1.0 0.6 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 56 0 +} + +flickerlight INQDTH11 +{ + color 1.0 0.5 0.0 + size 100 + secondarySize 128 + chance 0.3 + offset 0 32 0 +} + +flickerlight INQDTH12 +{ + color 1.0 0.4 0.0 + size 80 + secondarySize 96 + chance 0.3 + offset 0 32 0 +} + +flickerlight INQDTH13 +{ + color 1.0 0.3 0.0 + size 60 + secondarySize 72 + chance 0.3 + offset 0 24 0 +} + +flickerlight INQDTH14 +{ + color 0.5 0.15 0.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 18 0 +} + +object Inquisitor +{ + frame ROB3F { light INQATK1 } + frame ROB3J { light INQATK2 } + + frame ROB3H { light INQFLY1 } + frame ROB3I { light INQFLY2 } + + frame ROB3M { light INQDTH1 } + frame ROB3N { light INQDTH2 } + frame ROB3O { light INQDTH3 } + frame ROB3P { light INQDTH4 } + frame ROB3Q { light INQDTH5 } + frame ROB3R { light INQDTH6 } + frame ROB3S { light INQDTH6 } + frame ROB3T { light INQDTH6 } + frame ROB3U { light INQDTH7 } + frame ROB3V { light INQDTH8 } + frame ROB3W { light INQDTH6 } + frame ROB3X { light INQDTH6 } + frame ROB3Y { light INQDTH9 } + frame ROB3Z { light INQDTH10 } + frame ROB3[ { light INQDTH11 } + frame ROB3\ { light INQDTH12 } + frame RBB3] { light INQDTH13 } + frame RBB3A { light INQDTH12 } + frame RBB3B { light INQDTH13 } + frame RBB3C { light INQDTH14 } +} + +flickerlight INQSHOT_X1 +{ + color 1.0 0.8 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight INQSHOT_X2 +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight INQSHOT_X3 +{ + color 0.8 0.45 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight INQSHOT_X4 +{ + color 0.5 0.3 0.0 + size 80 + secondarySize 84 + chance 0.3 +} + +flickerlight INQSHOT_X5 +{ + color 1.0 0.6 0.0 + size 56 + secondarySize 60 + chance 0.3 +} + +flickerlight INQSHOT_X6 +{ + color 1.0 0.7 0.0 + size 60 + secondarySize 64 + chance 0.3 +} + +flickerlight INQSHOT_X7 +{ + color 1.0 0.7 0.0 + size 64 + secondarySize 68 + chance 0.3 +} + +flickerlight INQSHOT_X8 +{ + color 1.0 0.6 0.0 + size 40 + secondarySize 48 + chance 0.3 +} + +flickerlight INQSHOT_X9 +{ + color 1.0 0.4 0.0 + size 24 + secondarySize 32 + chance 0.3 +} + +object InquisitorShot +{ + frame BNG2A { light INQSHOT_X1 } + frame BNG2B { light INQSHOT_X2 } + frame BNG2C { light INQSHOT_X3 } + frame BNG2D { light INQSHOT_X4 } + frame BNG2E { light INQSHOT_X5 } + frame BNG2F { light INQSHOT_X6 } + frame BNG2G { light INQSHOT_X7 } + frame BNG2H { light INQSHOT_X8 } + frame BNG2I { light INQSHOT_X9 } +} + +// Programmer +flickerlight PROGATK1 +{ + color 0.5 0.5 1.0 + size 56 + secondarySize 64 + chance 0.3 + offset 0 60 0 +} + +flickerlight PROGATK2 +{ + color 0.6 0.6 1.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 60 0 +} + +flickerlight PROGATK3 +{ + color 0.8 0.8 1.0 + size 80 + secondarySize 96 + chance 0.3 + offset 0 60 0 +} + +flickerlight PROGDTH1 +{ + color 1.0 0.4 0.0 + size 112 + secondarySize 128 + chance 0.3 + offset 0 40 0 +} + +flickerlight PROGDTH2 +{ + color 1.0 0.6 0.0 + size 128 + secondarySize 140 + chance 0.3 + offset 0 40 0 +} + +object Programmer +{ + frame PRGRH { light PROGATK1 } + frame PRGRI { light PROGATK2 } + frame PRGRJ { light PROGATK3 } + + frame PRGRN { light PROGDTH1 } + frame PRGRO { light PROGDTH2 } +} + +flickerlight BASE_X1 +{ + color 1.0 0.55 0.0 + size 96 + secondarySize 112 + chance 0.3 + offset 0 40 0 +} + +flickerlight BASE_X2 +{ + color 1.0 0.50 0.0 + size 80 + secondarySize 96 + chance 0.3 + offset 0 40 0 +} + +flickerlight BASE_X3 +{ + color 0.5 0.2 0.0 + size 64 + secondarySize 72 + chance 0.3 + offset 0 32 0 +} + +object ProgrammerBase +{ + frame BASEA { light BASE_X1 } + frame BASEB { light BASE_X2 } + frame BASEC { light BASE_X3 } +} + +// Bishop +flickerlight BISHOP +{ + color 1.0 1.0 1.0 + size 96 + secondarySize 108 + chance 0.3 + offset 0 120 0 +} + +object StrifeBishop +{ + frame MLDRE { light BISHOP } +} + +object BishopMissile +{ + frame MISS { light MISSILE } + + frame SMISA { light MISSILE_X1} + frame SMISB { light MISSILE_X2} + frame SMISC { light MISSILE_X3} + frame SMISD { light MISSILE_X4} + frame SMISE { light MISSILE_X5} + frame SMISF { light MISSILE_X6} + frame SMISG { light MISSILE_X7} +} + +// ------------------ +// - Strife Objects - +// ------------------ + +// Lights +pointlight LIGHT1 +{ + color 1.0 1.0 1.0 + size 56 + offset 0 30 0 +} + +pointlight LIGHT2 +{ + color 1.0 1.0 1.0 + size 40 + offset 0 72 0 +} + +pointlight LIGHT3 +{ + color 1.0 1.0 1.0 + size 64 +} + +pointlight LIGHT4 +{ + color 1.0 1.0 1.0 + size 64 + offset 0 80 0 +} + +pointlight LIGHT5 +{ + color 1.0 1.0 1.0 + size 56 + offset 0 72 0 +} + +pointlight CLIGHT1 +{ + color 1.0 1.0 0.0 + size 24 + offset 0 12 0 +} + +pulselight CLIGHT2 +{ + color 1.0 1.0 0.0 + size 48 + secondarySize 50 + interval 8.0 + offset 0 64 0 +} + +pulselight LLIGHT +{ + color 1.0 0.5 0.0 + size 24 + secondarySize 32 + interval 12.0 + offset 0 76 0 +} + +pulselight TLLIGHT1 +{ + color 0.9 0.9 1.0 + size 56 + secondarySize 64 + interval 3.0 + offset 0 48 0 +} + +pointlight TLLIGHT2 +{ + color 1.0 1.0 0.5 + size 80 + offset 0 56 0 +} + +flickerlight HTECH +{ + color 0.3 1.0 0.3 + size 96 + secondarySize 104 + chance 0.5 + offset 0 80 0 +} + +pulselight BCOLUMN +{ + color 0.5 1.0 0.5 + size 120 + secondarySize 128 + interval 10.0 + offset 0 64 0 +} + +pulselight FBUBBLE +{ + color 0.5 1.0 0.5 + size 60 + secondarySize 64 + interval 10.0 + offset 0 32 0 +} + +pulselight CBUBBLE +{ + color 0.5 1.0 0.5 + size 60 + secondarySize 64 + interval 10.0 +} + +pointlight SPIDLGHT1 +{ + color 0.5 1.0 0.5 + size 64 + offset 0 10 0 +} + +pointlight SPIDLGHT2 +{ + color 0.2 0.75 0.2 + size 56 + offset 0 10 0 +} + +pointlight SPIDLGHT3 +{ + color 0.0 0.25 0.0 + size 48 + offset 0 10 0 +} + +object LightSilverFluorescent +{ + frame LITS { light LIGHT1 } +} + +object LightBrownFluorescent +{ + frame LITB { light LIGHT1 } +} + +object LightGoldFluorescent +{ + frame LITG { light LIGHT1 } +} + +object LightGlobe +{ + frame LITE { light LIGHT5 } +} + +object PillarHugeTech +{ + frame HUGE { light HTECH } +} + +object Candle +{ + frame KNDL { light CLIGHT1 } +} + +object StrifeCandelabra +{ + frame CLBR { light CLIGHT2 } +} + +object CageLight +{ + frame CAGE { light LIGHT3 } +} + +object OutsideLamp +{ + frame LAMP { light LIGHT4 } +} + +object PoleLantern +{ + frame LANT { light LLIGHT } +} + +object TechLampSilver +{ + frame TECHA { light TLLIGHT1 } +} + +object TechLampBrass +{ + frame TECHB { light TLLIGHT2 } +} + +object AlienBubbleColumn +{ + frame BUBB { light BCOLUMN } +} + +object AlienFloorBubble +{ + frame BUBF { light FBUBBLE } +} + +object AlienCeilingBubble +{ + frame BUBC { light CBUBBLE } +} + +object AlienSpiderLight +{ + frame SPDLA { light SPIDLGHT1 } + frame SPDLB { light SPIDLGHT2 } + frame SPDLC { light SPIDLGHT3 } +} + +// Burning Things +flickerlight BBARREL +{ + color 1.0 0.6 0.0 + size 32 + secondarySize 40 + chance 0.8 + offset 0 32 0 +} + +flickerlight BBOWL +{ + color 1.0 0.7 0.0 + size 24 + secondarySize 32 + chance 0.5 + offset 0 10 0 +} + +flickerlight BBRAZIER +{ + color 1.0 0.8 0.0 + size 40 + secondarySize 48 + chance 0.2 + offset 0 32 0 +} + +pulselight STORCH +{ + color 1.0 0.6 0.0 + size 28 + secondarySize 32 + interval 5.0 + offset 0 56 0 +} + +pulselight MTORCH +{ + color 1.0 0.6 0.0 + size 56 + secondarySize 64 + interval 5.0 + offset 0 64 0 +} + +pulselight LTORCH +{ + color 1.0 0.8 0.0 + size 64 + secondarySize 72 + interval 2.0 + offset 0 64 0 +} + +pulselight HTORCH +{ + color 1.0 0.6 0.0 + size 72 + secondarySize 76 + interval 3.0 + offset 0 72 0 +} + +object StrifeBurningBarrel +{ + frame BBAR { light BBARREL } +} + +object BurningBowl +{ + frame BOWL { light BBOWL } +} + +object BurningBrazier +{ + frame BRAZ { light BBRAZIER } +} + +object SmallTorchLit +{ + frame TRHL { light STORCH } +} + +object MediumTorch +{ + frame LTRH { light MTORCH } +} + +object LargeTorch +{ + frame LMPC { light LTORCH } +} + +object HugeTorch +{ + frame LOGS { light HTORCH } +} + +// Power Crystal +pointlight PCRYSTAL +{ + color 1.0 1.0 0.0 + size 40 + offset 0 16 0 +} + +pointlight PCRYSTAL1 +{ + color 0.4 0.4 1.0 + size 24 + offset 0 12 0 +} + +pointlight PCRYSTAL2 +{ + color 0.5 0.5 1.0 + size 30 + offset 0 18 0 +} + +pointlight PCRYSTAL3 +{ + color 0.45 0.45 1.0 + size 32 + offset 0 24 0 +} + +pointlight PCRYSTAL4 +{ + color 0.35 0.35 1.0 + size 28 + offset 0 32 0 +} + +pointlight PCRYSTAL5 +{ + color 0.1 0.1 1.0 + size 18 + offset 0 40 0 +} + +flickerlight POWCRYS_X1 +{ + color 1.0 0.7 0.1 + size 108 + secondarySize 112 + chance 0.3 +} + +flickerlight POWCRYS_X2 +{ + color 1.0 0.75 0.2 + size 112 + secondarySize 116 + chance 0.3 +} + +flickerlight POWCRYS_X3 +{ + color 1.0 0.8 0.4 + size 116 + secondarySize 120 + chance 0.3 +} + +flickerlight POWCRYS_X4 +{ + color 1.0 0.75 0.3 + size 115 + secondarySize 117 + chance 0.3 +} + +flickerlight POWCRYS_X5 +{ + color 1.0 0.7 0.27 + size 114 + secondarySize 113 + chance 0.3 +} + +flickerlight POWCRYS_X6 +{ + color 1.0 0.65 0.24 + size 113 + secondarySize 115 + chance 0.3 +} + +flickerlight POWCRYS_X6 +{ + color 1.0 0.62 0.22 + size 112 + secondarySize 114 + chance 0.3 +} + +flickerlight POWCRYS_X7 +{ + color 1.0 0.6 0.20 + size 111 + secondarySize 113 + chance 0.3 +} + +flickerlight POWCRYS_X8 +{ + color 1.0 0.58 0.18 + size 110 + secondarySize 112 + chance 0.3 +} + +flickerlight POWCRYS_X9 +{ + color 1.0 0.56 0.16 + size 109 + secondarySize 111 + chance 0.3 +} + +flickerlight POWCRYS_X10 +{ + color 1.0 0.54 0.14 + size 108 + secondarySize 110 + chance 0.3 +} + +flickerlight POWCRYS_X11 +{ + color 1.0 0.52 0.12 + size 107 + secondarySize 109 + chance 0.3 +} + +flickerlight POWCRYS_X12 +{ + color 1.0 0.5 0.10 + size 106 + secondarySize 108 + chance 0.3 +} + +flickerlight POWCRYS_X13 +{ + color 1.0 0.48 0.10 + size 105 + secondarySize 106 + chance 0.3 +} + +flickerlight POWCRYS_X14 +{ + color 1.0 0.46 0.08 + size 103 + secondarySize 104 + chance 0.3 +} + +flickerlight POWCRYS_X15 +{ + color 1.0 0.44 0.06 + size 102 + secondarySize 104 + chance 0.3 +} + +flickerlight POWCRYS_X16 +{ + color 1.0 0.42 0.04 + size 101 + secondarySize 103 + chance 0.3 +} + +flickerlight POWCRYS_X15 +{ + color 1.0 0.4 0.02 + size 100 + secondarySize 102 + chance 0.3 +} + +flickerlight POWCRYS_X16 +{ + color 1.0 0.38 0.0 + size 99 + secondarySize 101 + chance 0.3 +} + +flickerlight POWCRYS_X17 +{ + color 1.0 0.36 0.02 + size 98 + secondarySize 100 + chance 0.3 +} + +flickerlight POWCRYS_X18 +{ + color 1.0 0.34 0.0 + size 97 + secondarySize 100 + chance 0.3 +} + +flickerlight POWCRYS_X19 +{ + color 1.0 0.32 0.0 + size 96 + secondarySize 99 + chance 0.3 +} + +flickerlight POWCRYS_X20 +{ + color 1.0 0.3 0.0 + size 95 + secondarySize 98 + chance 0.3 +} + +flickerlight POWCRYS_X21 +{ + color 1.0 0.28 0.0 + size 94 + secondarySize 93 + chance 0.3 +} + +flickerlight POWCRYS_X22 +{ + color 1.0 0.26 0.0 + size 93 + secondarySize 92 + chance 0.3 +} + +flickerlight POWCRYS_X23 +{ + color 1.0 0.24 0.0 + size 92 + secondarySize 91 + chance 0.3 +} + +flickerlight POWCRYS_X24 +{ + color 1.0 0.22 0.0 + size 90 + secondarySize 92 + chance 0.3 +} + +flickerlight POWCRYS_X25 +{ + color 1.0 0.2 0.0 + size 86 + secondarySize 90 + chance 0.3 +} + +object PowerCrystal +{ + frame CRYS { light PCRYSTAL } + + frame CRYSB { light PCRYSTAL1 } + frame CRYSC { light PCRYSTAL2 } + frame CRYSD { light PCRYSTAL3 } + frame CRYSE { light PCRYSTAL4 } + frame CRYSF { light PCRYSTAL5 } + + frame BOOMA { light POWCRYS_X1 } + frame BOOMB { light POWCRYS_X2 } + frame BOOMC { light POWCRYS_X3 } + frame BOOMD { light POWCRYS_X4 } + frame BOOME { light POWCRYS_X5 } + frame BOOMF { light POWCRYS_X6 } + frame BOOMG { light POWCRYS_X7 } + frame BOOMH { light POWCRYS_X8 } + frame BOOMI { light POWCRYS_X9 } + frame BOOMJ { light POWCRYS_X10 } + frame BOOMK { light POWCRYS_X11 } + frame BOOML { light POWCRYS_X12 } + frame BOOMM { light POWCRYS_X13 } + frame BOOMN { light POWCRYS_X14 } + frame BOOMO { light POWCRYS_X15 } + frame BOOMP { light POWCRYS_X16 } + frame BOOMQ { light POWCRYS_X17 } + frame BOOMR { light POWCRYS_X18 } + frame BOOMS { light POWCRYS_X19 } + frame BOOMT { light POWCRYS_X20 } + frame BOOMU { light POWCRYS_X21 } + frame BOOMV { light POWCRYS_X22 } + frame BOOMW { light POWCRYS_X23 } + frame BOOMX { light POWCRYS_X24 } + frame BOOMY { light POWCRYS_X25 } +} + +// Computer +pulselight COMPUTER +{ + color 0.25 1.0 0.25 + size 112 + secondarySize 128 + interval 0.25 + offset 0 64 0 +} + +object Computer +{ + frame SECRA { light COMPUTER } + frame SECRB { light COMPUTER } + frame SECRC { light COMPUTER } + frame SECRD { light COMPUTER } +} + +// Strife Explosive Barrel +flickerlight BARREL_X1 +{ + color 1.0 0.6 0.1 + size 48 + secondarySize 56 + chance 0.3 +} + +flickerlight BARREL_X2 +{ + color 1.0 0.8 0.0 + size 56 + secondarySize 64 + chance 0.3 +} + +flickerlight BARREL_X3 +{ + color 1.0 0.7 0.0 + size 72 + secondarySize 80 + chance 0.3 +} + +flickerlight BARREL_X4 +{ + color 1.0 0.6 0.0 + size 80 + secondarySize 88 + chance 0.3 +} + +flickerlight BARREL_X5 +{ + color 1.0 0.5 0.0 + size 72 + secondarySize 76 + chance 0.3 +} + +flickerlight BARREL_X6 +{ + color 1.0 0.45 0.0 + size 56 + secondarySize 60 + chance 0.3 +} + +flickerlight BARREL_X7 +{ + color 1.0 0.4 0.0 + size 52 + secondarySize 56 + chance 0.3 + offset 0 24 0 +} + +flickerlight BARREL_X8 +{ + color 1.0 0.35 0.0 + size 36 + secondarySize 40 + chance 0.3 + offset 0 40 0 +} + +flickerlight BARREL_X9 +{ + color 1.0 0.3 0.0 + size 16 + secondarySize 24 + chance 0.3 + offset 0 56 0 +} + +object ExplosiveBarrel2 +{ + frame BARTC { light BARREL_X1 } + frame BARTD { light BARREL_X2 } + frame BARTE { light BARREL_X3 } + frame BARTF { light BARREL_X4 } + frame BARTG { light BARREL_X5 } + frame BARTH { light BARREL_X6 } + frame BARTI { light BARREL_X7 } + frame BARTJ { light BARREL_X8 } + frame BARTK { light BARREL_X9 } +} + +// Alarm +pointlight KLAXON +{ + color 1.0 0.0 0.0 + size 24 +} + +object KlaxonWarningLight +{ + frame KLAXC { light KLAXON } +} + +// ------------------ +// - Strife Effects - +// ------------------ + +// Bang Cloud +object Bang4Cloud +{ + frame BNG4B { light POWCRYS_X2 } + frame BNG4C { light POWCRYS_X3 } + frame BNG4D { light POWCRYS_X4 } + frame BNG4E { light POWCRYS_X5 } + frame BNG4F { light POWCRYS_X6 } + frame BNG4G { light POWCRYS_X7 } + frame BNG4H { light POWCRYS_X8 } + frame BNG4I { light POWCRYS_X9 } + frame BNG4J { light POWCRYS_X10 } + + frame BNG4K { light HEGRENADE_X1 } + frame BNG4L { light HEGRENADE_X2 } + frame BNG4M { light HEGRENADE_X3 } + frame BNG4N { light HEGRENADE_X4 } +} + +// Fire Droplet +object FireDroplet +{ + frame FFOTA { light PHFIRE_FX8 } + frame FFOTB { light PHFIRE_FX9 } + frame FFOTC { light PHFIRE_FX10 } + frame FFOTD { light PHFIRE_FX11 } +} + +// Lighning +flickerlight ZAPBALL1 +{ + color 0.8 0.8 1.0 + size 64 + secondarySize 72 + chance 0.3 +} + +flickerlight ZAPBALL2 +{ + color 0.8 0.8 1.0 + size 128 + secondarySize 144 + chance 0.5 +} + +flickerlight LIGHTNING1 +{ + color 0.8 0.8 1.0 + size 72 + secondarySize 80 + chance 0.8 +} + +flickerlight LIGHTNING2 +{ + color 0.8 0.8 1.0 + size 80 + secondarySize 96 + chance 0.8 +} + +flickerlight LIGHT_SPT +{ + color 0.8 0.8 1.0 + size 24 + secondarySize 32 + chance 0.8 +} + +flickerlight LGNTAIL +{ + color 0.4 0.4 0.5 + size 72 + secondarySize 80 + chance 0.8 +} + +object StrifeZap1 +{ + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBase +{ + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBall1 +{ + frame ZOT3 { light ZAPBALL1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBall2 +{ + frame ZOT3 { light ZAPBALL1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBigBall1 +{ + frame ZOT7 { light ZAPBALL2 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBigBall2 +{ + frame ZOT7 { light ZAPBALL2 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningH1 +{ + frame ZAP6 { light LIGHTNING1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningH2 +{ + frame ZAP6 { light LIGHTNING1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningH3 +{ + frame ZAP6 { light LIGHTNING1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningHTail +{ + frame ZAP6 { light LGNTAIL } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningV1 +{ + frame ZOT1 { light LIGHTNING1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningV2 +{ + frame ZOT1 { light LIGHTNING1 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningSpot +{ + frame ZAP5 { light LIGHT_SPT } +} + +object SpectralLightningBigV1 +{ + frame ZOT2 { light LIGHTNING2 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +object SpectralLightningBigV2 +{ + frame ZOT2 { light LIGHTNING2 } + + frame ZAP1A { light ARROWZAP1 } + frame ZAP1B { light ARROWZAP2 } + frame ZAP1C { light ARROWZAP3 } + frame ZAP1D { light ARROWZAP4 } + frame ZAP1E { light ARROWZAP5 } + frame ZAP1F { light ARROWZAP6 } +} + +// Teleport +pointlight TFOG1 +{ + color 0.5 0.5 0.25 + size 32 + offset 0 40 0 +} + +pointlight TFOG2 +{ + color 0.5 0.5 0.25 + size 40 + offset 0 40 0 +} + +pointlight TFOG3 +{ + color 0.5 0.5 0.25 + size 48 + offset 0 40 0 +} + +pointlight TFOG4 +{ + color 0.5 0.5 0.25 + size 56 + offset 0 40 0 +} + +pointlight TFOG5 +{ + color 0.5 0.5 0.25 + size 64 + offset 0 40 0 +} + +pointlight TFOG6 +{ + color 0.5 0.5 0.25 + size 72 + offset 0 40 0 +} + +object TeleportFog +{ + frame TFOGA { light TFOG1 } + frame TFOGB { light TFOG2 } + frame TFOGC { light TFOG3 } + frame TFOGD { light TFOG4 } + frame TFOGE { light TFOG5 } + frame TFOGF { light TFOG6 } +} \ No newline at end of file